new String()
will create a new instance of the object string with an own identity hash code. When creating a string like this String string = "myString";
Java will try to reuse the string by searching the already created string, for that exact string. If found, it will return the same identity hash code of this string. This will cause, that if you create e.g. a identity hash code of the string, you will get the same value.
Example:
public class Stringtest {
public static void main(String[] args) {
final String s = "myString";
final String s2 = "myString";
final String otherS = new String("myString");
//S and s2 have the same values
System.out.println("s: " + System.identityHashCode(s));
System.out.println("s2: " + System.identityHashCode(s2));
//The varaible otherS gets a new identity hash code
System.out.println("otherS: " + System.identityHashCode(otherS));
}
}
In most cases you don't need to create a new object of a string, cause you don't have static values when working with e.g. HashMap
s or similar things.
So, only create new strings with new String
when really needed. Mostly use String yourString = "...";
.