String s1 = "Java";
This creates a string literal. The JVM looks for "Java"
in the String Constant Pool.
If it finds it, s1
will point to that existing string.
If not, it creates a new string "Java"
in the pool and s1
will point to it.
String s2 = new String("Java");
This always creates a new String
object in the heap memory, regardless of whether "Java"
is in the pool or not.
Consider this code:
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2); // true (both point to the same object in the pool)
System.out.println(s1 == s3); // false (s3 is a new object in the heap)
Regards:
Trilochan Tarai
#Java #InterviewQuestions #StringHandling #CoreJava #SoftwareDevelopment #CodingInterview #TechJobs #JavaDeveloper #silansoftware #codeintervu
No comments:
Post a Comment