Assignment and Data Conversion with Arithmetic Operators

Basic facts on assignment and conversion

  1. Fact: Variables and values ALWAYS have a TYPE

  2. Fact: Operators operate ONLY on values that have identical type

  3. If the types do not match, the compiler will do some conversions automatically

  4. If automatic conversions do not fix the mismatch, then the programmer must revise the expression and include explicit conversions.

  5. The programmer can always add conversions

Explicit Conversions - Casting

  1. Explicit conversions are called type casting
  2. Put type in parentheses
  3. eg int i = (int) 3.9; // Truncates to 3
  4. Cast int into a float:

Two kinds of conversions: Widening and Narrowing

  1. Narrowing
  2. Widening

Automatic Conversions - Assignment Conversion

  1. Compliler will automatically do widening conversion on RHS of assignment
  2. Compliler will NOT automatically do narrowing conversion on RHS of assignment

Automatic Conversions - Promotion

  1. Remember: all operators require the same type on both sides!

  2. In expressions, compiler will use widening conversions to make both values the same type

  3. consider byte b, int i, float f, double d;

  4. 2 + d + 4 // Convert all values to double

  5. 2 + d + f // convert all values to double

  6. 2 + 3.0 // convert all values to double

  7. 2 + f // convert all values to float

  8. b + i + d // Convert all to double

  9. b + i // Convert all to int

  10. Type can change as evaluation progresses

  11. eg: 2 + (3 + 4) * ( 5 + 6 ) % (2 * 4)

Order of operation

  1. Parens
  2. Mult
  3. Add
  4. Left to right when same level

Automatic Conversions - Assignment and Promotion

  1. int i = 3 / 4;

  2. int i = 10; int j = 25; int x = i / j; int x = j / i

  3. int i = 10; int j = 25; int x = i % j; int x = j % i

  4. float f = 3 / 4.0;

  5. float f = 10.0; float g = 25.0; float x = f / g; float x = f / g

  6. i + ( f * g ) / (i /