Roam
Roam

Reputation: 4949

Java String class interning

When i invoke

System.out.println("print this line here");

is the String

"print this line here"

interned?

The class String has a native interning mechanism to look up every new String value (except for those instantiated by the explicit call of its constructor) in a pool of values, and create a String object of that value only if it doesn't find it in this pool.

I'm wondering how this works with String constants. So, every time i'm invoking this statement in a loop, is "print this line here" being interned-- looked up in the pool to see whether it's there ... ?

//======================

NOTE: this is similar to but different than my prev.Q here.

Upvotes: 0

Views: 59

Answers (3)

Russell Zahniser
Russell Zahniser

Reputation: 16354

String literals in code are compiled as part of the constant pool of the class. When the class file is first loaded, they are added to the String intern pool. By the time the statement is executed, it is just loading the interned string from the computed constant address.

Edit:

If you do what you suggest:

String str = new String ("print this line here");

... then you still have an interned constant string, plus a new string that is not == to the interned one.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

The relevant chapter in the Java Language Specification is here. It states

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

So, yes, the String literal "print this line here" is interned.

I'm wondering how this works with String constants. So, every time i'm invoking this statement in a loop, is "print this line here" being interned-- looked up in the pool to see whether it's there ... ?

Not exactly, byte code is a little different. What you will see is the specific reference to a String object in the class' constant pool be pushed on the stack.

You can see this in the byte code

 public static void main(java.lang.String[]) throws java.lang.Exception;    Code:
      0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      3: ldc           #3                  // String print this line here
      5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      8: return

where the ldc instruction is used to

push a constant #index from a constant pool (String, int or float) onto the stack

That constant is used in the println() method invocation.

Upvotes: 1

Trying
Trying

Reputation: 14278

String literals are compile time constants and are default interned.

Upvotes: 0

Related Questions