Presentation is loading. Please wait.

Presentation is loading. Please wait.

L EC. 02: D ATA T YPES AND O PERATORS (2/2) Fall. 2014 0 Java Programming.

Similar presentations


Presentation on theme: "L EC. 02: D ATA T YPES AND O PERATORS (2/2) Fall. 2014 0 Java Programming."— Presentation transcript:

1 L EC. 02: D ATA T YPES AND O PERATORS (2/2) Fall Java Programming

2 C ONTENT  Data types  Literals  Variable declaration and initialization  Scope rules  Operators  Expressions  Type conversion and casting  Wrapper classes for primitive types Fall Java Programming

3 O PERATORS  An operator is a symbol that tells computers to perform a specific mathematical or logical manipulation.  An operator takes one or more arguments, called operands ( 運算元 ), and produces a value with possible side effect (i.e. changing the content of the operands).  An operand may be either a variable, a literal or an expression.  An operator is called unary operator ( 一元運算子 ) if it takes only one operand.  An operator is called binary operator ( 二元運算子 ) if it takes exactly two operands.  There are 5 categories of operators, including 44 different operators provided, by Java language.  Assignment  Arithmetic  Bitwise logic and shift  Boolean (logic)  Relational Fall Java Programming

4 O PERATOR TABLE Fall Java Programming Operators ~! (type) * / % > >>> = instanceof == != & ^ | && || ?: = op= Comments Unary operators Multiply, divide, remainder Add, subtract, add string Shift ( >>> is zero-fill shift) Relational, type compare Equality Bit/logical AND Bit/logical exclusive OR Bit/logical inclusive OR Logical AND Logical OR Conditional operator Assignment operators precedence Assoc. R L L L L L L L L L L R R

5 EXPRESSIONS  An expression is a construct made up of literals, variables, operators, method invocations and expressions, which are constructed according to the syntax of the language.  Examples  2  counter  System.out.println()  2 + counter * var  (2 + counter ) * var Fall Java Programming

6 E VALUATING EXPRESSIONS  When an expression in a program is evaluated (executed), the result denotes one of three things:  A variable (i.e. the starting address of a memory space) Explaining it when we introduce the assignment operator and the command new  A value Examples The result denoted by is a value 5. The result a variable is the content of the variable.  Nothing (the expression is said to be void) For example, the result denoted by System.out.println() is nothing. An expression resulting nothing cannot be combined with other expression.  The type of an expression is the type of the result obtained by evaluating the expression. Fall Java Programming

7 P RECEDENCE AND ASSOCIATION  In an expression the ordering of executing operators is determined by the precedence ( 優先權 ) and association ( 組合 ) of operators.  The operators in parentheses are executed first.  The operator with higher precedence is executed prior to the one with lower precedence.  For operators with the same precedence, they are executed from left to right if the association is left-to- right.  For operators with the same precedence, they are executed from right to left if the association is right-to- left. Fall Java Programming

8 E XAMPLES OF EXPRESSION EVALUATION  “5 + 3 * 2” results in 11, instead of 16.  “(5 + 3) * 2 ” results in 16, instead of 11.  “8 / 4 / 2 ” results in 1, instead of 4.  “8 / (4 / 2) ” results in 4, instead of 1.  “5 – 3 – 2 ” results in 0, instead of 4.  “5 – (3 – 2) ” results in 4, instead of 0. Fall Java Programming

9 A RITHMETIC OPERATORS  Arithmetic operators perform arithmetic operations on all types of primitive data types, except boolean data type.  All the arithmetic operators cannot perform actions on operands with different data types.  Java will automatically convert the data types of the operands to the same data type before the operator is performed.  The process of conversion is called numeric promotion.  Numeric promotion includes:  Identity conversion: converting a type to that same type  Widening primitive conversion: explaining on next slide  Unboxing conversion: explaining later Fall Java Programming

10 W IDENING PRIMITIVE CONVERSION  There are 19 widening primitive conversion.  byte to short, int, long, float, or double  short to int, long, float, or double  char to int, long, float, or double  int to long, float, or double  long to float or double  float to double  Widening primitive conversion is legal. Fall Java Programming

