How to compare strings in Java
The Java language provides many different ways to perform string comparisons.
The equals method returns true if two strings have the same text, false otherwise.
The method s1.compareTo(s2) returns a negative value if s1 precedes s2, zero if s1 is equal to s2, and a positive value otherwise.
The example shows how to use the equals and compareTo methods:
public class CompareStringsTest
{
public static void main(String[] args)
{
String c1 = "Atene";
String c2 = "Zurich";
String n1 = "Albert";
String n2 = "Albert";
System.out.println("c1 = "+c1);
System.out.println("c2 = "+c2);
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);
System.out.println("------------------------------------------");
System.out.println("c1.compareTo(c2) = " + c1.compareTo(c2));
System.out.println("c2.compareTo(c1) = " + c2.compareTo(c1));
System.out.println("c1.equals(c2) = " + c1.equals(c2));
System.out.println();
System.out.println("n1.compareTo(n2) = " + n1.compareTo(n2));
System.out.println("n1.equals(n2) = " + n1.equals(n2));
System.out.println();
System.out.println("n1.compareTo(c1) = " + n1.compareTo(c1));
System.out.println("n1.equals(c1) = " + n1.equals(c1));
}
}
This is the result you get:
c1 = Atene
c2 = Zurich
n1 = Albert
n2 = Albert
------------------------------------------
c1.compareTo(c2) = -25
c2.compareTo(c1) = 25
c1.equals(c2) = false
n1.compareTo(n2) = 0
n1.equals(n2) = true
n1.compareTo(c1) = -8
n1.equals(c1) = false
Category: Java