Strings

From Suhrid.net Wiki
Revision as of 01:57, 21 August 2011 by Suhridk (talk | contribs) (→‎Intro)
Jump to navigationJump to search

Intro

  • A string is a sequence of characters.Each character is a 16-bit Unicode character.
  • Strings are immutable.

String Pool

  • To save memory the JVM reserves a memory area called the String pool - for all the String literals and String valued constant expressions.
  • The String Pool is nothing but a collection of references to String objects on the heap.
  • When the class loads, the JVM examines all String literals, and checks the pool to see if an identical String exists, if yes the reference will be made to point to the existing object in the pool. If not it creates a new String object on the heap and stores a reference to it in the pool. See below, str1, str2 and str3 are string literals in the pool.
	        String str1 = "herpderp";
		String str2 = "herpderp";
		String str3 = "derpherp";
		
		System.out.println(str1 == str2); //prints: true
		System.out.println(str2 == str3); //prints: false
  • However when new is used to build a string, the JVM will not look into the pool, but create a new String object on the heap.
String str1 = "herpderp";
String str4 = new String("herpderp");
System.out.println(str1 == str4); //prints: false


  • The intern method: When the intern method is invoked on a String object, if the String pool already contains a string equal to this String object, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
String str1 = "herpderp";
String str4 = new String("herpderp");
System.out.println(str1 == str4); //prints: false
//Let's intern str4 in the pool, now str1 and str4 share the same object.
str4 = str4.intern();
System.out.println(str1 == str4);