Saturday, December 24, 2011

Secret in java

First look at the code:
Integer i=new Integer(5);
integer j=10;
here what happening two object is created of integer type whose value type is int
Integer value lies between -2147483648 to 2147483647
ok fine...

Integer i=127;
Integer j=127;
here what happen one object is created pointed by two referece i and j
lets see..
if(i==j)
{System.out.println("yes");}
else

{System.out.println("no");}

here o/p we get yes

Now once again.......

Integer a=128;
Integer b=128;
here what happen two object is created one pointed by  referece a and another pointing by reference b
lets see..
if(a==b)
{System.out.println("yes");}
else{System.out.println("no");}

here o/p we get no


How it happen...?????

Initially I too get shocked , how it happen?,i opened the book, surf the site then i came to the conclusion....

Bydefault jvm have limited heap memory which we can increase manually......
because of this bydefault limited heap memory 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.
In simple we can say that Integer value can be consider as three type

Data Type            Value                            Memory
byte            -128 -- +127                    occupy 1 byte (8 bits) in memory
short            -32768 -- 32767             occupy 2 bytes (16 bits) in memory
int            -2147483648 -- 2147483647   occupy 4 bytes (32 bits) in memory


and for least data type i.e byte value is cached in such a way that when you use those numbers you always refer to the same number in memory,because of limit heap memory
 


If you really enjoyed this
give feedback
thanks...... :) 

3 comments:

Unknown said...

gr88 secret in java

Unknown said...

this post is awesome

mark jogger said...

nice post is this.. gud keep it up Abhishek