• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java pass by value

 
thejwal pavithran
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys,

I am having difficulty understanding How parameters are passed in java.

heres my code:



so i am passing the address of Hippo h2 to copyHippo through method copy. So when i modify the value of size of copyHippo in the copy method, it gets reflected in the main method, which can be seen by the output of the sop.

I just cant understand why the string variables value is not getting modified. Because isnt it completely similar to the copyHippo reference variable?

but why is the value of s2(null here)passed instead of the address.
I mean copyHippo is a reference variable which points to the same object to which h2 and h1 created in the main method are pointing to.so when i modify the value of instance variables of copyHippo in the copy function, the values of instance variables in the main function gets modified.

Same should be the case for the string variable too right? But what am i missing here?

I need to understand this.please help
 
jatan bhavsar
Ranch Hand
Posts: 299
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Refer this . It will solve your doubts.

Regards
jatan
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is more related to the behaviour of Strings as opposed to passing by value. See here about Strings: http://docs.oracle.com/javase/tutorial/java/data/strings.html. The important fact is that Strings are immutable.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James Boswell wrote:This question is more related to the behaviour of Strings as opposed to passing by value. See here about Strings: http://docs.oracle.com/javase/tutorial/java/data/strings.html. The important fact is that Strings are immutable.

Not really. The OP would have got the same result if s1 and s2 had been references to a mutable object.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Deleted - meant to edit previous post rather than quote it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic