• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How is this possible

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic