user2728475
user2728475

Reputation:

What's the difference in computation when I use final in Java compared to if I do not declare the variable to be final?

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
    }
}

Upvotes: 4

Views: 147

Answers (4)

upog
upog

Reputation: 5531

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

Upvotes: 1

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

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

Upvotes: 0

tbsalling
tbsalling

Reputation: 4545

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

Upvotes: 6

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 9

Related Questions