What is the result of the following code execution?

public class Main {
    public static void main(String[] args) {
        String value = "29.1";
        System.out.println((Float.valueOf(value) + 1.0) == 30.1);
        System.out.println((Double.valueOf(value) + 1.0) == 30.1);
        System.out.println(Float.valueOf(value) / 0);
        System.out.println(Double.valueOf(value) / 0);
1: Float.valueOf(value) results in 29.1f. Then 29.1f is converted to double since 1.0 is of double type (by default all the floating-point literals are of double type). Therefore, we obtain a value of 29.100000381469727d. Consequently (Float.valueOf (value) + 1.0) = 30.100000381469727d. As a result, (Float.valueOf (value) + 1.0) == 30.1 results in false.
2: Similarly to part 1. but without float to double conversion, all the variables are of double type. (Double.valueOf (value) + 1.0) results in 30.1d. As a result, (Double.valueOf (value) + 1.0) == 30.1 results in true.
3: Division of float by zero does not result in ArithmeticException (only integer division by zero will result in it). For such cases, Float class even contains a constant: public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
If the source code of the java.io.PrintStream#println(float) method is examined, it becomes clear that the float is converted to a string by the String.valueOf(float) method, which converts POSITIVE_INFINITY into "Infinity".
4: Similarly to 3.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback