Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Wrapper equality test

Tags:

  public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     } 

The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.

like image 518
Warrior Avatar asked Jan 19 '09 05:01

Warrior


People also ask

Can we compare wrapper classes using == in Java?

When a wrapper is compared with a primitive using ==, the wrapper is unwrapped. That's true! But which method is invoked/called depends on the type of the wrapper. If your wrapper is of type Integer, then indeed the intValue method will be called.

How can the values of wrapper class objects be compared?

Comparing Integers Integer is a wrapper class of int, and it provides several methods and variables you can use in your code to work with integer variables. One of the methods is the compareTo() method. It is used to compare two integer values. It will return a -1, 0, or 1, depending on the result of the comparison.

How do you compare primitive data types in Java?

Like in other languages, we can compare the values of primitives with the < , > , <= , and >= operator. The same problems of floating-point data types apply to them, so be aware. Also, boolean isn't comparable except for equality with == and != .


2 Answers

In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):

private static class IntegerCache {     private IntegerCache(){}      static final Integer cache[] = new Integer[-(-128) + 127 + 1];      static {         for(int i = 0; i < cache.length; i++)             cache[i] = new Integer(i - 128);     } } 

See also: http://www.owasp.org/index.php/Java_gotchas

like image 183
Ross Avatar answered Sep 29 '22 18:09

Ross


Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your == works.

Any Integer outside of that range are not cached, thus the references are not the same.

like image 24
SCdF Avatar answered Sep 29 '22 18:09

SCdF