r/javahelp • • May 15 '20

how reference variables are passed as method arguments in Java

Hello, I am struggling to understand what this question is asking for, I know in C++ for pass by reference the address of the variable is passed and altered before returning unlike pass-by value(correct me if Im wrong) but in java I thought all values were automatically pass by reference? struggling to make sense of the question so any help at all will be greatly appreciated:)

Explain the difference between how pass-by-reference operates in C++ and how reference variables are passed as method arguments in Java. A good answer will include a simple example of each

16 Upvotes

30 comments sorted by

View all comments

13

u/Yithar Intermediate Brewer May 15 '20

Java is always pass by value. It just so happens that what is in obj when you say Object obj = new Object(); is a memory address. So what happens is a method given obj is given a copy of the memory address.

The reason you know it's at least sometimes pass by value is because of how things work with primitives. If it was pass by reference, modifying an int passed to a method should modify the original one as well.

In C++, passing a pointer by reference means you can actually modify the original memory address from the method itself and the change will be reflected when the function returns. You can not do this in Java.
https://stackoverflow.com/questions/10240161/reason-to-pass-a-pointer-by-reference-in-c

1

u/iamsooldithurts May 15 '20

Damn great answer.