Does the switch statement work with double or float types?
sobes.tech AI
Answer from AI
No, in Java the switch statement does not work directly with double or float types.
The reason is that floating-point numbers have an imprecise representation in computer memory. Comparing such numbers for exact equality (==) can lead to unpredictable results due to inaccuracies.
switch requires an exact match of the value to select the execution branch. The types supported in switch are primitive integer types (byte, short, char, int), their wrapper classes (Byte, Short, Character, Integer), enumerations (Enum), and the String type (since Java 7).
To compare double or float values, you can use conditional operators if/else if/else. When doing so, it is recommended to use a specified tolerance (epsilon) for equality comparison.
double value = 10.5;
double epsilon = 0.0001;
if (Math.abs(value - 10.5) < epsilon) {
// Action for value == 10.5
} else if (Math.abs(value - 5.0) < epsilon) {
// Action for value == 5.0
} else {
// Action for other values
}