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 Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper Class" Watch "Wrapper Class" New topic
Author

Wrapper Class

Geetha Arthanari
Greenhorn

Joined: Nov 24, 2006
Posts: 25
Can you please explain this output:

public class Example
{
public static void main(String[] args)
{
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 127;
Integer i4 = 127;
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i1==i2);
System.out.println(i3==i4);
System.out.println(i5==i6);

}
}

Output is:
true
true
false
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14117
    
  16

Geetha, please quote your sources.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Saurabh Verma
Ranch Hand

Joined: Aug 13, 2007
Posts: 38
Hi ,Geetha

I modified your code.



And the output is


This is because == compares reference, not values. This operator compares two values to see if they refer to the same object.
Geetha Arthanari
Greenhorn

Joined: Nov 24, 2006
Posts: 25
Resource is:
http://www.javabeat.net/javabeat/scjp5/mocks/a/scjp-5-0-boxing-ans-1.php
Geetha Arthanari
Greenhorn

Joined: Nov 24, 2006
Posts: 25
Hi Saurabh,
I'm asking why i1 and i2 are equal. i3 and i4 are equal but i5 and i6 are not equal.
dipayan chatterjee
Ranch Hand

Joined: Oct 03, 2007
Posts: 47
hii geeteha i1 ,12 ,i3,i4,i5,i6 are all different instances of the Integer wrapper class and saurabh has mentioned the == ooperator returns true only when both the objects are indeed one ,which in our case is not true hence the output will be

false
false
false


SCJP1.4 , gearing up for SCWCD 5
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

Originally posted by Geetha Arthanari:
Hi Saurabh,
I'm asking why i1 and i2 are equal. i3 and i4 are equal but i5 and i6 are not equal.


The boxing of integers uses an integer cache. Basically, -128 to 127 are cached when they are boxed, hence, you always get the same one during boxing of numbers in this range.

Interestingly, the specification states that this range must be cache, but it makes no mention of what happens outside this range. This means that in the future, with a new JVM, i5 and i6 may be equal.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Geetha Arthanari
Greenhorn

Joined: Nov 24, 2006
Posts: 25
Thanks to all of you.
 
 
subject: Wrapper Class