why is this statement evaluating false??
Hi all I am very new to Java and have come across a problem. im sure this is extremely simple to most of you but i just cant figure it out.
I have 2 variables, one called material and one called jewel
the material variable contains the string "diomand" and the jewel variable contains the string "diomand ring"
now the problem im having is when i execute the following into a tester: jewel == material + "ring";
it evaluates to false. I cant work out why this is because im thinking it should be true.
I understand this is a very noob question but as i said, i am very new to Java and indeed all programming.
any help is very appreciated.
many thanks
john
Re: why is this statement evaluating false??
When comparing strings (and other objects as well) you should use the equals() function, for example
Code :
if ( jewel.equals(material+" ring") ){//don't forget the space in " ring"
//do something
}
Using the == checks to see whether these two objects refer to the same instance, which may or may not be true. Using the equals() function you evaluate the contents. Note that for primitives (int, char, byte, etc...) == will work
Re: why is this statement evaluating false??
you should always use EQUALS when comparing strings.
A String is an OBJECT, when doing String == String, you are asking computer to check if they are the same 'object'.
for example:
Code :
String cat = "meow";
String tiger = "meow";
System.out.print(cat == tiger);
RETURNS: True.
Code :
String turtle = "";
//turtles are quiet.
String cat = turtle + "meow";
String tiger = "meow";
System.out.print(cat == tiger);
RETURNS: False.
The first example uses the same reference to "meow" both times while in the 2nd example the computer doesnt do this, and the objects dont match.
Just use cat.equals(tiger)
good luck