Win a copy of Rust Web Development this week in the Other Languages forum!
  • 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 ...
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Integer.ValueOf() Method

Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);


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...???
Java Cowboy
Posts: 16084
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic