HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Java String intern() method example

Java String intern() method example

The Java String intern() return the reference of a equal string literal present in string pool. If there is an existing string literal present in string pool then it’s reference is returned. Otherwise a new string with same content is created and the reference of new string is returned.

String equality is checked with String.equals() method.

1. String pool

String pool is a reserved memory area in heap memory which Java uses for storing string constants. Note that Java strings are immutable by default.

Java stores only one copy of every distinct String value in the string pool. It helps to reuse String objects to save memory during program execution. There may be many references to a string in running program, but there will be only copy of string inside string pool.

1.1. Two ways to create string

In Java we can create strings in two ways.

String str1 = new String("hello world");

String str2 = "hello world";

In above example, both ways are used to create strings, but later is recommended which uses string literals. String literals always go to string pool.

When we create string with new keyword, two objects will be created i.e. one in the Heap Area and another in the String constant pool. The created string object reference always points to heap area object.

To get the reference of same object created in string pool, use intern() method.

2. Java String intern() method

The String.intern() returns a reference to equal string literal present in string pool.

As we know that all string literals are automatically created in String pool, so intern() method is applicable to String objects created via 'new' keyword.

String intern() is native method. By the help of intern() method, we can get the reference of corresponding String constant pool object of an original string object.

3. Java String intern() example

Java program intern a string with String.intern() method.

public class StringExample 
{
    public static void main(String[] args) 
    {
        //String object in heap
        String str1 = new String("hello world");
        
        //String literal in pool
        String str2 = "hello world";
        
        //String literal in pool
        String str3 = "hello world";
        
        //String object interned to literal
        //It will refer to existing string literal
        String str4 = str1.intern();
        
        
        System.out.println(str1 == str2);       //false
        System.out.println(str2 == str3);       //true
        System.out.println(str2 == str4);       //true
    }
}

Program output.

false
true
true

In this example, we learned to intern a string in Java. This is native method and provides very high performance.

References:

A Guide to Java String
String Java Doc

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Jim Forsyth

    August 6, 2020

    Is it really true that “When we create string with new keyword, two objects will be created i.e. one in the Heap Area and another in the String constant pool.”
    There would seem to be little need for an exposed intern() method if ‘new’ also creates a pooled object.

    • Lokesh Gupta

      August 7, 2020

      That’s true. intern() is a legacy method. And for the same reason, you will not see its use anywhere (probably few places in JDK).

  2. Namrata Maradkar

    June 18, 2020

    But we can get a reference from String pool by using String literal.. we can so String str = “hello world”; this will return reference from pool. Why do we even need intern() method to get literal String ?

    • Lokesh Gupta

      June 18, 2020

      Probably, its the reason we never see its use in real-world applications.

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)