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 edited May 17 '20
Your quotes inlude 'Java is always pass by value', ' it's at least sometimes pass by value', 'It's always.'. Those are your quotes and they contradict each other.
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