What is String.equals() in Java?

The EQUALS() function takes in a string as a parameter and returns true if both the source string and parameter are equal; otherwise, it returns false.

Figure 1 shows a visual representation of the EQUALS() function.

Figure 1: Visual representation of EQUALS() function

Syntax

boolean equals(Object strObj)

string1.equals(string2)

Parameter

The EQUALS() function takes another string (string2) to be compared with string1 as a parameter.

Return value

The EQUALS() function returns true if both the strings are equal; otherwise, it returns false.

Code

class JAVA {
public static void main( String args[] ) {
String string_1 = "educative";
String string_2 = "edpresso";
String string_3 = "EDUCATIVE";
//same both strings
System.out.println("string_1.equals('educative'):");
System.out.println(string_1.equals("educative"));
//different both strings
System.out.println("string_2.equals('educative'):");
System.out.println(string_2.equals("educative"));
//same string but one is uppercase and other is lowercase
System.out.println("string_3.equals('educative'):");
System.out.println(string_3.equals("educative"));
//string2 is not string obj
System.out.println("string_1.equals(12345):");
System.out.println(string_1.equals(12345));
}
}

Free Resources