I was viewing an online course on Udemy where the instructor provided the following examples for String Interning.
Example 1:
String s1 = "hel" + "lo"; // This is interned by JVM
Example 2:
String s1 = "lo";
String s2 = "hel" + s1 ; // This is not interned automatically by JVM
What is the difference between the above two code snippets? Why one is interned but the other is not interned?
As per the explanation of the instructor, in the first example, the value of s1
is known at compile time, but in the second example the value of s2
is known at run time. Why is that?