Sub topic 3
Numeric Operations and Promotion
Numeric Operations and Promotion
Arithmetic operators are symbols for calculations: +, -, *, /, and % (remainder). When both numbers in a division are integers, Java drops the fractional part. For example, 5 / 2 gives 2.
Before most arithmetic, Java uses promotion: it changes smaller numeric types to a type suited to the calculation. For example, adding two byte values produces an int, not a byte.
For mixed types, the result is usually double if either value is double. Otherwise, it is float if either is float, then long if either is long, or int.
Conversions and Casts
A conversion changes a value from one type to another. Java automatically allows many widening conversions, such as int to long. Some widening conversions can still lose precision, such as int to float.
A cast is a type name in parentheses that asks Java to convert a value. Narrowing conversions, such as double to int, usually need a cast. Casting a decimal value to int drops its fractional part.
Overflow and Floating-Point Precision
Overflow happens when an integer result is outside its type's range. The result wraps around instead of producing an error.
Floating-point types store approximations of many decimal values. This can make a result slightly different from the expected decimal.
Run this program to see these rules. Save it as NumericExample.java.
class NumericExample {
public static void main(String[] args) {
byte a = 10;
byte b = 20;
int sum = a + b;
long widened = sum;
int narrowed = (int) 3.9;
int overflow = Integer.MAX_VALUE + 1;
final int DAYS_PER_WEEK = 7;
System.out.println(sum); // 30
System.out.println(5 / 2); // 2
System.out.println(widened); // 30
System.out.println(narrowed); // 3
System.out.println(overflow); // -2147483648
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(DAYS_PER_WEEK);
}
}Final Variables and Constants
A final variable can be assigned only once. It is useful for a constant, a value that should not change. Constant names often use uppercase letters and underscores.
Choosing a Primitive Type
Use int for most whole numbers and long for larger ones. Use byte or short when a smaller range is required. Use double for most decimal calculations; float uses less space but has less precision. Use char for a Unicode code unit and boolean for true or false.
For money, avoid relying on floating-point values for exact decimal results.
Exercise
What are the results of 7 / 2 and (int) 7.9?
Show answer
Both are 3. Integer division and the cast each drop the fractional part.