Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CHAPTER 2-2 DATA TYPES Java provides 8 basic data types: o Numeric types Integral types: byte, short, int, and long Floating types: float and double o Non-numeric types Character type: char Boolean type: boolean Integral data types --------------------------------------------------------------------------------------------------------------------Data type size in bits range of values byte 8 -128 to127 (-27 to 27-1) short 16 -32,768 to 32,767 (-215 to 215-1) int 32 -2,147,483,648 to 2,147,483,647 (-231 to 231-1) long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (-263 to 263-1) --------------------------------------------------------------------------------------------------------------------Figure 2-2-1. The basic integral data types of Java. A literal is a constant value that appears directly in the program. An integer literal such as 302 is assumed to be of type int. To denote an integer literal of type long, append it with the letter L or l. An integral constant cannot have commas, as in 1,000. It can optionally be preceded by the + or – symbol to denote the sign, as in +7 or -2. //Example 2-2-1 //Demo.java public class Demo { public static void main(String[] args) { byte byteVar=3; short shortVar=21; int intVar=315; long longVar=123456789123L; System.out.println(byteVar); System.out.println(shortVar); System.out.println(intVar); System.out.println(longVar); } } //line 7 //line 8 //line 9 //line 10 //line 11 //line 12 //line 13 //line 14 Walkthrough: Lines 7-10 are data definition statements. After these 4 lines are executed, the data structure of the program has the following state: byteVar: 3 shortVar: 21 intVar: 315 longVar:123456789123 Lines 11-14 print the values of byteVar (3), shortVar (21), intVar (315), and longVar (123456789123) on the screen. Note: After line 14 is done, method main finishes and it returns control to its caller (the JVM). When a method returns, the computer performs the following 2 actions: o Destroys the data structure of the method since it is of no use any more (after all, its associated algorithm has finished). o Returns control and possibly a value to the method's caller. The set of memory locations of the data structure of a method created when the method executes is called an ________________________. Integral overflow //Example 2-2-2 //Demo.java public class Demo { public static void main(String[] args) { int num= 1000000000; num = num*4; System.out.println (num); } } //line 7 //line 8 //line 9 The floating data types --------------------------------------------------------------------------------------------------------------------Data type size in bits range of values significant digits float 32 -3.4*1038 to 3.4*1038 7 double 64 -1.7*10308 to 1.7*10308 14 --------------------------------------------------------------------------------------------------------------------Figure 2-2-2. The floating data types of Java. Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. Like an integer constant, a floating constant cannot have commas, and it can be preceded optionally by the symbol + or – to denote the sign. Floating-point literals can also be specified in scientific notation. For example, 1.23456e+2 (we can use E or e) is equivalent to ____________, and 1.23456e-2 is equivalent to ________________. //Example 2-2-3 //Demo.java public class Demo { public static void main(String[] args) { float x=123.2345F; double y=123.23456789; System.out.println(x); System.out.println(y); //line 7 //line 8 //line 9 //line 10 } } Floating overflow Suppose the data item x belongs to a floating data type. If we put a value outside the range of values supported by the floating data type of x into location x at run time, it results in a ___________________. For the data type double, the range of supported values is very large. Thus, in practice, real number overflow is not a problem that a programmer worries about everyday. The precision problem //Example 2-2-4 //Demo.java public class Demo { public static void main( String[] args) { float x=123.23456789F; double y=123.23456789; System.out.println(x); System.out.println(y); } } //line 7 //line 8 //line 9 //line 10 Integral arithmetic operators Java provides the following integral arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), modulus (%) for working with integral basic type values. Each of these operators takes ____ operands. These operators are integral because their operands must be ___________ and the result of an arithmetic expression involving each of them is ___________. None of these operators produce any side effects. The - symbol is overloaded to also mean negation. The negation operator takes ___ operand and it produces no side effects. //Example 2-2-5 //Demo.java public class Demo { public static void main( String[] args) { int n1=42, n2=10; System.out.println(n1+"+"+n2 +"=" +(n1+n2)); System.out.println(n1+"-"+n2 +"=" +(n1-n2)); System.out.println(n1+"*"+n2 +"=" +(n1*n2)); System.out.println(n1+"/"+n2 +"=" +(n1/n2)); System.out.println(n1+"%"+n2 +"=" +(n1%n2)); System.out.println("-"+n1+"=" +(-n1)); } } //line 7 //line 8 //line 9 //line 10 //line 11 //line 12 //line 13 The modulus Operator % //Example 2-2-6 //Demo.java public class Demo { //Prints the sum of the 3 digits of a 3-digit number (e.g. the output for the number 123 is 6) public static void main(String[] args) { int num=385; int sum= ones+tens+hundreds; System.out.println("For the number 385, the sum is "+sum); } } //Example 2-2-7 //Demo.java public class Demo { //Prints hours, minutes, and seconds given total seconds public static void main(String[] args) { int totalSeconds = 5000; System.out.println(totalSeconds + " seconds = " + hours + " hours " + minutes + " minutes " + seconds + " seconds"); } } Floating arithmetic operators The symbols +, -, *, /, and % are overloaded to work with floating-point operands. In particular, Java provides the following floating arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and negation (-). These operators are floating operators because their operands must be of a _____________ type, and the result of an arithmetic expression involving each of them is of a ___________ type. The floating point % returns the remainder after dividing the dividend by the divisor a whole number of times. None of these operators produce any side effects. //Example 2-2-8 //Demo.java public class Demo { public static void main(String[] args) { double n1=5.0, n2=2.0; System.out.println(n1+"+"+n2 +"=" +(n1+n2)); System.out.println(n1+"-"+n2 +"=" +(n1-n2)); System.out.println(n1+"*"+n2 +"=" +(n1*n2)); System.out.println(n1+"/"+n2 +"=" +(n1/n2)); System.out.println(n1+"%"+n2 +"=" +(n1%n2)); System.out.println("-"+n1+"=" +(-n1)); } } The assignment operator revisited An assignment expression using the assignment operator has the following syntax: identifier = expr The left operand (identifier) must be a ___________, and the right operand (expr) must be an expression that returns a value of the same type as ___________. When the computer executes an assignment expression, it performs the following actions: 1. Evaluates expr. 2. Assigns the value evaluated in step 1 to identifier. 3. Returns the value assigned to identifier to the caller. Is the following statement legal? x=(y=99); The updating assignment operators In addition to the assignment operator, Java provides the following updating assignment operator: +=, -=, *=, /=, and %=. An updating assignment expression has the following syntax (op can be +, -, *, /, or %): identifier op= expr The updating assignment operator op= takes 2 operands. The left operand (identifier) must be a _____________, and the right operand (expr) must be an expression that returns a value of the same type as _____________. The updating assignment expression is equivalent in semantics to the following expression: identifier = identifier op expr In other words, when the computer executes an updating assignment expression identifier op= expr, it performs the following actions: 1. Evaluates identifier op expr. 2. Assigns the value evaluated in step 1 to identifier. 3. Returns the value assigned to identifier to the caller. //Example 2-2-9 //Demo.java public class Demo { public static void main( String[] args) { int x=2, y=0; y = (x+=3); System.out.println("x is "+x ); System.out.println("y is "+y ); } } //line 7 //line 8 //line 9 //line 10 The prefix increment and decrement operators The prefix increment operator ++ takes 1 operand of any numeric type. The syntax of a prefix increment expression is: ++ identifier The operand of the ++ operator (identifier) must be a _____________. The semantics of the prefix increment expression are as follows: 1. Increments the value of identifier by 1. 2. Returns the value of identifier after the increment. The prefix decrement operator -- takes 1 operand of any numeric type. The syntax of a prefix decrement expression is: -- identifier The operand of the -- operator (identifier) must be a _____________. The semantics of the prefix decrement expression are as follows: 1. Decrements the value of identifier by 1. 2. Returns the value of identifier after the decrement. //Example 2-2-10 //Demo.java public class Demo { public static void main( String[] args) { int x=2, y=0; y = ++x; System.out.println("x is "+x ); System.out.println("y is "+y ); x = --y; System.out.println("x is "+x ); System.out.println("y is "+y ); } } //line 7 //line 8 //line 9 //line 10 //line 11 //line 12 //line 13 The postfix increment and decrement operators Java allows the increment operator and the decrement operator to be used in their postfix form, as in x++ and x--, with a slightly different semantics. In particular, ++x and x++ produce the same side effect, namely, x is incremented by 1. The difference between these 2 forms is that ++x returns the value of x __________the increment, whereas x++ returns the value of x ___________the increment. The difference between --x and x-- is similar. //Example 2-2-11 //Demo.java public class Demo { public static void main( String[] args) { int x=2, y=0; y= x++; System.out.println("x is "+x ); System.out.println("y is "+y ); x=y--; System.out.println("x is "+x ); System.out.println("y is "+y ); //line 7 //line 8 //line 9 //line 10 //line 11 //line 12 //line 13 } } The data type boolean --------------------------------------------------------------------------------------------------------------------Data type size in bits range of values boolean 1 true, false ------------------------------------------------------------------------------------------------ --------------------Figure 2-2-3. The boolean data type of Java. //Example 2-2-12 //Demo.java public class Demo { public static void main(String[] args) { boolean flag=true; //line 7 System.out.println(flag); //line 8 } } Relational operators Java provides the following relational operators: < (less than), > (greater than), == (equal), != (not equal), <= (less than or equal), and >= (greater than or equal). Each of these operators takes 2 operands which must be of the same type in which all legal values of such a type must have an ordering defined on them so that the values can be compared. An expression involving a relational operator is called a _____________________. A relational expression is of type ___________ and returns a ___________ value. None of these relational operators produce any side effects. //Example 2-2-13 //Demo.java public class Demo { public static void main( String[] args) { boolean flag=true; flag= (5>7); System.out.println( flag ); flag= (5!=7); System.out.println( flag ); } } //line 7 //line 8 //line 9 //line 10 //line 11 Logical operators (short-circuit) Java provides the following logical operators: && (and), || (or), ^ (exclusive or), and ! (not). Each of the first 3 operators (&&, ||, and ^) takes 2 operands which must both be of type ___________. The last operator ! takes 1 operand which must be of type ___________. An expression involving a logical operator is called a _____________________. A logical expression is of type ___________ and returns a ___________ value. None of these logical operators produce any side effects. Note that in English "or" means "exclusive or". -----------------------------------------------------------------------------------------------------------------Oper1 Oper2 Oper1&&Oper2 Oper1||Oper2 Oper1^Oper2 !Oper1 true true true true false false true false false true true false false true false true true true false false false false false true -----------------------------------------------------------------------------------------------------------------Figure 2-2-4. The semantics of the logical operators &&, ||, ^, and !. //Example 2-2-14 //Demo.java public class Demo { public static void main( String[] args) { System.out.println((3<4)&&(2<1)); System.out.println((3<4)||(2<1)); System.out.println((3<4)^(2<1)); System.out.println(!(3<4)); } } //line 7 //line 8 //line 9 //line 10 Note: The operators && and || are short-circuit logical operators. When Java evaluates a logical expression involving a short-circuit logical operator, Java will stop the evaluation as soon as the value of the logical expression is known. Normally, whether oper2 is evaluated or not makes no difference. However, if oper2 is an expression that produces ___________, then whether oper2 is evaluated or not makes a big difference. //Example 2-2-15 //Demo.java public class Demo { public static void main( String[] args) { int i=3; System.out.println((3<4)||(3<i++)); System.out.println(i); } } //line 7 //line 8 //line 9 Non-short-circuit logical operators Java provides 2 additional logical operators & and |, which work exactly the same as && and || respectively except that & and | are non-short-circuit logical operators. //Example 2-2-16 //Demo.java public class Demo { public static void main( String[] args) { int i=3; System.out.println((3<4)|(3<i++)); //line 7 //line 8 System.out.println(i); //line 9 } } The data type char Java programs are intended to execute worldwide on many types of computer systems. Thus, Java designers adopted the Unicode standard, which describes the specifications to produce consistent encoding of the world's characters and symbols. --------------------------------------------------------------------------------------------------------------------Data type size in bits range of values char 16 The 65536 characters defined by the Unicode standard --------------------------------------------------------------------------------------------------------------------Figure 2-2-5. The char data type of Java. We can represent a char constant in a Java program by enclosing the character we want within single quotes, provided that we can indeed enter such a character from the keyboard without it being interpreted differently by the computer. For example, the data item that represents the uppercase letter A is represented by the char constant _____. To represent hard-to-get characters in a Java program, Java has pre-defined many ______________. --------------------------------------------------------------------------------------------------------------------Escape sequence character represented \n or \u000A newline \b or \u0008 backspace \t or \u0009 tab \\ or \u005C backslash \r or \u000D carriage return \' or \u0027 single quote \" or \u0022 double quote --------------------------------------------------------------------------------------------------------------------Figure 2-2-6. Some escape sequences defined in Java. To denote the char constant that represents the backspace character in a Java program, we write ____. To include the backspace character in a String, we simply insert the escape sequence, as in "Hello\bYou". In particular, the 65536 Unicode characters are ordered, and the first character is encoded by the bit string that represents the integer 0, the second character is encoded by the bit string that represents the integer 1, the third character is encoded by the bit string that represents the integer 2, and so on. Based on this integer encoding, Java also allows us to represent a character constant by its corresponding integer value expressed in base 16 (hexadecimal) using the escape sequence '\udddd'. For example, the character '1' is the 50th character in the Unicode character set. Thus, to represent the character '1' , we can also use ___________. //Example 2-2-17 //Demo.java public class Demo { public static void main( String[] args) { char x='0', y='0'; x='1'; y='\u0031'; System.out.println("x is "+x+"\ny is "+y); //line 7 //line 8 //line 9 //line 10 } } Note: The constants 1, '1', and "1" are very different data items. The constant 1 is an _____, the constant '1' is a _____, and the constant "1" is a _______. Their internal representations in binary are all ___________. The Unicode character set has adopted the ASCII character set (an older 7-bit character encoding standard) as its subset, providing support for the basic western alphabet including A-Z, a-z, 0-9, and various symbols found on a western keyboard. In particular, '\u0000' to '\u007F' (0 to 127) corresponds to the 128 ASCII characters. --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------Figure 2-2-7. ASCII character set in Hex. Class String The char type only represents one character. To represent a string of characters, use the data type called ___________. String is a predefined class in the Java library. It is known as a ___________. //Example 2-2-18 //Demo.java public class Demo { public static void main( String[] args) { String s1 = "Welcome to Java"; String s2 = "Welcome " + "to " + "Java"; String s3 = "Chapter" + 2; String s4 = "Supplement" + 'B'; int k = Integer.parseInt("123"); double d =Double.parseDouble("123.45"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); System.out.println(k); System.out.println(d); } } Precedence of operators --------------------------------------------------------------------------------------------------------------------(), [], ., postfix ++, postfix -unary +, unary -, prefix ++, prefix -(type) casting ! * / % + < <= > >= == != & ^ | && || =, +=, -=, *=, /=, %= --------------------------------------------------------------------------------------------------------------------Figure 2-2-8. Partial table of operator precedence listed from high to low. //Example 2-2-20 //Demo.java public class Demo { public static void main( String[] args) { int j=3; System.out.println(j+=4+5*2); } } //line 7 //line 8 Associativity of operators In Java, all binary operators except the assignment operators are left associative (left to right). All the assignment operators are right associative (right to left). In Java, some unary operators are left associative (postfix ++), some are right associative (e.g. prefix ++, unary -). Convert mathematical expressions to Java 52 9 52 93 1 2 1<=x<=10 3 4 x 10( y 5)( a b c) 4 9 x 9( ) 5 x x y Case Study -- Fahrenheit to Celsius Write a program that converts a Fahrenheit degree to Celsius using the formula: celsius ( 95 )( fahrenheit 32) //Example 2-2-21 //FahToCel.java public class FahToCel { //Output:86 degree Fahrenheit converted to degree Celsius and printed on the screen public static void main(String[] args) { } } Programming exercises 1. Write a console application which converts total ounces to gallons, quarts, and ounces and prints the answer on the screen. For example: Your program can initialize totalOunces to any integer you want. However, the code must work without change if the initial value of totalOunces is changed to another number. Hint: 1 gallon=4 quarts 1 quart =32 ounces You must write the API for method main. API stands for Application Programmer Interface, which refers to the comment header block that is required for each method. In addition, you must include the following comment at the top of the program //Your name //Your email address //GallonsQuartsOunces.java Note: Your program must follow the good software engineering practices discussed (naming, layout, user-friendly, avoid unnamed constants, documentation). 2. Write a console application which converts total ounces to tons, pounds, and ounces and prints the answer on the screen. For example: Your program can initialize totalOunces to any integer you want. However, the code must work without change if the initial value of totalOunces is changed to another number. Hint: 1 ton=2000 pounds, 1 pound=16 ounces You must write the API for method main. In addition, you must include the following comment at the top of the program //Your name //Your email address //TonsPoundsOunces.java Note: Your program must follow the good software engineering practices discussed (naming, layout, user-friendly, avoid unnamed constants, documentation). 3. Write a console application which prints the volume of a sphere with radius 5.3 on the screen. You must write the API for method main. In addition, you must include the following comment at the top of the program //Your name //Your email address //VolumeOfSphere.java Hint: The formula for the volume of a sphere is: 4 r 3 3 Remember to test your program. Note: Your program must follow the good software engineering practices discussed (naming, layout, user-friendly, avoid unnamed constants, documentation). 4. Write a console application which converts 32 degree Celsius to degree Fahrenheit and prints the answer on the screen. You must write the API for method main. In addition, you must include the following comment at the top of the program //Your name //Your email address //CelToFah.java Hint: The formula to convert degree Celsius to degree Fahrenheit is: cel * 9 32 5 5. Write a console application which converts 356 inches to yards, feet, inches and prints the answer on the screen. For example, 40 inches will be converted to 1 yard, 0 feet, 4 inches. You must write the API for method main. In addition, you must include the following comment at the top of the program //Your name //Your email address //InchesToYdFtIn.java Hint: 1 foot =12 inches 1 yard =3 feet