Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question on conversion

 
Achutha Prasad
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

We know that an implicit conversion from an int to an byte is not possible. But when the int variable is declared as final then the implicit conversion takes place. Y is it so? The below code compiles and give an output 100.
public test{
public static void main(String args[])
{
final int i = 100;
byte b = i;
System.out.println(b);
}
}
 
Son Le
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Achutha,
1.final int i = 100;
2.byte b = i;
3.System.out.println(b);
final keywords has an advantage that is the compiler can inline final elements. Line 2 will be treated like:
2.byte b=100;
Therefore, it's legal.
Hungson Le
 
venkatesan Rajagopalan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Achutha,
you are right implicit conversion cannot take place from int to byte.
you will agree that when final modifier is given that particular variable value remains constant and cannot be changed, right.
In the instant case, the compiler implicitly knows for sure that the int value will remain pegged to 100 and would never be changed and the compiler upon checking that it is within the range of byte, compiles the program and no casting errors is spewed up.
regards
venkat
 
Achutha Prasad
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks venkat and Son.
Regards,
prasad
[This message has been edited by Achutha Prasad (edited January 25, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic