Monday, 19 September 2011

Java Constant Pool : String


For those who already experienced in Java Programming should already familiar with the concept of String constant pool.
String s1 = “jim”;
String s2 = “jim”;

System.out.println(s1==s2); // true.
Object s2 is the same object with s1. But if you create using new operator:
String s1 = “jim”;
String s2 = new String(“jim”);
System.out.println(s1==s2); //false.
It will allocate new Object instead getting from String constant pool.
Another sample:
String s1 = “jim”;
String s2 = “j”+”im”;String s3 = “j”;
String im = “im”;
s3+= im;
System.out.println(s1==s2); //true.System.out.println(s1==s3); //false.
Concatenation during runtime will create new String Object.
Sample if using final modifier:
final String s1 = “j”;
final String s2 = “im”;
String jim = “jim”;
System.out.println(s1+s2 == jim); // returns true: Constant expression.
String s3 = “j”;
String s4 = “im”;
System.out.println(s3 + s4 == jim); // returns false: Not a constant expression.
Concatenation of 2 final String is a Constant.
Although is not necessary for us programmer to know about the detail of JVM implementation about String Constant Pool. Some would say “I’m not stupid, I used equals to check equality of Strings. And I don’t really care how JVM in my OS implemented the damn Constant Pool”. But for me knowing this knowledge is something great, and somehow I think it will help me in the future :)
More information about this : JLS – Lexical Structure
  • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).

  • Literal strings within different classes in the same package represent references to the same String object.

  • Literal strings within different classes in different packages likewise represent references to the same String object.

  • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

  • Strings computed by concatenation at run time are newly created and therefore distinct.
References Url :
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5
http://java.sun.com/docs/books/vmspec/html/ConstantPool.doc.html

No comments:

Post a Comment