Understanding Java Enums and Floating-Point Precision
Analyzing Enum Usage in Java
Let's examine EnumTest.java and interpret its output.
public class EnumTest {
public static void main(String[] args) {
Size s = Size.SMALL;
Size t = Size.LARGE;
// Do s and t reference the same object?
System.out.println(s == t); // false
// Is it a primitive type?
System.out.println(s.getClass().isPrimitive()); // false
// Convert from string
Size u = Size.valueOf("SMALL");
System.out.println(s == u); // true
// List all values
for (Size value : Size.values()) {
System.out.println(value);
}
}
}
enum Size { SMALL, MEDIUM, LARGE }
Output analysis:
s == treturnsfalsebecuasespoints toSMALLandtpoints toLARGE.s.getClass().isPrimitive()returnsfalsebecause enums are object types, not primitives.s == ureturnstruebecauseuis derived fromSize.valueOf("SMALL"), which returns the same singleton instance ass.- The loop prints all enum consatnts:
SMALL,MEDIUM,LARGE.
Key takeaways:
- Enums are special classes representing fixed sets of constants.
- Enum instances are singletons, so
==comparison works reliably. - Enums are object types, not primitives.
- You can obtain an enum constant from a string and list all constants.
Floating-Point Precision in Java
Execute the following TestDouble.java code:
public class TestDouble {
public static void main(String args[]) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
}
}
Observe that the results differ from manual calculations. This occurs because floating-point numbers in computers have limited precision. double typically offers 15–17 significent decimal digits, while float provides about 6–9 digits. Due to this finite precision, arithmetic results may be approximate.
Generating Arithmetic Problems
A software company's programmer, Erzhu, has a child in second grade. The teacher asks parents to generate 30 arithmetic problems daily. The following Java code accomplishes this:
import java.util.Random;
public class Math4 {
public static void main(String args[]) {
Random r2 = new Random();
for (int i = 1; i <= 30; i++) {
int n = r2.nextInt(100);
int m = r2.nextInt(4);
int t = r2.nextInt(100);
switch (m) {
case 0:
System.out.print(n + "+" + t + "=" + (n + t) + "\t");
break;
case 1:
System.out.print(n + "-" + t + "=" + (n - t) + "\t");
break;
case 2:
System.out.print(n + "*" + t + "=" + (n * t) + "\t");
break;
case 3:
if (n % t == 0) {
System.out.print(n + "/" + t + "=" + (n / t) + "\t");
} else {
double n1 = n;
double t1 = t;
System.out.print(n + "/" + t + "=" + (n1 / t1) + "\t");
}
break;
}
if (i % 5 == 0) {
System.out.println("\n");
}
}
}
}
This code generates 30 random arithmetic problems involving addition, subtraction, multiplication, and division (with integer or decimal results).