String Compare Java Program

Sharing is healthy !!

Today lets delve into string compare java program.

In java there are three methods to compare a string. Namely,

  • using compareTo() method
  • using equals() method
  • using == operator method

Let us understand each method with an example,

Method 1: String compareTo() method is used in sorting. compareTo() method compares value in alphabetical order and returns value that relate if first string is equal to second string or greater than or lesser than second string.

Example:

Also Read – Char Array to String Java Program

public class String_Compare_Java {

public static void main(String[] args) {
 
String str_First = "Flower";
String str_Second = "Flower";
String str_Third = "Brackets";
 
System.out.println("String Compare Java Program");

// here output will be zero since str_First == str_Second
System.out.println(str_First.compareTo(str_Second));
 
// here output will be positive value since str_First > str_Third
System.out.println(str_First.compareTo(str_Third));
 
// here output will be negative value since str_Third < str_First
System.out.println(str_Third.compareTo(str_First));
 
}

}

Output:  

String Compare Java Program

0 4 -4


Method 2: equals() method basically compares value of a string for equality. There are two methods,

  • public boolean equalsIgnoreCase(another string) – this method compares one string to another string ignoring smaller case and bigger case.
  • public boolean equals(another object) – this method compares given string to the specified object.

Example:

public class String_Compare_Java {

public static void main(String[] args) {
 
String str_First = "Flower";
String str_Second = "Flower";
String str_Third = new String("Flower");
String str_Fourth = "Brackets";
String str_Fifth = "FLOWER"; 

System.out.println("String Compare Java Program");
 
System.out.println(str_First.equals(str_Second));
 
System.out.println(str_First.equals(str_Third));
 
System.out.println(str_First.equals(str_Fourth));
 
System.out.println(str_First.equals(str_Fifth));
 
System.out.println(str_First.equalsIgnoreCase(str_Third));
 
}

}

Output: 

String Compare Java Program

true
true
false
false
true


Method 3: == operator method basically compares references(not value).

Example:

Also Read – Convert Date To String Java Program

public class String_Compare_Java {

public static void main(String[] args) {
 
String str_First = "Flower";
String str_Second = "Flower";
String str_Third = new String("Flower");
 
// here output will be true since str_First and str_Second refer to same instance
System.out.println(str_First == str_Second);
 
// here output will be false since str_Third refer to instance created
System.out.println(str_First == str_Third);
 
}

}

Output:

String Compare Java Program

Sharing is healthy !!

Leave a Reply

Your email address will not be published.