Assignment and Data Conversion with Arithmetic Operators
Basic facts on assignment and conversion
- Fact: Variables and values ALWAYS have a TYPE
- Primitive types: byte, short, int, long, float, double,
char, boolean
-
Fact: Operators operate ONLY on values that have identical type
-
Operators we are concerned with here:
+, -, *, /, %, =
- If the types do not match, the compiler will do some
conversions automatically
- If automatic conversions do not fix the mismatch, then
the programmer must revise the expression and include explicit
conversions.
- The programmer can always add conversions
Explicit Conversions - Casting
- Explicit conversions are called type casting
- Put type in parentheses
- eg int i = (int) 3.9; // Truncates to 3
- Cast int into a float:
- eg float f = (float) 3; // converts 3 to 3.0
Two kinds of conversions: Widening and Narrowing
- Narrowing
- From larger size value to smaller
- Can lose information
- eg int i = 3; byte b = (byte) i; // Does not lose info
- eg int i = 333; byte b = (int) i; // Will lose info
- eg int i; ... byte b = (int) i; // Might lose info
- eg float f; ... int i = (float) f; //Might lose info
- Compiler will NOT do automatic narrowing conversions
- Widening
- From smaller size value to larger (usually)
- Does not lose information (might lose precision)
- eg byte b=3; int i=b
- eg int i=3; float f=i (can lose precision)
Automatic Conversions - Assignment Conversion
- Compliler will automatically do widening conversion on RHS
of assignment
- eg: float f = 3; // Automatic cast to float
- eg: byte b = 3; int i = b; // Automatic cast to int
- Compliler will NOT automatically do narrowing conversion on RHS
of assignment
- eg: int f = 3.0; // Syntax error
- eg: int i = 3; byte b = i; // Syntax error
Automatic Conversions - Promotion
- Remember: all operators require the same type on both sides!
- In expressions, compiler will use widening conversions to
make both values the same type
- consider byte b, int i, float f, double d;
- 2 + d + 4 // Convert all values to double
- 2 + d + f // convert all values to double
- 2 + 3.0 // convert all values to double
- 2 + f // convert all values to float
- b + i + d // Convert all to double
- b + i // Convert all to int
- Type can change as evaluation progresses
- eg: 2 + (3 + 4) * ( 5 + 6 ) % (2 * 4)
Order of operation
- Parens
- Mult
- Add
- Left to right when same level
Automatic Conversions - Assignment and Promotion
- int i = 3 / 4;
- int i = 10; int j = 25; int x = i / j; int x = j / i
- int i = 10; int j = 25; int x = i % j; int x = j % i
- float f = 3 / 4.0;
- float f = 10.0; float g = 25.0; float x = f / g; float x = f
/ g
- i + ( f * g ) / (i /