Monday, October 19, 2015

Understand Java primitives wrapper class comparison

Java has a wrapper class for every primitive types, Such as  Integer to int, Boolean to boolean, Short to short, Character to char and etc. Also we all know that when compare two java objects,  "a==b" only  check if a and b refer to the same objects, while "a.equals(b)" normally can compare the real value that instance a and b really presents. That is true.

So in short, always use equals() to compare primitives wrapper class. 

In this article, let's use some demos to help you get a clearer understand.

All demos used in this article have been tested under JDK 1.7.

Demo 1

package com.shengwang.demo;

public class DemoMain {

public static void main(String[] args) {
Integer i1,i2;

i1 = new Integer(5);
i2 = new Integer(5);

System.out.println(i1==i2); // false, i1,i2 refer to 2 objects
}
}

This demo is very straitforward, since i1 and i2 refer to 2 different Integer instances, the "i1==i2" condition will return false.


Demo 2

package com.shengwang.demo;

public class DemoMain {

public static void main(String[] args) {
Integer i1,i2;

i1 = 5;
i2 = 5;

System.out.println(i1==i2); // true, why?
}
}

This demo 2 is very similar to demo 1, but use i1=5 to initial the Integer instance instead of using keyword new. The output turns out that i1==i2 is true, why? Because in java, an internal java.lang.Integer instance will be created automatically before assign constant int 5 to an java.lang.Integer variable. This is called auto-boxing in Java. In order to save memory, there will be only one internal instance if the primitive value is same. Which means i1 and i2 do point t the same internal Integer object. So the output of demo 2 is true.


Let's step a little bit further.

package com.shengwang.demo;

class ClassA {
public Integer i1 = 5;
}

class ClassB {
public Integer i2 = 5;
}

public class DemoMain {

public static void main(String[] args) {
System.out.println(new ClassA().i1 == new ClassB().i2); // true again
}
}

It still uses primitive constant to initial wrapper class instance by auto-boxing. The same rule applies even variables are in different class instances.

Recap

  • Only use equals() to compare java primitives wrapper class instances.
  • If you wonder why sometimes "==" also get the  appeared right result? That's because JVM try to save memory, auto-boxing for constant always using the same internal object if the primitive value is same.

0 comments:

Post a Comment

Powered by Blogger.

About The Author

My Photo

Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List