May 20, 2018

Copying the value and copying the reference in java

code snippet

public class HelloWorld{


     public static void main(String []args){
      
        Integer a=new Integer(10);
        Integer b=new Integer(20);
        a=b; //Value is copied
        
        a=40;
        
        System.out.println("a="+a+" b="+b);
        
        
         class Numberr
        {
            private Integer value;
            
            Numberr(Integer value)
            {
              this.value=value;  
            }
            
             public void setValue(Integer value)
            {
              this.value=value;  
            }
            
            public Integer getValue()
            {
                return value;
            }
        }
        
        Numberr aObj=new Numberr(70);
        
        Numberr bObj=new Numberr(80);
        
        aObj=bObj; //Reference is copied
        
        aObj.setValue(100);
        
        System.out.println("aObj="+aObj.getValue()+" bObj="+bObj.getValue());
     }
}

No comments:

Post a Comment