• Post Reply Bookmark Topic Watch Topic
  • New Topic

use of assinment operator with String  RSS feed

 
Ravi Ramnath
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • 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
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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!
 
Durand Grimmett
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!