Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Objects and Literals

 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An integer literal cal be assigned to a long primitive variable. Like this

long l=23;

But the same integer literal when assigned to Long wrapper object. It gives an error

Long l=23;

Compiler Error:
found : int
required: java.lang.Long
Long l=23;
^
1 error

Why is this difference happening in Wrapper objects. Why cant wrapper objects behave like normal primitives?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because when 23 is boxed, it is autoboxed into an Integer.

There is no relationship between Integer and Long.
 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kieth,
Consider the following statement

Byte b=23;

Going by what you said 23 will be autoboxed to Integer. And this Integer object will be assigned to Byte reference But there is no relation between Integer and Byte so the assignment should fail. Instead the code works fine. Why ???
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Satish Kota:
Kieth,
Consider the following statement

Byte b=23;

Going by what you said 23 will be autoboxed to Integer. And this Integer object will be assigned to Byte reference But there is no relation between Integer and Byte so the assignment should fail. Instead the code works fine. Why ???


The 23 will be boxed into a Byte because 23 is in the range [-128..127]
However 456 will fail because it is out of range.

You can box a long like this:
Long l = 456L;
 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
During autoboxing which method is being used internally by the JVM. Is it new Byte() or Byte.valueOf() ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic