Introduction
There are two ways to compare strings in Java
[Compares references not
values]
- ".equals()" method, derived from object
class, i.e. java.lang.object.equals()
[Compares values for
equality]
Note: .equals() method is automatically
defined for each and every class, because it is defined in Object class, from
which all other classes are derived.
In the case of String, Most of the programmers are
gone in the wrong way, i.e. using "==" operator to compare equality of Strings. String is a Java
Type, it just defines an object. String is not an array of characters in java.
Syntax to define an object of String type:
String str = "This is a string object."
where str is an object of String type.
The right way of comparing equality of two
Strings: use ".equals()" method instead of "==" operator.
The following program demonstrates the above
statement
== versus .equals()
Code:
- public class JavaApplication11 {
- public static void main(String[] args) {
- String str = "CSharpCorner";
- String str1 = str;
- String str2 = new String("CSharpCorner");
- System.out.print("str.equals(str1) : ");
- if (str.equals(str1)) {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- System.out.print("str == str1 : ");
- if (str == str1) {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- System.out.print("str1.equals(str2) : ");
- if (str1.equals(str2)) {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- System.out.print("str1 == str2 : ");
- if (str1 == str2) {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- System.out.print("str1.equals(\"CSharpCorner\") : ");
- if (str1.equals("CSharpCorner")) {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- System.out.print("str1==\"CSharpCorner\" : ");
- if (str1 == "CSharpCorner") {
- System.out.println("True");
- } else {
- System.out.println("False");
- }
- }
- }
Output:
- str.equals(str1): True
- str == str1: True
- str1.equals(str2): True
- str1 == str2: False
- str1.equals("CSharpCorner"): True
- str1 == "CSharpCorner": True