Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Conversion

 
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Why does not this code give a compile error?(because of final?)
Thanks
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Areca!

It's normal not to give a compile error because 100 can be converted to a byte.
Bytes numbers are represented on 8 bits=> means a byte number is between -2^7..2^7 - 1 (x^y means x multiplied with x for y times) = -128..127.
Because 100 can be represented on a byte (-128<100<127) the compiler gives no error and converts the int number 100 to the byte number 100.
If you tried to convert an int number greater than 127 or less than -128 (let's say 144) to a byte number, the compiler will give you an error.


The code example above gives you an error compile.
So, the final modifier has nothing to do with the conversion.

I hope this answer lets you.
Do let me know if you have troubles understanding it.
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The final modifier certainly has to do something with conversion Emilia. In the first example provided the value is within the range of byte values (-128 < 100 < 127) whereas in the second example the value is outside of the range of byte values (144 > 127). Since the variable is final the runtime value is known at compile time and can thus be verified to be in the range of byte. Hence a cast is not required in the first example but is required in the second.
 
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iakhnin u r correct ....

if u try the same code not using final then it gives an error of loss of precision inspite of 100 being fit into the byte ...what Iakhnin said i suppose if u declare the variable as final then its value is computed at compile time ...

class MyClass{
public static void main(String []args) {
int i = 100;
byte b = i;
System.out.println(b);
}}


thanks & regards

srikanth
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!