Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

What is the difference between these codes?

 
Ranch Hand
Posts: 32
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";
 
Ranch Hand
Posts: 40
2
Eclipse IDE Oracle Java
  • 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
 
Ranch Hand
Posts: 182
18
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic