my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question on conversion 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 "A question on conversion" Watch "A question on conversion" New topic

A question on conversion

Achutha Prasad

Joined: Jan 25, 2001
Posts: 2
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;
Son Le

Joined: Jan 15, 2001
Posts: 21
Achutha, int i = 100;
2.byte b = i;
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

Joined: Jan 12, 2001
Posts: 15
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.
Achutha Prasad

Joined: Jan 25, 2001
Posts: 2
Thanks venkat and Son.
[This message has been edited by Achutha Prasad (edited January 25, 2001).]
Consider Paul's rocket mass heater.
subject: A question on conversion
It's not a secret anymore!