-6

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
Community
  • 1
  • 1
Sandeep
  • 26
  • 3

4 Answers4

2

== on objects compares by reference. The first pair of strings was considered equal due to a feature called internalization. To compare strings for content equality, use

s1.compareTo(s2) == 0

or

s1.equals(s2)
G. Bach
  • 3,869
  • 2
  • 25
  • 46
2

There's only one instance of string constants, e.g., "ohai", so == will work.

New String objects are just that, new objects, which may be created from another string's value.

Strings should almost always be compared with .equals, e.g.

str1.equals(str2);

This compares string values, not references.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

In first case you have declared se1 and se2 as String literals. So you can use == operator to compare two Strings.

But in later case str1 and str2 are String objects and hence compairing through == operators fails. To compare two objects you should use equals method.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
1

You should not use == when comparing objects including strings. Generally == compares references, so it return true only of same objects. You should use equals() 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.

AlexR
  • 114,158
  • 16
  • 130
  • 208