Java String Intern Method Example

String manipulation is one of the most read and confused subject for the Java programmers. String literals are stored in the string pool where identical objects are pointing to the same reference. If you look at the below example, we have created the “JavaBeat” string using the literals and “new” operator. When we create the string literals, identical literals are pointing to the same location, it will never create the new object in the memory. When we use the “new” operator, it creates the new object in the memory. But, if you are using the intern() method on string objects, it will return the object from the string pool instead of creating a new object. If you look at the below example, you could easily understand it better.

package javabeat.net.core;

/**
 * String intern() example
 * @author krishna
 *
 */
public class StringInternExample {
	public static void main(String args[]){
		String str1 = "JavaBeat";
		String str2 = "JavaBeat";
		String str3 = new String("JavaBeat");
		String str4 = new String("JavaBeat").intern();
		System.out.println(str1==str2);
		System.out.println(str1==str3);
		System.out.println(str1==str4);
	}
}

Output…

true
false
true

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!