Home > Blockchain >  Does string concatenation turn out to be compile-time constant?
Does string concatenation turn out to be compile-time constant?

Time:11-08

I study from OCP O'Reilly book for Java.

There is a statement such that:

15: String first = "rat" 1;

On line 15, we have a compile-time constant that automatically gets placed in the string pool as "rat1"

I cannot understand why concatenation operation generates compile-time constant. In my understanding, the operation should be done at run-time. What is the point I am missing?

CodePudding user response:

When Strings are created with the help of String literals and operator, they get concatenated at compile time. This is referred to as Compile-Time Resolution of Strings.

When Strings are created with the help of String literals along with variables and operator, they get concatenated at runtime only, as the value of the variables cannot be predicted beforehand. This is referred to as the RunTime Resolution of Strings.

Consider the below example

// Strings are computed in compile-time in this case.
public static void main(String[] args) {
   String first = "rat1";
   String result = "rat"   1;

   System.out.println(first == result); //prints true
}

However, in the code below, the Strings are computed in runtime because the variable one is not a constant expression:

public static void main(String[] args) {
   String first = "rat1";
   String one = "1";
   String result = "rat"   one;

   System.out.println(first == result); //prints false
}

You can also refer to this link which has a more detailed explanation. CompileTime Vs RunTime Resolution of Strings

  •  Tags:  
  • java
  • Related