String assignment differences
Can anybody know what is the difference between the following two String assignments:
String ref = "HAI"; and String obj = new String("HAI");
Can anybody know what is the difference between the following two String assignments:
String ref = "HAI"; and String obj = new String("HAI");
The second is in 99% of all cases ****, because it creates a String "HAI" and then creates a new String with the same content, which is usually just a waste of memory.
also note that
ref.equals(obj) is true while ref == obj is false
The first one might create a new String object, if that String hasn't already been used and interned, the second one definately always creates a new String object, regardless of any interning that's gone on
It's almost always inappropriate to use the second one