пʼятниця, 25 червня 2010 р.

Sun`s secret number

Today i`ve found an interesting test:


  1. class SCJPPrepration1 {  
  2.   public static void main(String[] args) {  
  3.      Integer i = Integer.valueOf(10);  
  4.      Integer j = Integer.valueOf(10);  
  5.   
  6.        
  7.      System.out.println(i==j);  
  8.        
  9.      int magicSunOfficialSecretNumber =143;  
  10.        
  11.      Integer k = Integer.valueOf(magicSunOfficialSecretNumber);  
  12.      Integer l = Integer.valueOf(magicSunOfficialSecretNumber);  
  13.   
  14.        
  15.      System.out.println(k==l);  
  16.   
  17.   }  
  18. }     
Never thought before that answer will be : true and FALSE. 

Important thing  that need to remember: 

Whenever boxing is applied , only one wrapper object exists in the program for primitive values of( boolean,byte,char and int or short):
1).boolean values true or false,
2).a byte,
3).a char in range \u0000 to \u007f,
4),and an int or short value in the range -128 and 127.

so for eg if a and b refer to two wrapper objects that box same value which is among one of those mentioned above ,then a==b is always true,i.e object and reference equality will give same result..
Let us take an example,

  1.   Byte b1=(byte)10;   
  2.   Byte b2=(byte)10;  
  3.   System.out.println(b1==b2);                //true  
  4.   System.out.println(b1.equals(b2));        //true  

but in case if we violate one of the above 4 points ,for eg here let us take point 4,
and do

  1.       Integer k=143;  
  2.            Integer l=143;  
  3.            System.out.println(k==l);                //false because after boxing the range of int is bet[-128,127]  
  4.            System.out.println(k.equals(l));        //true as objects have same value  

Thus this proves the result. 


Немає коментарів:

Дописати коментар