File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper Objects and Literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper Objects and Literals" Watch "Wrapper Objects and Literals" New topic
Author

Wrapper Objects and Literals

Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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?


SCJP 5.0 77%
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Because when 23 is boxed, it is autoboxed into an Integer.

There is no relationship between Integer and Long.
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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

Joined: Aug 03, 2002
Posts: 7729
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;


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
During autoboxing which method is being used internally by the JVM. Is it new Byte() or Byte.valueOf() ?
 
GeeCON Prague 2014
 
subject: Wrapper Objects and Literals