Tuesday, May 27, 2008

Java Tricky Questions - 1

Whats the difference between

int length = 5;
int breadth = 10;
int area = length * breadth;

and

final int length = 5;
final int breadth = 10;
int area = length * breadth;


dont scroll down until you have thought over the answer
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
gave it a thought ?
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
sure ?
.
.
.
.
.
.
.
.
.
.
.
Ok then heres the answer...
In the second code snippet multiplication is done at compile time.
In first multiplication is done at Runtime.
Reason
Java compiler uses something known as Constant Folding. Constant folding refers to the compiler precalculating constant expressions.
Query
I wonder what will happen if the code is

int length = 5;
final int breadth = 10;
int area = length * breadth;

The above code will not use constant folding for length but do so for breadth.
What if ?

static final int breadth = 10;
int area = 5 * breadth;

then compiler will use constant folding for breadth.

2 comments:

Anonymous said...

Thank you!
For posting this example.

Eli Elfassy

Sivaji Kondapalli said...

good example. thank you.