1
Class #05: Understanding Primitives and Assignments
Software Design I (CS 120): D. Mathias
Java Arithmetic
} Evaluate the following expressions: 1.
int x = 5 / 2 + 2;
2.
int x = 2 + 5 / 2;
3.
int x = 5 / 2.0 + 2;
4.
double x = 5 / 2.0 + 2;
5.
int x = (int) 5 / 2.0 + 2;
6.
int x = (int) ( 5 / 2.0 + 2 );
7.
int x = 5 / (int) 2.0 + 2;
8.
int x = 5 / (int) (2.0 + 2);
9.
double x = 5 / 2 + 2;
Software Design I (CS 120) 2
4 ERROR 4.5 4 4 1 ERROR 4 4.0
Java Mixed-Type Arithmetic: Tricky Cases
} When we mix types of numbers in a math expression, the
final result will be of widest type (unless we cast)
} However, the result we get can also depends on when
the switch is made from narrow types to wider ones
} This depends upon operator precedence, too
} Examples: 1.
5 / 2 * 2
- 2. 5.0 / 2 * 2
- 3. 5 / 2.0 * 2
- 4. 5 / 2 * 2.0
Software Design I (CS 120) 3
⟸ 4 ⟸ 5.0 ⟸ 5.0 ⟸ 4.0
Here, since division 5 / 2 is performed first, and both 5 and 2 are of type int, we use int division Conversion to double type doesn’t happen until the multiplication (*)
Understanding Java Assignments
} Remember: the assignment operator (=) is not the
same as the equals sign used in mathematics
} An assignment instruction in Java:
target = expression; is a command, saying that we should store the value of the expression to the target
} If the target is a variable identifier, then we can
change the value of what it stores this way
Software Design I (CS 120) 4