Reputation:
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
Reputation: 5531
I believe int product1 = a * b; will be calculated during compilation itself, Since a and b was declared as final.
Upvotes: 1
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
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
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