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 Integer.ValueOf() Method 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 "Integer.ValueOf() Method" Watch "Integer.ValueOf() Method" New topic
Author

Integer.ValueOf() Method

sonia jaswal
Ranch Hand

Joined: Jun 01, 2007
Posts: 42
is this code right???

Integer n1 = new Integer(1);
Integer n2 = new Integer(1);

Integer n3 = 1;
Integer n4 = 1;

Integer n5 = 1;
Integer n6 = Integer.valueOf(1);


output:

n1 == n2: false

n3 == n4: true

n5 == n6: true




the Integer.ValueOf() method is taking 1 as argument.... should it not be in double quotes... because Integer.ValueOf() takes a string argument...???
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

If you look in the API documentaton of class Integer, you'll see that there are different versions of the valueOf() method - there's one that takes a String, but there's also one that takes an int.

To explain the results you see:

n1 and n2 are different Integer objects, so if you compare them with ==, the result is false.

n3, n4 and n5 are Integer objects that are initialized via auto-boxing. n6 is an Integer object initialized with the return value of Integer.valueOf(). With auto-boxing, Integer.valueOf() is called behind the scenes.

Note that class Integer has a special caching mechanism. If you call Integer.valueOf() with a value between -128 and 127, the method will return an Integer object out of the cache that it manages behind the scenes. If you call Integer.valueOf() with the same input value multiple times (as you are doing with n3, n4, n5 and n6), it will return a reference to the same Integer object in the cache.

So if you compare those variables with ==, you'll get true - because the variables refer to the same Integer object.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Integer.ValueOf() Method