This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with this code

 
Niranjan Deshpande
Ranch Hand
Posts: 1277
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final int i = 100;
byte b = i;
System.out.println(b);

int i = 100;
byte b = i;
System.out.println(b);


The first code snippet compiles and gives output 100. Why does the 2nd code give compiler error??
 
Jesus Angeles
Ranch Hand
Posts: 2068
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 138
Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
System.out.println(b);

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.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question has been asked many times in this forum. Please search through past posts.
 
Mihai Lihatchi
Ranch Hand
Posts: 138
Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry .
I am new here . I rushed into posting.
 
A Kumar
Ranch Hand
Posts: 980
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

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

Have a look at this post..

Implicit casting

If you search ...you cvan get still further posts that addresses

your doubt..

Let me know if you find it useful..

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic