I have to get something straight. Please tell me if I'm correct:
String a;
String b;
a = b means that b takes the value of a?
And
b = a means that a takes the value of b?
I'm awkwardly confused about this & I'd appreciate an explanation.
I have to get something straight. Please tell me if I'm correct:
String a;
String b;
a = b means that b takes the value of a?
And
b = a means that a takes the value of b?
I'm awkwardly confused about this & I'd appreciate an explanation.
Generally, a = b
means "a
becomes b
". However, this is only part of the story when we talk about Object
s (as opposed to primitives). After the assignment both variables or fields reference the same object. When object allows changes (which String
does not) any changes you perform on a
take an effect on b
as well, and vice versa.
This can be illustrated with a simple diagram:
In Java, String a; declaration meaning , a is a reference variable of type String object in memory.
In your case, both a and b are String reference variables.
1) a = b , means a gets the reference of b. if b has any value, it will be assigned to a.
2) b = a , means b gets the reference of a. if a has any value, it will be assigned to b.
It can be easily tested with simple java program if you have started learning in Java.
Java Example:
package test;
public class TestString {
public static void main(String args[]) {
String a = "Stack";
String b = "Overflow";
a = b;
System.out.println("after [a=b]:" + "a =" + a + ";b=" + b);
//after this a and b has Overflow as value.
b = a;
System.out.println("after [b=a]:" + "a =" + a + ";b=" + b);
}
}
output:
after [a=b]:a =Overflow;b=Overflow
after [b=a]:a =Overflow;b=Overflow