Unit 2 Lesson 8 - Operators and Expressions
Lesson summary and assignments
A detailed explanation of all Java operators can be found at Operators in Java
In the following code:
1. byte smallInt = 75;
2. int largeInt = 5280;
3. float smallDecimal = 3645.042 + smallInt + LargeInt;
4. double largeDecimal = smallDecimal * 678765675.665765;
In line 3, smallInt is first coerced (promoted) to float and added to 3645.042. LargeInt is then coerced (promoted) to float and added to the previous result. Finally, that final result of the compound expression on the right side of the equals operater is then assigned to the smallDecimal.
In line 4, smallDecimal is first coerced (promoted) to type double before adding it to 678765675.665765. The result is then moved into largeDecimal.
The diagram below shows what coercions/conversions can be accomplished. The solid arrows are always accomplished without loss of precision. The dashed arrows indicate that some of the right most digits may be lost (replaced by zeros) in the conversion if the original number is too large.
Java Operator Precedence Table
Precedence | Operator | Type | Associativity |
---|---|---|---|
15 | () [] ยท |
Parentheses Array subscript Member selection |
Left to Right |
14 | ++ -- |
Unary post-increment Unary post-decrement |
Left to Right |
13 | ++ -- + - ! ~ ( type ) |
Unary pre-increment Unary pre-decrement Unary plus Unary minus Unary logical negation Unary bitwise complement Unary type cast |
Right to left |
12 | * / % |
Multiplication Division Modulus |
Left to right |
11 | + - |
Addition Subtraction |
Left to right |
10 | << >> >>> |
Bitwise left shift Bitwise right shift with sign extension Bitwise right shift with zero extension |
Left to right |
9 | < <= > >= instanceof |
Relational less than Relational less than or equal Relational greater than Relational greater than or equal Type comparison (objects only) |
Left to right |
8 | == != |
Relational is equal to Relational is not equal to |
Left to right |
7 | & | Bitwise AND | Left to right |
6 | ^ | Bitwise exclusive OR | Left to right |
5 | | | Bitwise inclusive OR | Left to right |
4 | && | Logical AND | Left to right |
3 | || | Logical OR | Left to right |
2 | ? : | Ternary conditional | Right to left |
1 | = += -= *= /= %= |
Assignment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment |
Right to left |
Larger number means higher precedence.
Source: Bilkent University Comp Sci 101
Answers
Vocabulary
- compound assignment operator
- shortcut syntax to perform an operation on both operands and assign the result into the variable on the left
- compound expression
- a combination of expressions
- concatenation
- when two Strings are joined together
- expression
- a combination of data and operators that evaluates to a single value
- operand
- the data that is operated on
- truncate
- to cut off data from the end