String Constant Pool

Examine the below code snippet:

package com.test.test1;
public class StringPool {
	public static void main(String[] args) {
		String str3 = "Harry";
		String str4 = "Harry";
		System.out.println(str3);
		System.out.println(str4);
	}
}

What will happen behind the scenes?

Lets validate:

package com.test.test1;
public class StringPool {
	public static void main(String[] args) {
		String s1 = "Cat";
		String s2 = "Cat";
		String s3 = new String("Cat"); 
		if(s1==s2)
		{
			System.out.println("s1 and s2 are pointing to same string "+s1);
		}
		else
		{
			System.out.println("s1 and s2 are not pointing to same string "+s1);
		}
		if(s1==s3)
		{
			System.out.println("s1 and s3 are pointing to same string "+s1);
		}
		else
		{
			System.out.println("s1 and s3 are not pointing to same string "+s1);
		}
	}
}

Problem: Count the number of strings.

Last updated