October 1

Does java passes by value or reference?

Posted by Ajay

|

So the other day someone asked me

“Does Java pass by reference or by value?”

Hey I answered, I ought to know this,

“By value of course.”

So imagine an object Person P passed into a function doModifyPerson(Person p). I call P’s setter, say p.setName(”initalName”) and i then invoke p.setName(”new Name”) inside the function doModifyPerson.

Now the question is does Person p get modified?

So i answered,

“No way jose, Java is pass by value aint it”

Guess what amigos!!…I was dead wrong. Java is pass by value, of course, but in this case the Person object’s reference is passed by value, not the value itsef. So we have two references pointing to the same Person object, so u modify the reference’s value of course the object’s value changes.

But then why does this not happen with Strings, Strings are objects too, but they dont get modified inside the function. Guess what Strings are immutable.

So another instance of not getting my concepts right.

Tags:

Reply

Copyright © 2010 “An Image of My Life” blog series All rights reserved. Theme by Laptop Geek.

Total hits: 59886