Wednesday, July 24, 2019

memory - Clarification on java pass-by-value



I'm confused as to why the following code doesn't change the data of the Node a:



public class Node{Node next; int data;}
public static void change(Node a)
{
a = a.next;
}

public static void main(String [] args){

Node a = new Node();
Node b = new Node();
a.next = b;
a.data = 1;
b.next = null;
b.data = 2;
change(a);
System.out.print(a.data); //Still 1, why isn't it changed to 2?
}


Since Node is an object, isn't its reference passed by value to the method change? Which means any changes made to the passed in Node should actually change the node?


Answer



This is because in Java you call methods via reference-copies.



This means that when you call change(a); Java basically creates a copy of the reference a and this will be the incoming parameter in public static void change(Node a). Inside the method you will then change that copied reference to point somewhere else. And this will have no effect once your method returns.



This exact same code will work though without the method in between.



Do this a = a.next; instead of change(a) and now your a.data will be 2.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...