0

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];

    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Buddhika Chathuranga
  • 1,334
  • 2
  • 13
  • 22

1 Answers1

5

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".

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 1
    I don’t think that [the exact rules as to what counts as a constant expression](https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.29), i.e. “*A **constant expression** is an expression denoting a value of primitive type or a `String` that does not complete abruptly and is composed using only the following:*”, followed by an explicit list of constructs, is unintuitive. – Holger Jun 02 '21 at 17:40
  • @Holger: the primary reason it's unintuitive is that sometimes a field `x` is constant or not depending on when / how it was initialized. `final static int x = 3;` makes `x` a constant expression whereas `final static int x; static { x = 3 };` makes `x` *not* a constant expression. – Joachim Sauer Jun 02 '21 at 19:40
  • 1
    Given that the `static {}` block could be anywhere in the source file and the assignment be buried between other statements, I think it’s not so much surprising that a compile-time constant requires an *initializer* that is always directly at the declaration, rather than an *assignment* that could be anywhere. Only deliberately placing the block directly after the variable declaration makes it look similar. – Holger Jun 03 '21 at 06:48
  • @Holger: yes, with enough know-how and understanding all problems become shallow. All the rules make sense when inspected in detail. But that's still quite a bit different from being "intuitive". Two examples that look very similar behave quite differently. That's what I'd call unintuitive. – Joachim Sauer Jun 03 '21 at 06:49
  • 1
    Sounds like a self-fulfilling prophecy. Instead of spreading “enough know-how and understanding”, we discourage people by calling the rules “unintuitive”, only to find there are people not understanding the rules, indicating that the rules were unintuitive. – Holger Jun 03 '21 at 06:57
  • You know what: I've chosen the wording for my answer, heard your critique and chose to keep it. I stand by it. I chose that description based on the number of questions I see where people *are* confused by it. – Joachim Sauer Jun 03 '21 at 07:07