Q:

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

belongs to collection: Java String Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Java code 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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
String palindrome program in Java... >>
<< Uppercase to lowercase conversion without using an...