compare string with equals method and == [duplicat

2019-07-10 08:00发布

Possible Duplicate:
How do I compare strings in Java?
Java String.equals versus ==

I am newbie Java programming and I have a little question about compare string with equals method and ==

Example 1: Doesn't work when get input from user but if it has set initial value it works fine.

if(str1 == str2) 
 System.out.println("equal");

Example 2: always works

if(str1.equals(str2))
 System.out.println("equal");

if I have to compare string which command can be used.

标签: java
1条回答
来,给爷笑一个
2楼-- · 2019-07-10 08:33

String literals points to same location/value, thats why == on string literals works

When you get input from user, it will be treated as new String object.

equals() check for values equality whereas == check for reference equality.

查看更多
登录 后发表回答