2

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.

Community
  • 1
  • 1
Jay Sithiporn
  • 91
  • 5
  • 14

1 Answers1

3

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.

kosa
  • 65,990
  • 13
  • 130
  • 167