r/javahelp • u/djpfg • 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
-1
u/Jarl-67 May 17 '20
There are a lot of definitive "Java is pass by value only" statements in the comments. This disproves that false narrative. Examples given include primitives and the reference itself but that is only partially pass by value. Java passes the pointer by value and that's it. The object is modifiable as the reference to that object is the same. No copy of an object parameter is made in java.
Java pass by reference example
For parameters that are pass by value, it's impossible to change a parameter where that change lasts past the method execution. In this simple example, you can see that an object is modified and that modification persists after the method is complete. This situation is impossible in a pass by value scenario.
Running the example yields this result:
Before method: Joe "by Value" Java
Start method: Joe "by Value" Java
End method: Joe "by Reference" Java
After method: Joe "by Reference" Java