Techno

things which came out my laptop

Java Concepts

| Comments

They are some interesting concepts which make java more interesting. I will
present series of articles which will explain these concepts.

Concept 1,
Can you guess what will be printed on the screen?

class Test
{
public static void main(String[] args) {
Test inst_test = new Test();
int i1 = 2000;
int i2 = 2000;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );
}
public void method( Integer i , Integer eye )
{
System.out.println(i == eye );
}
}

When I first saw this code I was confident that it will give out put as,
false
false.
because == compares hashCode, not the value for wrapper classes.

But When I checked it with my IDE, Surprisingly it was giving out put as,
true
false.

After a bit of googling I found the reason,

Certain ranges of values of wrapper classes are stored as immutable objects by the Java Virtual Machine.
Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object. The following is the list of primitives stored as immutable objects:
* boolean values true and false
* All byte values
* short values between -128 and 127
* int values between -128 and 127
* char in the range \u0000 to \u007F

Comments

Vaibhav Tulsyan
Awesome! :D
Varsha
Thanks for this post. I was not aware of this concept for Integers.
Sachin6870
== does compare hashcode,
but for int values between -128 and 127 hash code is same.
mahesh
class Test
{
public static void main(String[] args) {
Test inst_test = new Test();
int i1 = 130;
int i2 = 130;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree.hashCode());
System.out.println( Ifour.hashCode());
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );
}
public void method( Integer i , Integer eye )
{
System.out.println( i.hashCode() == eye.hashCode());

System.out.println( i == eye );

}
}

This shows that == does not checks hashCode.Isn’t it.

Comments