Possible Duplicate:
Questions about Java’s String pool
What’s the difference between the two ways of declaring strings in Java?
String se1 = "java";
String se2 = "java";
System.out.println(se1 == se2); // output true
String str1 = new String("OKAY");
String str2 = new String("OKAY");
System.out.println(str1 == str2); // output false
You should not use
==when comparing objects including strings. Generally==compares references, so it returntrueonly of same objects. You should useequals()method instead:str1.equals(str2)It occasionally works for you in first case because java caches string constants, so
"java"in both cases is represented by same instance of String.