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

Wrapper class question  RSS feed

 
David Miranda
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

public static void main(String args[]) {
Byte byteW1 = new Byte("1"); //line1
Byte byteW2 = new Byte("2"); //line2
byte b12 = byteW1.byteValue() + byteW2.byteValue(); //line3
byte b13 = (byte) (byteW1.byteValue() + byteW2.byteValue()); //line4
byte b14 = 4 + 4; //line 5
}

Why does line 3 generate a compiler error and not line 5?
I understand that byteW1.byteValue() + byteW2.byteValue(); returns an int value, and that passing a int to a byte without an explicit cast causes a compiler error; but if thats true, why does line 5 compile correctly?

Doesn't adding 4 + 4 return an int value also?

Thanks
[ March 23, 2005: Message edited by: David Miranda ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David Miranda:

Doesn't adding 4 + 4 return an int value also?


Because you're adding two constants, the math can be done at compile-time by the compiler, rather than being done while the program is running. Because the compiler can add 4+4 to get 8, and because it knows that 8 is a valid value for a byte, this line compiles just fine; the conversion from int to byte is (at least conceptually) done for you, automatically.

In line 3, the compiler isn't smart enough to know what byteValue() will return, so it can't be sure that the result of the addition -- which will be done at runtime -- is going to fit into a byte.
 
David Miranda
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Takes total sense.

Thanks Ernest!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!