DEV Community

Cover image for Can you use == for strings in java?
joshua-brown0010
joshua-brown0010

Posted on

Can you use == for strings in java?

In this article, I will explain different methods to make you understand better, of using (==) for strings in java. We can use “ == “ in java, but it has few exceptions and is clearly stated below

Approach

EqualsTo() Method

In java, we can use “ == “ operator to compare two strings which has same or different values.
In the below example, I have used two strings named str1 and str2. We have used equals to operator(==) to compare these two strings. Thus the output value is obtained.

Example 1

public  class EqualsToStrings 

{

Public static void main(String[ ] args)

{

String str1 = “Kodlogs”;

String str2 = “Kodlogs”;

if(str1 == str2)

System.out.println(“ They are equal”);

else

System.out.println(“They are not equal”);

}

}
Enter fullscreen mode Exit fullscreen mode

Output

They are equal

Equals() Method

  • Coming to example2, we have declared two String constructors to create these strings str1, str2. If we use (==) operator i.e., equals to(), then it shows wrong output, because they compare the reference of strings.
  • So we need to use equals() method for comparing two constructor strings because it compares the values of strings.

Example

public  class EqualsToStrings 

{

Public static void main(String[ ] args)

{

String str1 = new  String(“Kodlogs”);

String str2 = new String(“Kodlogs”);-

if(str1.equals(str2))

System.out.println(“ They are equal”);

else

System.out.println(“They are not equal”);

}

}
Enter fullscreen mode Exit fullscreen mode

Output

They are equal

EqualsTo() in place of Equals()

Read more

Top comments (0)