This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How is this possible" Watch "How is this possible" New topic
Author

How is this possible

Mathangi Siva
Greenhorn

Joined: Jun 26, 2002
Posts: 3
hi
Ive 2 pieces of codes with the corresponding output
public class MyClass1
{
public static void main(String []args)
{
int i = 100;
byte b = i;
System.out.println(b);
}
}
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;
System.out.println(b);
}
}
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
 
 
subject: How is this possible
 
Similar Threads
cast
how is this possible??--Help Wanted
What is the output for First Snippet and Second Snippet?
automatic primitive conversion from higher to lower precision?????
Conversions with final keyword please helpme understand