Need help understanding how Java uses expressions and how they evaluate
Hi,
Hopefully this is a simple one. I have a section of code:
int x = 17;
int y = 9;
String name = "Robinson";
String bird = "Robin";
My task is to explain what each expression evaluates to, but more importantly why. The 2 expressions I am having trouble with are:
name == bird + "son";
and
name.equals(bird + "son");
I have checked both statements in the application I am using and the first statement evaluates to False and the second evalutes to True. I'm not really undestanding how these expressions are working as I would expect both statements to evaluate as true?
Any help is greatly appreciated! :)
thanks
Re: Need help understanding how Java uses expressions and how they evaluate
The == operator compares the values of the reference pointers to see if they both refer to the same object.
The equals methods compares the contents of the two objects pointed to by the reference pointers.
name and bird are what I am calling reference pointers. They have the address of String objects that contain Strings. You'd test if they both have the same address using the == operator.
For example:
name = "X";
bird = name;
Now bird == name is true. They both point to the same object.
Re: Need help understanding how Java uses expressions and how they evaluate
Hi,
thanks very much for the reply. I think I understand what you are saying there. I'm still having trouble understanding why the statement:
name == bird + "son";
evaluates to False, I have got to that answer by running the code through the application I am using.
The way I am reading it would suggst an answer of True, in that name = Robinson, bird + son would be Robin and son, so Robinson, but I guess I'm missing something with how the "+" operator works in this example?
Am I missing something here?
Cheers
Re: Need help understanding how Java uses expressions and how they evaluate
If there are two String objects with the same contents, equals() will return true, == will return false.
equals() compares the contents, == compares the locations of where the objects are located.
Re: Need help understanding how Java uses expressions and how they evaluate
ahh, great, got it!
Thanks for the help :)