• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Wrapper class question

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Takes total sense.

Thanks Ernest!
 
What is that? Is that a mongol hoarde? Can we fend them off with this tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic