It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with this code " Watch "Problem with this code " New topic

Problem with this code

Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
final int i = 100;
byte b = i;

int i = 100;
byte b = i;

The first code snippet compiles and gives output 100. Why does the 2nd code give compiler error??

SCJP 1.4 - 95% [ My Story ] - SCWCD 1.4 - 91% [ My Story ]
Performance is a compulsion, not a option, if my existence is to be justified.
Jesus Angeles
Ranch Hand

Joined: Feb 26, 2005
Posts: 2068
the first one:
the compiler is able to assign a value to b, as at compile time, the data is available (it is final, so the compiler knows it is the value and will never change).

the second one:
the value that will be assigned to b will be available only during runtime. but you cannot assign directly like that; as int is larger than byte.
Mihai Lihatchi
Ranch Hand

Joined: Oct 28, 2005
Posts: 138

It is weird indeed. This is connected to the compiler I believe.
If you change the first snippet of code to

final int i = 130;
byte b = i;

the code generates the compilation error you would expect anyhow (because i>128).
My assumption is this:

The compiler checks whether a loss of precision MAY take a place but i is final AND already asigned to 100 (in bit domain) therefore the compiler knows it can fit into a byte and this cannot change and I believe that for optimization purposes does not generate the error.

However if i>127 the error is generated as the conversion MUST take place and there is a big chance for the precision to be lost.
However this trick is much too subtle.. I would have certainly overlooked it.
You have a very good question .. I had to copy the code into Eclipse and test it to be shore that it doesn't throw a compilation error.

Better, faster, lighter Java ... you mean Ruby right ?
SCEA5,SCBCD1.3,SCWCD5,SCJP1.4 - memories from my youth.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
This question has been asked many times in this forum. Please search through past posts.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Mihai Lihatchi
Ranch Hand

Joined: Oct 28, 2005
Posts: 138

Sorry .
I am new here . I rushed into posting.
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 980

There are certain rules...that govern implicit casting...

Have a look at this post..

Implicit casting

If you search cvan get still further posts that addresses

your doubt..

Let me know if you find it useful..

I agree. Here's the link:
subject: Problem with this code
It's not a secret anymore!