Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries.

Similar presentations


Presentation on theme: "Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries."— Presentation transcript:

1 Variables, Data Types, & Constants

2 Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries Scanner Class Math Class Arithmetic Compound Assignment Flow Charting

3 Variable Is a name for a value stored in memory Containers for values Is a name for a location in memory used to hold a data value.

4 Variable Declaration Tells the compiler to reserve a portion of main memory space large enough to hold the value. All variables must be declared with a name and a type before they can be used. –int myValue = 3; //Declared & Initialized myValue to 3 Variable can only store one value of its type at a time.

5 Assignment Statement (=) symbol is used as the assignment statement. – (=) - is known as the assignment operator. All assignments occurs from right to left. Meaning the right side of the equal sign is evaluated first and then stored to the variable on the left side. –Identifier variable = expression ; –myVariable = myValue + 3; myValue + 3 is evaluated first The result is then stored in myVariable

6 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5; a literal (5) is assigned to x x = y + 2; the value of an expression (y + 2) is assigned to x x = z; the value of another variable ( z ) is assigned to x

7 Variable Assignment A variable can store only one value at any time. int x; x = 5; x = 10; x 5 10

8 Naming Variables 1 st letter of a variable name should be lowercase. Name should consist of letters and numbers and underscore. No spaces No symbols If using two words join together, the 1 st letter of the second word should be capitalized. –myHouse, totalSum Do not use reserve or keywords

9 Reserve Reserve Words – words that have a predefine meaning –boolean, char, byte, int, short, long, float, double, void, true, false, public, private, protected, static, final, import, class, interface, extends, implements, this, super, abstract, new, if, else, for, while, do, switch, case, default, break, return, try, catch, finally, throw, throws, continue, package, native, volatile, transient, synchronized, instanceof All reserved words use only lowercase letter

10 Java Keywords abstractdoubleintstrictfp booleanelseinterfacesuper breakextendslongswitch bytefinalnativesynchronized casefinallynewthis catchfloatpackagethrow charforprivatethrows classgotoprotectedtransient constifpublictry continueimplementsreturnvoid defaultimportshortvolatile doinstanceofstaticwhile

11 Primitive Data Types or built-in data types Data type – determines the type of data the variable will store They are called primitive because data types have no properties.

12 Eight Primitive Data Types 4 kinds of Integers data types 2 kinds of floating point data types 1 character data type 1 boolean data type

13 Primitive Data Types TypeStorage Required int 4 bytes //AP EXAM double 8 bytes //AP EXAM char 2 bytes //Not on AP Exam boolean 1 bit //AP EXAM

14 Integer Data Types Use for whole numbers byte – 1 byte range –2 7 to 2 7 -1 or –128 to 127 short – 2 bytes range –2 15 to 2 15 – 1 or 32,768 to 32,767 int – 4 bytes range –2 31 to 2 31 - 1 long – 8 bytes range –2 63 to 2 63 – 1

15 Floating Points Data Types Use for real numbers (numbers with decimal). float – 4 bytes –3.4 x 10 38 to 3.4 x 10 38 double – 8 bytes –1.8 x 10 308 to 1.8 x 10 308

16 Character Data Type Used for single letters in single quotes char – 2 bytes Unicode character set (with ASCII subset)

17 Boolean Data Type Used for true or false boolean – 1 byte true or false

18 Choosing a data type It is important to choose the most appropriate type for the quantity being represented.

19 Constants Literal – A primitive value used in a program. oNumeric literal – 8, 9, 427 oString literal – “hello” Symbolic - uses the keyword final when declaring variables –final int SUM = 8; –Use all caps the distinguish constant variables from other variables. Constants are like variables, but they have the same value throughout the program. Constant can’t change their value once they are assigned a value.

20 Named Constants  A named memory location that cannot be changed from its initial value.  The keyword final is used in a constant declaration.  Constant identifiers are typically all uppercase with an underscore ( _ ) separating words within the identifier name.  Example: final double TAX = 0.08;

21 Constants Advantages Prevent accidental changing during the program run by another source. Maintenance - by changing the assignment where it is assigned. It will change throughout the program.

22 ASCII American Standard Code for Information Interchange –Represents the numeric code for each character –One Byte per character –0 to 127 Extended ASCII –128 to 255

23 Unicode Two bytes per character –ASCII is a subset of Unicode Represents 65,000 characters for most world languages

24 Import, Arithmetic, Casting, Logical Operators, Relational Operators

25 Java Packages  Numerous packages are included with JDK  Packages contain classes  Packages can be added to an application with an import statement. For example, the statement import java.util.Scanner; makes the Scanner class and its methods accessible to the application.

26 Packages Group of related classes by one name. Eamples: java.lang – java.util

27 Class Libraries Class Library – is a set of classes that supports the development of programs. The Java standard class Library is a useful set of classes that anyone can use when writing Java programs. Java APIs – Application Programmer Interfaces. Class library made up of several sets of related classes.

28 Import Declaration import – keyword used to identify packages and classes that will be used by the program. import java.util.Random; –Gains access to the Random Class import java.util.*; –Gains access to the package that contains class Random

29 java.lang.*; Automatically imported Classes in java.lang package –String –System –Double –Integer –Comparable –Math –Object –Etc.

30 java.util.*; Random ArrayList HashMap HashSet Iterator LinkedList List ListIterator Map Set TreeMap TreeSet

31 Inputting

32 Scanner Class next() nextLine() nextInt() nextDouble() nextBoolean() nextFloat() nextLong() nextShort()

