Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Type Conversion  RSS feed

 
S Anand
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ! everybody
My problem is with the following code :
byte b;
b=10+20;
System.out.println(b);
Numeric literals are integer by default, i.e. Values 10 and 20 are integer values. So according to me, it should give an compilation error. But it is working fine without any explicit type casting. Can anybody give me the reason for this.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler is smart enough to realize that the right hand side is an intergral constant that can fit in a single byte, so it allows it.
The main reason is to allow you to write:
byte b = 10;
without having to write
byte b = (byte) 10;
all the time, which would be a pain in the you-know-what.
The expression "10+20" is evaluated at compile-time, and the result is another interger of value 30, which will fit into a byte. It's the same as writing
byte b = 30;
But try this:
byte b = 1+255;
and see what happens. Go in, I dare ya!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!