4

This is a question asked in one the written that I had given last week can anybody help me identify the difference

public class TestClass {
    static final  int a = 2;
    static final  int b = 3;

    static int c = 2;
    static int d = 3;

    public static void main(String[ ] args) {
    int product1 = a * b;             //line A
    int product2 = c * d;             //line B
    }
}
0

4 Answers 4

9

Since a and b are declared final, there's the possibility that the compiler will in-line the calculation (the calculation being done at compile time). See the Java Language Specification, section 15.28: Constant Expressions. That doesn't happen with c and d; the product will always be calculated at run time.

Sign up to request clarification or add additional context in comments.

Comments

6

Line A is candidate to be computed at compile-time because the fields are final. Line B is computed at runtime.

Comments

1

I believe int product1 = a * b; will be calculated during compilation itself, Since a and b was declared as final.

Comments

0

variables a and b are final so the compiler will replace variables a and b with 2 and 3 in the line product = a * b

3 Comments

Not quite 'will'. The compiler can choose to inline.
@Bathsheba, isn't there surety of it?
see JLS link in another answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.