Search code examples
javajvmpass-by-referencecall-by-value

what exactly happen in jvm when i create an object in java?


To my understanding if i am writing

Car a3=new Car() 

This statement will create a handle named a3 in jvm stack with all its properties in JVM heap. IF this is correct i am wondering how call by value works. So, if i create a method checkMethod(Car c) and call it by saying checkMethod(a3); suppose our car is

public class Car{
   int a=0;
   public int getpar(){
       return a;
   }
}

in checkMethod i try to access a using a3.a = 5; so i changed the value of a3.a it will show me in the calling class as well as it was pointing to the same fields that jvm created in the heap.

But when i do a3= null; in the calling method and go back again in the method from which i was calling checkMethod(a3) and try to see this object it is not null? Why it behaved differently as compared to property of object that is a???


Solution

  •  checkMethod(a3);
    

    Pass a copy of a value which is a reference to object instance of Car

    Inside method...

    a3.a = 5
    

    Using a3, modify object instance of Car which is identified by a3 ( which is a copy of original a3).

    a3 = null
    

    Set the reference to null ( copy)

    When this happens, only the copy you passed to your method will point to null. But the original a3 still points to your object instance of Car.