33 Creating a Scanner object Scanner console = new Scanner(System.in); console is the object of Scanner console has access to all the methods using the dot operator.

34 Scanner Class Methods next() –Returns a string nextLine() –Returns a string of the entire sentence nextInt() –Returns an integer nextInt() –Returns an integer nextDouble() –Returns a double value nextBoolean() –Returns a Boolean value nextFloat() –Returns a float value nextLong() –Returns a long value nextShort() –Returns a short value

35 Inputting Char No methods for inputting chars Scanner console = new console Scanner(System.in); char dude = console.next().charAt(0); //return the char at the 0 index

36 Program import java.util.*; public class Scan{ public static void main(String args[]){ int x=0,y=0, z=0; String temp = new String(); Scanner console = new Scanner(System.in); System.out.println("Input 3 values"); x = console.nextInt(); y=console.nextInt(); z=console.nextInt(); System.out.println(x); System.out.println(y); System.out.println(z); }

37 When inputting values, do not use the enter keys between the values.

38 The Math Class  Part of the java.lang package  The random() methods generates a double between 0 and 1.0. For example, double rNum; rNum = Math.random();  A random integer in a range is generated by using the expression: (highNum – lowNum + 1) * Math.random() + lowNum

39 Math Class abs(int) or abs(double) - absolute value acos(double) – arc cos asin(double) – arc sin atan(double) – arc tan cos(double) – cosine sin(double) - sine tan(double) - tangent ceil(double) – smallest whole number greater than or equal to num exp(double) - power floor(double) – largest whole number less than or equal to num. pow(double, double) – return num raised to a power random() – 0.0 to < 1.0 sqrt(double) – square root

40 Built-in arithmetic operators * - multiplication % - modulus division / - division + - addition - - subtraction

41 Modulus Division Modulus division ( % ) returns the remainder of a division operation:

42 Compound Assignment Operators OperatorOperation += addition and then assignment -= subtraction and then assignment *= multiplication and then assignment /= division and then assignment %= modulus division and then assignment

43 Order of Precedence !, (unary) -, Cast, ++, -- *, /, % +, -, =, ==, != && || In the absence of parentheses, binary operators of the same rank are performed left to right, and unary operators right to left. If in doubt use parentheses!

44 Parentheses Operations inside of parentheses are evaluated first. The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division: Example: –6 + 4 * 2 – 1 // 13 –(6 + 4) * (2 – 1) // 10 –(5 + 6) * 4 / 2 // 22

45 Type promotion (implicit conversion) Occurs when using a math expression of different data types. Example: int + double will return a double and the int will be promoted to a double by the compiler automatically. You will need to have a double data type to store the result. If you try to store it in an int memory location, you will get a loss of precision error.

46 +, -, *, % Will return the data type of the operand if they of same data type. Mixed mode operands will use type promotion to determine the data type that will be return. Can’t % by a 0 –5 % 0; Can 0%8 = 0

47 Mixed Mode Operands int + int  int int + double  double double + double  double int * int  int int *double  double double * double  double int / int  int int / double  double double / double  double Just as long as one of the operand is a double, the other operand will be promoted up and result will be a double.

48 / division Must be careful when working with division. int/int will return an int and the remainder is dropped. One or both of the sides of the division must be a double to return a double Can’t divide by 0 example 5/0; Can 0/5 = 0;

49 Real Division Real division ( / ) is performed when one or both operands are type double. The entire quotient, including the decimal portion is returned: double result; result = 20.0/7.0;//result is 2.857

50 Integer Division Integer division ( / ) is performed when both operands are integers. Only the integer portion of the quotient is returned:

51 Division & Modulus Can use if statement to eliminate errors if(x != 0) 8 / x Eliminates any errors if x = 0;

52 Casting or Type Casting Converts a value Data Type temporary to another type. Examples: int x, i = 2; double d = 3.7; x = i * (int) d; // d is explicitly cast Type casting is necessary in this case because one of the operands has less precision than the variable that will store the result. Explicit casting also makes it clear that the programmer intended for the calculation result to be an int.

53 Type Casting Type Casting converts a number of one type to a number of a different, but compatible type. Type casting is used to: 1.make the operand types in an expression match. For example, wholeNum = (int)y * 2 2.truncate the decimal portion of a double. For example, wholeNum = (int)z 3.change the way in which a division ( / ) operation will be performed. For example, realDivision = (double)a / (double)b

54 Casting real division Casting is useful when real division with integers is preferred result = (double) 8/ (double) 5; //explicitly result = (double) 8/ 5; // explicitly & implicitly Java will implicitly type cast operands in a mixed expression to match the precision of the variable storing the value. Although explicitly type casting is not necessary, it is better programming style to include casts. Casting makes the programmer’s intentions clear and makes bugs easier to find.

55 Truncate Casting a double to an int truncates the decimal portion of the number.

56 Rounding Rounding can be simulated when casting a double to an int by adding.5 to the number before the casting. x = i * (int)(d + 0.5);

57 Abstract Data Types A variable declared with a class is called an object. For example, the object spot is type Circle: Circle spot = new Circle(4);spot getRadius() area()

58 Programming Errors  Syntax errors violate the rules of Java.  Logic errors, also called semantic errors, occur in statements that are syntactically correct, but produce undesired or unexpected results.  Run-time errors, also called exceptions, halt program execution at the statement that cannot be executed. One type of exception is called InputMismatchException.

59 Flowchart Symbols process

60 The BirthdayGame Flowchart


Download ppt "Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries."

Similar presentations


Ads by Google