This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Tell me Why ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Tell me Why ?" Watch "Tell me Why ?" New topic
Author

Tell me Why ?

Sherry Jacob
Ranch Hand

Joined: Jun 29, 2005
Posts: 128
Hi All,
I compiled this code...


and this code...


The first code compiles but the second does not. Why ?
Please help.


<strong><br />Cheers !!<br /> <br />Sherry<br /></strong><br />[SCJP 1.4]
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Sherry, please give your topic a meaningful title, and please tell us the compilation error you get. Is the error given by the compiler not meaningful?

Yes, I can see why the second does not compile:In the first case i is a compile time constant within the range of a byte (-128 to 127). In the second it is not a constant and the compiler cannot guarantee in all possible cases that at the time of the assignment that i still contains 100.
[ September 06, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
amit g
Greenhorn

Joined: Sep 04, 2005
Posts: 2
Hi Sherry,

Reason is simple in the first code u declared variable as a final and final
variables are constants so compiler knows that the value of this particular variable will not change in runtime ie. will not change from 100.
So it will not go out of range.

In other way compiler replaces all final variable with there values at compile time as in ur code


statement
byte b = i; //for first code

will replace to

byte b = 100; before compilation then compilation will occur.


but in second snap shot of code i

byte b = i ;

will not replace to

byte b =100;

it will simply

byte b = i;


Cheers
Amit Goyal
Thomas Drew
Ranch Hand

Joined: Sep 15, 2004
Posts: 47
Sherry, the reason your second file fails to compiles is because i is promoted to an integer before it is assigned to the byte b. To fix the problem you will have to cast i back to a byte (byte) i.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
because i is promoted to an integer before it is assigned to the byte b


i is already an int, it does not have to be promoted.
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
http://www.coderanch.com/t/250545/java-programmer-SCJP/certification/Final-variable

Check this one out..

Regards
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Tell me Why ?