×

Java Programs

Java Practice

Comparing Strings with equals() and compareTo() methods in Java

Here, we are going to learn about the string compare methods – In this tutorial/example, we are comparing strings using equals(), compareTo() and == operator in Java.
Submitted by IncludeHelp, on July 12, 2019

Problem statement

Given strings and we have to compare them using equals() and compareTo() method.

Comparing Strings with equals() and compareTo() methods

  • Java string equals() method
    Java string equals() method compares the content of two strings, If all characters are the same, it returns true, else it returns false.
  • Java string compareTo() method
    Java string compareTo() method is called with a string and another string is supplied as an argument, it compares the strings based on the Unicode values of the characters in the strings. It returns a positive number, negative number or 0. If both strings have the same content, it returns 0.

Java program to compare the strings using equals(), compareTo() and == operator

// Comparing Strings with equals() and compareTo() 
// methods in Java

public class Main {
    public static void main(String[] args) {
        //strings
        String str1 = new String("ABC");
        String str2 = new String("PQR");

        //comparing strings using equals() method
        System.out.println(str1.equals(str2));
        System.out.println(str1.equals(str1));

        //comparing strings using == operator 
        System.out.println(str1 == str1);
        System.out.println(str1 == str2);

        //comparing strings using compareTo() method
        System.out.println(str1.compareTo(str1));
        System.out.println(str1.compareTo(str2));
    }
}

Output

false
true
true
false
0
-15

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.