File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How is this possible Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How is this possible" Watch "How is this possible" New topic

How is this possible

Mathangi Siva

Joined: Jun 26, 2002
Posts: 3
Ive 2 pieces of codes with the corresponding output
public class MyClass1
public static void main(String []args)
int i = 100;
byte b = i;
Output is :Compilation Error
this is coz we need Type casting
see this code
public class MyClass
public static void main(String []args)
final int i = 100;
byte b = i;
This code is similar to the first except the var is declared "final" and
Output is 100
Pls tell me how is this possible

mathangi sivakumar
Snigdha Solanki
Ranch Hand

Joined: Sep 07, 2000
Posts: 128
An integer is a bigger datatype. Doing something like this
byte b = i;
will give a compilation error because a byte cannot hold more than 8 bits whereas an integer can hold upto 32bits. Java compiler checks this this type mismatch at run time. So in order to compile and run you need to typecast the statement
byte b = (byte)i;
But in the second case you are declaring i as final. when you decalre a variable as final you cannot change its value afterwards. So i will always be 100 in your case. Since 100 can fit in a byte, the code get's compiled. In the earlier case although you were setting i as 100 but later it is possible to change the value to something bigger which will not fit into byte and so the compiler gave an error.
In the second example set the value of i as 100000
final int i = 100000; and then try. this time compiler will give error.
Hope this helps.

Snigdha<br />Sun Certified Programmer for the Java™ 2 Platform
I agree. Here's the link:
subject: How is this possible
jQuery in Action, 3rd edition