11 C OMPILE - TIME CONSTANT EXPRESSIONS  A compile-time constant expression is an expression which is composed of the following components.  Primitive-type and String literals  Constant variables A constant variable is a variable declared with the keyword final. A constant variable can appear as the left-hand operand of assignment operator no more than once.  All the operators except ++, --  Casting (explaining later)  Evaluating constant expressions can be done in compilation time.  Examples  true  (short)(1*2*3*4*5*6)  Integer.MAX_VALUE / * Math.PI  "The integer " + Long.MAX_VALUE + " is mighty big." Fall Java Programming

12 T ABLE OF THE TYPES OF OPERATION RESULTS Fall Java Programming Data type of op1Data type of op2Result data types Byte, Character, Short byte, char, short Short, shortshort Byte, Character, Short, Integer byte, char, short, int Integer, intint Byte, Character, Short, Integer byte, char, short, int Long, longlong Byte, Character, Short, Integer, Long byte, char, short, int, long Float, floatfloat Byte, Character, Short, Integer, Long, Float byte, char, short, int, long, float Double, doubledouble

13 E XAMPLES OF ARITHMETIC OPERATORS Fall Java Programming SymbolsOperationExampleResultComment +add The data type of the result is int The data type of the result is double. –subtract7 – 8 The data type of the result is int. 7.0 – 8 *multiply7 * * /divide7 / 80The result is truncated to zero, since it must be int type. 7.0 / The data type of the result is double. %remainder8 % 71 –8.0 % 7–1.0

14 E XAMPLES OF ARITHMETIC OPERATORS Fall Java Programming SymbolsOperationExampleResultThe value of x after execution +positive+ x77 –negative– x-77 ++Increment by 1++x88 x Decrement by 1--x66 x--76 Assume that x has an int value 7.

15 R EMAINDER OPERATOR  The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.  It accepts both integral and floating-point operands.  For integral operands  If the result of a % b is c, then (a/b)*b+c is equal to a.  If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.  For floating-point operands (both operands not infinity, 0 and NaN)  If the result of a % b is c, then (a/b)*b+c is equal c = a – (b * q) where q is equal to the floor of a/b.  No exception will be thrown under all conditions. Fall Java Programming

16 E XAMPLES OF % OPERATOR Fall Java Programming ExpressionResult 5 % 32 5 % (-3)2 (-5) % 3-2 (-5) % (-3) % % (-3.0)2.0 (-5.0) % (-5.0) % (-3.0)-2.0

17 I NCREMENT AND DECREMENT  ++ and -- operator performs increment and decrement by 1 operation on its operand.  Both operators change the content of its operand.  In an expression, if an increment or decrement operator precedes its operand, Java will perform the corresponding operation prior to obtaining the operand’s value for use by the rest of the expression.  Example: int x = 10; y = ++x; will set the content of y to 11.  In an expression, if an increment or decrement operator follows its operand, Java will obtain the operand’s value before incrementing or decrementing it.  Example: int x = 10; y = x--; will set the content of y to 10. Fall Java Programming

18 R ELATIONAL OPERATORS  A relational operator is used to compare the values of its two operands.  The result of a relational operator is a boolean value.  The relational operators include >, =, <=, ==, and !=.  Except == and !=, the relational operators are not applicable to boolean type.  Notes for == and != operators  These two operators compare the content of the memory associated with the operands. Fall Java Programming

19 L OGICAL OPERATORS  Logical operators are only applicable to boolean type.  There are 4 Logical operators.  Logic OR: | and || || is a short-cut logical operator since whenever the left operand is true, the right operand will not be evaluated. | is not a short-cut operator where both operands will be evaluated.  Logic AND: & and && && is a short-cut logical operator since whenever the left operand is false, the right operand will not be evaluated. & is not a short-cut operator where both operands will be evaluated.  Logic NOT: !  Logical exclusive OR: ^ Fall Java Programming

