Search code examples
javajavac

Does javac precalculate fixed expressions?


Is there optimization provided for such variable declaration:

final int secondsInDay = 24 * 60 * 60;

This code on C++ won't even compile despite that additional_funct is not used at all:

#include <iostream>

void additional_funct(int num);


void main()
{
    std::cout << "just a text";
}


void additional_funct(int num)
{
    // For both lines will be shown "divide by zero"
    int var = 5 / 0;
    int another_var = num + (2 / 0);
}

This proves that C++ compiler does optimization for numeric literals expressions precalculating them before running. While same Java code will simply start to run:

package experimental_main;

public class Experimental_start {
    public static void main(String[] args) {
        // Will throw ArithmeticException "by zero"
        additionalMethod(2);
        System.out.println("just a text");
    }


    static void additionalMethod(int num) {
        int var = 5 / 0;
        int anotherVar = num + (2 / 0);
    }
}

I understand that javac does not compile code in C-language meaning. But maybe it provides optimization in some other way or its better to declare such numeric literals in this way:

// 24 * 60 * 60
final int secondsInDay = 86_400;

Solution

  • Yes, javac will precompute compile-time constants. It will also concatenate compile-time constant strings, e.g. final String s = "foo" + "bar" would result in the string "foobar" in the string pool, not two strings "foo" and "bar".

    You should always write your code for readability. If writing it as 24 * 60 * 60 makes more sense in terms of what you are writing, use that. Even if it weren't computed at compile time, I would treat any claim that this repeated multiplication were having a meaningful impact on your code's performance with great skepticism.

    The cost of debugging the fact that you wrote 84_600 instead of 86_400 is orders of magnitude greater.