Comparing Strings With Equals() And Compareto() Methods in Java

You are currently viewing Comparing Strings With Equals() And Compareto() Methods in Java

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

// 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply