Using String Comparison in Java

In Java, strings can be compared in multiple ways. The most common method is the equals() method of the String class. This method checks if two strings have the same sequence of characters. It's essential to understand that the == operator compares object references, not the content, so it may not yield the expected results for string comparisons. Another method is compareTo(), which belongs to the Comparable interface that the String class implements. The compareTo() method compares two strings lexicographically. It returns a negative number if the calling string is lexicographically before the argument string, zero if they're the same and a positive number otherwise. In this Java String Compare Example, two strings have been created, and their contents are compared. Click Execute to run the Java Compare Example online and see the result.
Using String Comparison in Java Execute
public class StringComparison {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = "World";

Updated: Viewed: 46 times