Buddhika Chathuranga
Buddhika Chathuranga

Reputation: 1468

Will Java update Strings on creation

Since Strings are immutable in Java, will this create 3 objects, or will it internally create only one object.

How the execution will happen in the JVM and will it depend on the JVM implementation?

class Main{
    public static void main(String[] args) throws Exception{
        
        String s = "FirstString" + "SecondString" + "ThirdString";

    }
}

If the above case resolved in the compile-time how the below case works.

class Main{
    public static void main(String[] args) throws Exception{
        
        String s = "FirstString" + "SecondString" + args[0];

    }
}

Upvotes: 0

Views: 53

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308031

In this example

String s = "FirstString" + "SecondString" + "ThirdString";

the 3 constant strings concatenated with + make up a constant expression. What this means is that the compiler can know the exact result of that expression at compile time and therefore inlines the result (i.e. the resulting .class file will look as if there was just a single constant with the content FirstStringSecondStringThirdString).

Note that the exact rules as to what counts as a constant expression are not quite intuitive, so check the JLS for details, if interested.

In

String s = "FirstString" + "SecondString" + someStringVariable;

the first concatenation will be "collapsed" into simply "FirstStringSecondString" and the third concatenation will be done the "normal" way at runtime.

The specific way that String concatenation at runtime happens in Java 9 is quite complex and causes the relevant constant entry in the pool to be "FirstStringSecondString\u0001" (note the trailing \u0001 to indicate where the argument goes). But it still demonstrates that the first concatenation in this expression is resolved during compilation from .java to .class.

This leads us to realize that even

    String s = "First" + "Second" + someStringVariable + "Last";

will be optimized into a single operation, since the constant used in this case is "FirstSecond\u0001Last".

Upvotes: 5

Related Questions