javastringinstantiation

is "someString" equivalent to new String("someString")? in java


I always thought that an expression like this in java:

String tmp = "someString";

is just some kind of "syntactic sugar" for

String tmp = new String("someString");

As I recently decompiled my java app, I saw that ALL usages of

public static final String SOME_IDENTIFIER = "SOME_VALUE";

are replaced in code by just the value and the static final variable is stripped.

Doesn't instantiate this a new String everytime one wants to access the static final? How can this be considered as an "compiler optimization"??


Solution

  • String literals in Java source are interned, meaning that all literals with the same text will resolve to the same instance.

    In other words, "A" == "A" will be true.

    Creating a new String instance will bypass that; "A" == new String("A") will not be true.