20 Fall Java Programming 19 boolean trueFlag = true; boolean falseFlag = false; boolean vBoolean; int vInt = 10; vBoolean = trueFlag || ++vInt > 10; System.out.println(vInt); vBoolean = falseFlag || ++vInt > 10; System.out.println(vInt); boolean trueFlag = true; boolean falseFlag = false; boolean vBoolean; int vInt = 10; vBoolean = trueFlag | ++vInt > 10; System.out.println(vInt); vBoolean = falseFlag | ++vInt > 10; System.out.println(vInt); Output: Output: boolean trueFlag = true; boolean falseFlag = false; boolean vBoolean; int vInt = 10; vBoolean = trueFlag && ++vInt > 10; System.out.println(vInt); vBoolean = falseFlag && ++vInt > 10; System.out.println(vInt); boolean trueFlag = true; boolean falseFlag = false; boolean vBoolean; int vInt = 10; vBoolean = trueFlag & ++vInt > 10; System.out.println(vInt); vBoolean = falseFlag & ++vInt > 10; System.out.println(vInt); Output: 11 Output: 11 12

21 A SSIGNMENT OPERATOR  The assignment operator is the single equal sign, =.  Syntax form = expression;  The assignment operator sets the content of the variable to the result of evaluating the expression.  The type of must be compatible with the type of expression.  Compatible means that one of the identity, widening primitive, unboxing and boxing conversion is applicable.  The result of executing the assignment operator is the value set to the variable.  a = b = c = 3 + 4; sets the contents of a, b and c to 7. Fall Java Programming

22 S HORTHAND ASSIGNMENTS  Java provides shorthand assignment operators (compound assignments) with the form op= to simplify the coding of certain assignment statements.  Shorthand assignments are implemented more efficiently by the Java run-time system.  A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.  Java provides shorthand operators for all the binary operators.  An operator operates on two operands is called binary operator. Fall Java Programming

23 S HORTHAND ASSIGNMENTS  Examples  “ var += 3 * counter” is equivalent to “ var = var + (3 * counter) ”.  “ var *= 3 + counter” is equivalent to “ var = var * (3 + counter) ”.  The following two program segments are equivalent so there is no compilation error for the left. Fall Java Programming short x = 3; x += 4.6; short x = 3; x = (short) (x + 4.6); ≡

24 T YPE CONVERSION  When a value is assigned to a variable, the type of value must be compatible to the type of variable.  Before assigning a value to a variable, the type of the value will be automatically converted to the type of the variable if they are compatible.  If the type of the value is not compatible to the type of the variable, a compilation error occurs.  Example: “ boolean flag = 2; ” will result in an error.  Example: “ int var = 2 > 10; ” will result in an error.  Example:“ byte b = v1; ” will result in an error if v1 is not byte.  Example:“ byte b = v1 + 2; ” will result in an error even if v1 is byte.  Example: “ byte b = 2 + 3; ” will NOT result in an error.  Example: “ long var = 2 + v1; ” will NOT result in an error if v1 is not float or double.  Example: “char ch1 = ‘X’, ch2; ch2 = ++ch1;” will not result in an error.  Example: “char ch1 = ‘X’, ch2; ch2 = ch1 + 1;” will result in an error. Fall Java Programming

25 C ASTING  Casting conversion converts the type of an expression to a type explicitly specified by a cast operator.  Using cast to force type conversion may result in information lost including the magnitude and/or precision.  Syntax form (target-type) expression  Example  (float) 2 / 4 → 0.5  (float) (2 /4) → 0  2.4 / 4 → 0.6  (int) 2.4 / 4 → 0  ” byte var = (byte) (v1 + 3); ” is legal even if v1 is int/float/double, but with possible information lost.  ” byte var = (byte) (v1) + 3; ” is illegal even if v1 is byte. Fall Java Programming Only 2 is converted to float The result of division is converted to float

26 W RAPPER CLASSES FOR PRIMITIVE TYPES  Each primitive data type has an associated wrapper class which represents the primitive data type as a class type.  Each primitive data type has its own operations defined in the associated wrapper class.  Each object of a wrapper class can hold only one value.  All the wrapper classes are immutable ( 不變 ) and final.  A class is immutable if the state of an object of the class cannot be changed once the object is created.  A class is final if it cannot be inherited. Fall Java Programming

27 T ABLE OF PRIMITIVE TYPES AND ASSOCIATED WRAPPER CLASSES Fall Java Programming Primitive data typeWrapper class booleanBoolean charCharacter byteByte shortShort intInteger longLong floatFloat doubleDouble

