how Passing a string to a function
I would like to ask a really simple question. I am just passing a String object to a function but the result is weird. I supposed that because I am passing an object(by reference) the result should have be ” Here” and not “Hello”. Why is this happening?
If that is the case then why if I pass it inside a wrapper object is working? The wrapper object it is not by reference?
PS: Why this is working that way? String is an object. Why do I need another wrapper Object to change an OBJECT! What if I want to pass something by reference? Is that possible?
Java passes object references by value this means when you call a function the following happens.
When the object is passed to the value it looks like this
Then in the function you reset what passedStr points to
The original string still refers to “Some String” but the copy of it now refers to “Other String”
When you return from the function the original string reference still points at “Some String”
// EDIT: Why can you modify objects referred to by another object?
Lets say I have StringWrapper, which is a class which contains a string.
To java that looks like this
When you pass it to a function the following happens just like above
Notice how both variables point at strWrpA in memory.
You would have the same problem as you have without a wrapper if you did this