• Post Reply Bookmark Topic Watch Topic
  • New Topic

String object created twice with the same reference variable  RSS feed

 
mvPrasad Regula
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Temp {
public static void main(String[] args)
{
String a,b,c;
c= new String("mouse");
a=new String("Car");
b=a;
a= new String("Dog");
c=b;
System.out.println(c);
}
}

Here I am getting the output as Car. The same reference variable a has been instantiated twice. So the reference variable a should now point to the newly created object "Dog". As c is refering to b which is refering to a, the output is supposed to be Dog.

 
Mark Spritzler
ranger
Sheriff
Posts: 17309
11
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to Beginning Java, this is a forum for Spring Framework.

Good Luck

Mark
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mvPrasad Regula wrote:As c is refering to b which is refering to a, the output is supposed to be Dog.


Java doesn't have assignment by reference. It has assignment by value (of references). So when you do,

b = a;

this does not mean that b becomes an alias for a and that both a and b are now two symbols for the same variable. That would be a by reference assignment and Java doesn't have that.

Instead what happens is that the value held by a (a reference) is replacing the value currently held by b. Afterwards the two variables a and b hold the same value (the same reference pointing at an object). This is an assignment by value of a reference and that's what Java does.

Java doesn't do anything by reference. It does everything by value, both assignments and parameter passing. The value assigned or passed can be a reference though.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at what's happening line by line:

  • c refers to a String object containing "mouse"
  • a refers to a String object containing "Car"
  • b refers to the same String object that a refers to (the one containing "Car")
  • a is now changed to refer to a String object containing "Dog" (note that nothing has changed with b!)
  • c is now changed to refer to the same String object that b refers to (the one containing "Car")

  • So in the end, c refers to the "Car" String object.
     
    Ulrika Tingle
    Ranch Hand
    Posts: 92
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Jesper Young wrote:
    (note that nothing has changed with b!)


    You say so but what's the reason?

    Hint: Look at my reply.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!