Problem on String – Set II

      No Comments on Problem on String – Set II




final variable values replace the variable with its value during compile time itself. This can be verified if the compiled class is seen.

Let’s take an example to understand it.

package com.masterjavatutorial;

public class TestExample {
	public static void main(String[] args){
        String str = "This is test example";
        final String str1 = "This is ";
        String str2 = str1 + "test example";
        System.out.println(str == str2); 
        
 	}
}

Output of the above method is as below:

true

Why does str and str2 points to the same String object in above example?

Let’s see the three lines of code below.

String str = "This is test example";
final String str1 = "This is ";
String str2 = str1 + "test example";

After compilation of the class, String str2 = “This is test example”; It is because str1 is a final variable and hence the variable str1 will be replaced by its value during compile time itself.
Now, str and str2 are two String objects references pointing to the same String object in the String pool and hence, it gives the output as true.