Thursday, 12 June 2014

String Literal Pool

There are two ways to instantiate String objects in Java.
a. Literal notation
b. Using new key word

Literal Notation
String literals appears between quotes in a program. Literal string values in Java
source code are turned into String objects by the compiler.

Example
   String s1 = "abc"
   String s2 = "def"

class StringLiteral{
 public static void main(String args[]){
  String s1 = "abc";
  String s2 = "def";
  
  System.out.println("Value Of String s1 is " + s1);
  System.out.println("Value Of String s2 is " + s2);
 }
}

Output
Value Of String s1 is abc
Value Of String s2 is def

What happens when string created using literal notation
When a string is created using literal notation, then JVM checks its literal pool (Which provides shared access to String objects). If there is already a string in the literal pool with the same value, then JVM reuses the existing instance without recreating the new instance. If there is no matching instance in the literal pool then JVM creates one instance in the literal pool.

To check this, We check two reference with the same literal vale.“==” operator checks whether two references points to same object or not.

class StringLiteralEquality{
 public static void main(String args[]){
  String s1 = "abc";
  String s2 = "abc";
  String s3 = "abc";
  
  System.out.println((s1==s2));
  System.out.println((s1==s3));
  System.out.println((s2==s3));
 }
}

Output
true
true
true

Object Notation
Strings can be create using new operator also. String class provides various constructors to create string objects.
Example
   String s1 = new String(“abc”);

What happens when string created using new operator
When String is created using new operator, then two objects are created, once is in string literal pool and second one is in heap memory. If you create two String objects having same contents using new operator, then those two are different objects even though they has same content.

Example
class StringObject{
 public static void main(String args[]){
  String s1 = new String("abc");
  String s2 = new String("abc");
  String s3 = new String("abc");
  
  System.out.println((s1==s2));
  System.out.println((s1==s3));
  System.out.println((s2==s3));
 }
}

Output
false
false
false

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment