• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the difference between these codes?

 
Nil. Hatamova
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends!
What is the difference between these codes?
1.


2.
Why in the second code s1 does not change but in the first code it changes?
1.output is one two three
2.output is one two one three

But i thought output for second code will be "one two one two three";
 
Kaleem Anwar
Ranch Hand
Posts: 40
2
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nil. Hatamova wrote:Why in the second code s1 does not change but in the first code it changes?
1.output is one two three
2.output is one two one three

But i thought output for second code will be "one two one two three";


The thing you are missing is in the second code, when s1 is passed to alter method it is treated as a local method reference variable referring to "one" , once the alter methods changes the s1 like s1 = s1 + "two" , s1 start referring to a different object on heap whereas the original s1 string remain unchanged still referring to "one"and that's why its result in this one two one three. Hope you understand.

Regards,
Kaleem
 
Ramya Subraamanian
Ranch Hand
Posts: 178
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the second class

Java uses pass by value, a copy of the reference is passed to the alter() method. And the above line creates a new string object with contents "one two", that the copy of the reference now points to. But the original reference in the start method still points to "one" and hence the output "one two one three".

These links should give you some idea
http://theopentutorials.com/post/uncategorized/passing-string-as-parameter-to-a-method/
search for "Passing Strings" in this link - http://www.cs.utoronto.ca/~dianeh/tutorials/params/
http://www.javaranch.com/campfire/StoryPassBy.jsp
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic