• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

What is the difference between these codes?

 
Ranch Hand
Posts: 32
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
I got this tall by not having enough crisco in my diet as a kid. This ad looks like it had plenty of shortening:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic