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.


 * 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();



Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!