next up previous
Next: Note on comparisons: lexicographic Up: Unit 05 Previous: Conditional expression

Note on comparisons: equality between strings

To test whether two strings (i.e., two objects of the class String) are equal, we have to use the equals() method. It would be wrong to use ==.

Example:

String input;
...
if (input == "YES") { ... }        // This is WRONG!!!
if (input.equals("YES")) { ... }   // This is CORRECT!!!

Indeed, == tests the equality between two references to an object, and this corresponds to test the identity of the two objects (i.e., that the two objects are in fact the same object). Instead, equals() tests that the two objects have the same content (i.e., that the two strings are constituted by the same sequences of characters).

Example:

String s = new String("pippo");
String t = new String("pippo");
String w = s;

System.out.println("s == w? " + s == w);           // TRUE
System.out.println("s == t? " + s == t);           // FALSE
System.out.println("s equals t?" + s.equals(t));   // TRUE


next up previous
Next: Note on comparisons: lexicographic Up: Unit 05 Previous: Conditional expression