0

Possible Duplicate:
How do I compare strings in Java?
Java String.equals versus ==

I am new to Selenium and Java.

I have tried the below to compare the field value of last name to the one which i supplied.

String lastname=selenium.getValue("//*[@id='lastName']");
System.out.println(lastname);
assertTrue (lastname == "xxx");

It is keep on failing.

Just literally tried to change the last line with help of Eclipse (just trial and error)

assertTrue("lastname.equals("xxx")); 

It is working fine... Why it is failed in first case? == is not allowed to compare strings?

Community
  • 1
  • 1
ChanGan
  • 4,254
  • 11
  • 74
  • 135

5 Answers5

2

Short answer: == checks for same object .equals checks for the same value.

More info in How do I compare strings in Java?

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
0

equals function checks the actual contents of the lastname. == operator checks whether the references to the objects are equal.

Chandana
  • 2,578
  • 8
  • 38
  • 55
0

You must use equals() to compare strings with Java, as you guessed.

Arcadien
  • 2,258
  • 16
  • 26
0

You're actually comparing pointers (or really reference equality) when you use == with strings. In other words you're testing if two objects are the same, rather than the content of the objects.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
0

For comparing equality of string ,We Use equals() Method. There are two ways of comparison in java. One is "==" operator and another "equals()" method . "==" compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39