1

this is the test code I am using to understand how java handles object memory.

public class TestCode {

  public static void main(String[] args) {
    TestCode obj = new TestCode();

    CustomClass cs1 = new CustomClass(5);
    obj.updateExistingObj(cs1);
    System.out.println(cs1.val);

    CustomClass cs2 = new CustomClass(5);
    obj.instantiateExistingObj(cs2);
    System.out.println(cs2.val);

    CustomClass cs3 = null;
    obj.updateNullObj(cs3);
    System.out.println(cs3.val);
  }

  void updateExistingObj(CustomClass cs1) {
    cs1.val = 9;
  }

  void instantiateExistingObj(CustomClass cs2) {
    cs2 = new CustomClass(9);
  }

  void updateNullObj(CustomClass cs3) {
    cs3 = new CustomClass(9);
  }
}

class CustomClass {
  int val;
  CustomClass next;
  CustomClass(int x) { val = x; }
}

The output of the first syso where I am printing cs1.val I am getting expected value which is 9.
The output of the second syso where I am printing cs2.val I am getting 5 as output instead of 9.
The output of the third syso where I am printing cs3.val I am getting a null pointer exception.


Can anybody help me understand what is happening here under the hood? How exactly java handles the memory location when we pass an object as a function parameter? Thanks for helping!!

Rito
  • 3,092
  • 2
  • 27
  • 40
  • Think of a variable as a pointer to an object. When you _assign_ to a variable, you only modify the pointer. When you access a field of the object, you follow the pointer. `cs1.val = 9;` actually takes a `pointer to cs1`, follows it to find `val`, and changes the value there from 5 to 9. `cs2 = new CustomClass(9);` does not follow the pointer. instead it overwrites the stored pointer so that it now points to a different location. The variable `cs2` from where you called this function is still the original pointer though. Same thing for the `cs3` scenario – lucidbrot Aug 30 '19 at 09:03

1 Answers1

0

cs2 and cs3 are local variable, assigning a new value to them have no effect outside of the methods where they are declared.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24