Check out this example from "sandeep mock exam" class MyClass { public static void main(String []args) { final int i = 100; byte b = i; System.out.println("i ="+b); } } ans : o/p i =100 BUT class MyClass { public static void main(String []args) { int i = 100; byte b = i;......(1) System.out.println(b); } } I get a compiler error as Incompatible type declaration, so when I cast line (1) as byte b = (byte)i; it works fine with o/p 100 why is this strange behaviour with " final keyword"?, I am confused. can somebody clear my doubt? Thanks in advance satheesh
George Toronto
Ranch Hand
Joined: Dec 30, 2000
Posts: 78
posted
0
plz check Rhalid book.
Tom Tang
Ranch Hand
Joined: Dec 24, 2000
Posts: 133
posted
0
This looks really tricky. Can someone explain more?
I reallly could not understand what is given in the book when I read it, could u pls explain to me in brief Thanks in advance
Bob Moranski
Ranch Hand
Joined: Nov 22, 2000
Posts: 177
posted
0
Hi, I think it has to do with compiling rules. When an int is declared final, its value is set forever at compile time. The compiler knows for sure that 100 is within the range of byte value. On the other hand, without declaring an int final, the compiler will have no way of knowing for certain that the int's value will be within byte's range. Therefore, without the final keyword, compiler requires the int to be cast to byte.
Sean Casey
Ranch Hand
Joined: Dec 16, 2000
Posts: 625
posted
0
I must've seen this example at least three times in the last month. It's funny how some things just keep popping up.
Satheesh Kumar
Greenhorn
Joined: Nov 21, 2000
Posts: 14
posted
0
Thanks bob for ur detail explanation now I got it.., satheesh
Cherry Mathew
Ranch Hand
Joined: Dec 26, 2000
Posts: 159
posted
0
Originally posted by Tom Tang: This looks really tricky. Can someone explain more?
hi Tom, Tom java compiler goes for optimization and replaces the final variables with the values present in that. Note that the final method call is faster than a non-final method call bcoz in case of final method it doesnt have to go for dynamic data lookup which is slow . Cherry
Rat Ban
Ranch Hand
Joined: Jan 20, 2001
Posts: 30
posted
0
Hey...Satheesh Kumar, Can u tell me where i can find this particuler Mock Exam?? ************T H A N K S IN A D V A N C E *************** round6