DEV Community

loading...
Cover image for Can you use == for strings in java?

Can you use == for strings in java?

joshuabrown0010 profile image joshua-brown0010 ・1 min read

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

Discussion (1)

pic
Editor guide
Collapse
zoedreams profile image
☮️✝️☪️🕉☸️✡️☯️

the == in java is mostly used to compare object types with reflection etc.. however you can use it compare literal string under the hood it uses string compare library, so its much faster to implement that directly.

docs.oracle.com/javase/tutorial/ja...