The clumsy facet of Java Integer comparisons



A good high level computer language should be easy to read and understand while providing a reliable environment despite from the machine, but the developer. The general theories should not be changed in order to invent a new class or a data type. The Integer and the int type of Java has a distinct behavior.

The Integer is a class, while the int becomes a data type. What’s the difference ?? The Integer value is always wrapped to an Object while the int just stores value as a value itself. In fact, it keeps the binary value of that decimal number. The problem will rise its head, when Integer comparison comes.

We all know 150 == 150 right ?? But if the computer says it is wrong, would you believe? Yes you have to…!! That is where the misconception arises.

In Java,

Integer num1 = 150, num2=150; 
Integer num3 = 100, num4=100;

System.out.println(num1==num2); //gives false
System.out.println(num3==num4); //while this gives true !!!


This gives a negative impact to a developer (Even though this happens for a specific reason). 90% of the developers may not get comfortable with it. Integer wrapper unboxing will happen when we compare two Integer objects with smaller values (let’s say below 100). But every time, when we compare larger values, if that is equal (as a value), it will give false (That is right ; both are objects). Because at that time, the unwrapping will not happen. If you need to unwrap an Integer, there is a method to call from that Integer object.

int num1_int= num1.intValue();
int num2_int= num2.intValue();

So, the same could be done using,

System.out.println(num1_int==num2_int);//gives true   Happy ???  :)

How it compares to c#?

In C#, There is no class called Integer, but int is there (which is same as Int32). It is a data structure which resides in System.Int32. This enables the developer to adjust flexibly in programming without any spontaneous misconceptions.


What is the use of Integer as a value keeping reference type? Wouldn’t it bothers the developer?

The solution

The conversion I described above (which is messy; not a good practice), or do not use smaller numbers when using Integer as a value storing reference type (which never happens).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s