RARE pic of String’s Pool party


(Series on String Pool – Part 4 of 4)

I know, its late, but it took us a while to get thisĀ RARE pic for you.

In this (gossip) blog post, you’ll find out, who managed to let their hair down on the the New Year Eve’s String Pool party, hosted by the JVM. A you know, the ‘String Pool’ party is EXCLUSIVELY for the String literals.

But do you think its open to the String literals defined in ALL scopes?

Let’s see whether the String literals assigned to a local, instance or static variable, or passed as method arguments, were permitted in the String pool.

All of the following claimed to be invited by JVM:

(1) String literals assigned to local variables


(2) String literals passed as method arguments

(3) String literals assigned to instance variables


(4) String literals assigned to static variables



Now here is the rare pic of this party, exclusively for you!

As you can see, all String literals, irrespective of the scope in which they are defined, made it to the String pool.

The preceding pics and concepts will help you to answer questions on String Pool in the OCA Java Certification. For example, the following code will output ‘true’ thrice:

class EJavaGuruSPool3 {
	static String staticStr = "eJavaGuru.com";       // static variable
	String instanceStr = "eJavaGuru.com";            // instance variable

	public static void main(String args[]) {
		SPool3 sPool = new SPool3();
		sPool.aMethod(staticStr);                // static variable passed as method parameter
		sPool.aMethod(sPool.instanceStr);        // instance variable passed as method parameter
		System.out.println(staticStr == sPool.instanceStr);
	}

	void aMethod(String paramStr) {
		String localStr = "eJavaGuru.com";        // local variable
		System.out.println(localStr == paramStr);
	}
}

Here’s a quick question for your to answer.

What is the output of the following code?

 

class SPool4 {
	public static void main(String args[]) {
		final String local1 = "eJava";         // local1 variable in main
		final String local2 = "Guru.com";      // local2 variable in main
		SPool4 sPool = new SPool4();
		sPool.aMethod(local1 + local2);
	}

	void aMethod(String paramStr) {
		String localStr = "eJavaGuru.com";        // local variable in aMethod
		System.out.println(localStr == paramStr);
	}
}

 

Happy Coding!

Mala Gupta
Author of Manning’s OCA Java SE 8 Programmer I Cert book

Leave a Reply

Your email address will not be published. Required fields are marked *