28 W HY NEED WRAPPER CLASSES  The wrapper class of a primitive type can represent a primitive type value as an object to meet the requirement of some processes.  The wrapper class of a primitive data type provides useful methods to process values of the primitive type.  The Integer class provides the following methods for processing int values.  parseInt: converting a int value in string form to a int value  toBinaryString: representing a int value in its binary form  toString: converting a int value to its string form Fall Java Programming

29 B OXING AND UNBOXING  Boxing denotes the process of creating a wrapper class object for a value of corresponding primitive data type.  Unboxing denotes the reverse process of boxing.  Java will automatically perform the boxing and unboxing as necessary.  Example int vInt = 20; Integer oInt = vInt; //autoboxing int pInt = oInt; //auto-unboxing Fall Java Programming

30 S PECIAL CASES OF BOXING AND UNBOXING  Under the following situations, the object used to wrap the value is unique.  A boolean value  A byte or a char in the range \u0000 to \u007f  an int or a short number between -128 and 127  Try the program given on next slide!  Checking the functionality of the equals method defined in the java.lang.Integer class. Fall Java Programming

31 T RY THIS … public class TestBoxing { public static void main( String args[] ) { Integer o1, o2; o1 = 120; o2 = 120; System.out.println("o1 = " + o1 + ", o2 = " + o2); System.out,ptintln(" o1 == o2: " + (o1 == o2)); System.out.println("o1.equals(o2): “ + (o1.equals(o2))); o1 = -130; o2 = -130; System.out.println("o1 = " + o1 + ", o2 = " + o2); System.out,ptintln(" o1 == o2: " + (o1 == o2)); System.out.println("o1.equals(o2): “ + (o1.equals(o2))); } Fall Java Programming

32 S TRING CONCATENATION  Concatenating two strings is to append one of the string to the end of the other.  “+” operator is overloaded and performs either of the following two operations depending on the context.  Numerical addition if both operators are of numerical data type.  String concatenation if one of the operator is of string type. The value of the other operator is automatically transformed to a string if it is not a string.  Example  The result of “TEST” is a string “33TEST”.  The result of 21 + “TEST” + 12 is a string “21TEST12”. Fall Java Programming

33 N OTES ON STRING CONCATENATION Fall Java Programming  The results of the following two code blocks are different.  Compile-time constant expressions of type String are always "interned" so as to share unique instances. String s1 = “Happy ”, s2 = “New Year”, s3 = “Happy New Year”; String s4 = s1 + s2; String s1 = “Happy ”, s2 = “New Year”, s3 = “Happy New Year”; String s4 = “Happy ” + “New Year”;

34 N OTES FOR EVALUATING EXPRESSIONS  The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.  The result of executing the following program is “j = 9” followed by “j = 18”. Fall Java Programming public class TestExpEva { public static void main(String[] args) { int i = 2, j; j = (i = 3) * i; System.out.println("j = " + j); j = i * (i = 6); System.out.println("j = " + j); } 3*6 3*3

35 N OTES FOR EVALUATING EXPRESSIONS  If the operator is a compound-assignment operator, then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.  The result of executing the following program is “i = 93”. Fall Java Programming public class TestExpEva { public static void main(String[] args) { int i = 6; i += i + (i = 9) * i; System.out.println(“i = " + i); } 6+6+9*9

36 N OTES FOR EVALUATING EXPRESSIONS  If evaluation of the left-hand operand of a binary operator completes abruptly (i.e. a run-time error occurs), no part of the right-hand operand appears to have been evaluated.  The result of executing the following program is “j = 1”. Fall Java Programming class TestExpEva { public static void main(String[] args) { int j = 1; try { int i = forgetIt() / (j = 2); } // a run-time error occurs when // evaluates left-hand operand of /, // right-hand operand of / does not // evaluate catch (Exception e) { System.out.println("j = " + j); } } static int forgetIt() throws Exception { // generating a run-time error throw new Exception("I'm outta here!"); }


Download ppt "L EC. 02: D ATA T YPES AND O PERATORS (2/2) Fall. 2014 0 Java Programming."

Similar presentations


Ads by Google