Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How is this possible

 
Mathangi Siva
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Snigdha Solanki
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic