• 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
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

use of assinment operator with String

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi to all,

problem is as follows..

String ad="hi";
String ac=ad; //1
ad="bye";
System.out.println(ad+", "+ac+", "+ad);

at line commented '1' ,
why 'ac' is assingned with value of var. 'ad' insted of refernce of string object "hi"?

before running program i was expecting o/p as :
bye, bye, bye

but actual o/p is,
bye, hi, bye

plz help me understand it correctly.

bye
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ravindra,

Welcome to JavaRanch!

When you assign one variable the value of another, the contents of that second variable are copied to the first. If the second variable is a reference to an object, then the first variable is made to refer to that same object.

If you then later change the second variable, the first variable's value will not change, regardless of what kind of variable it is. In your example, making ad point to "bye" does not change ac; ac still points to "hi".

I suspect you would learn a lot by reading this and this. They're fun to read, too!
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't understand how your expected o/p was "bye bye bye"

intially the value of 'ad' is "hi"
then you assign ac=ad.......which makes ac=="hi"
finally you assign ad="bye"

so at the time of your system.out.println.......ad=="bye" and ac=="hi"
which is why you get the output of "bye, hi, bye"

if you wanted the output of "bye, bye, bye"
after the statement ad="bye"
should be the statement ac=ad........then your system.out.println()

i hope this helps

DG
reply
    Bookmark Topic Watch Topic
  • New Topic