0

I just start learning Java and the things that occur to me are that they don't have passing by reference like c++ does. How do I change the value of object variable after I passing it to function?

public static doStuff(Node x, Node currentNode){
   if(x == null)
      x = currentNode;

}

public static void main(String []args) {
   Node x = null;
   Node newNode = new Node() 
   doStuff(x,newNode);
   System.out.println(x) // --> This one supposed to be different than null

}
FloydVu0531
  • 23
  • 1
  • 5
  • 1
    Passing an object variable in Java is similar to passing a pointer in C or C++. You can't change _which_ object it refers to, but you _can_ change the fields of the object that it refers to. So you might try to write a class which has the value you want to change as one of its fields. – Dawood ibn Kareem Aug 25 '21 at 21:10
  • Related: [*Is Java “pass-by-reference” or “pass-by-value”?*](https://stackoverflow.com/q/40480/642706) – Basil Bourque Aug 25 '21 at 21:20

1 Answers1

0

This is a strange limitation of Java.

I believe the intended pattern for the pattern you are describing is to modify the "doStuff" method to return currentNode, and then set the value in main.

Something like:

public static Node doStuff(Node x, Node currentNode){
   if(x == null) {
      return currentNode;
    }
}

public static void main(String []args) {
   Node x = null;
   Node newNode = new Node() 
   x = doStuff(x,newNode);
   System.out.println(x) // --> This one supposed to be different than null

}

I consulted this answer to create mine:

Reference: Java changing value of a variable through a method?

Christian May
  • 127
  • 11