BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String intern() method

Last Updated: June 9, 2024 by Chaitanya Singh | Filed Under: java

Java String intern() method is used to manage memory by reducing the number of String objects created. It ensures that all same strings share the same memory.

For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance.

How intern() Works

When you use intern() method on a String, it does following in order:

  1. It checks if an identical string is already present in the intern pool.
  2. If It finds an identical string in the pool, instead of creating new string, it returns the reference from the pool.
  3. If it doesn’t find an identical string, it adds the string to the pool and returns the reference to this new entry.

Basic Syntax

String internedString = str.intern();

Java String intern() method Examples

1. Creating intern String using intern() method and literal

In this example:

  • str1 is a new string object.
  • str2 is a string literal, these are automatically interned, which means creating string literal is same as calling intern() method on an identical string.
  • str3 is created using intern() on str1, which makes str3 reference the same interned string as str2.
public class Example{  
public static void main(String args[]){
String str1 = new String("Hello");
String str2 = "Hello";
String str3 = str1.intern();

System.out.println(str1 == str2); // Output: false
System.out.println(str2 == str3); // Output: true

}
}

2. Memory management using intern() method

Here, strings str1 and str2 are two different objects with the same content. Calling intern() method on any of these strings would point to the same interned string.

public class Example{  
   public static void main(String args[]){  
	String str1 = new String("BeginnersBook");
        String str2 = new String("BeginnersBook");

        // Output: false as these strings are created 
        // without calling intern() method
        System.out.println(str1 == str2);

        String str3 = str1.intern();
        String str4 = str2.intern();

        // Output: true as these strings are created 
        // after calling intern() method on identical strings
        System.out.println(str3 == str4); 
   }
}

Benefits of Using intern() method

  1. Memory management: By using intern() method, you can save memory as identical strings share the same memory space.
  2. Faster Comparisons: The strings created using intern() method are called Interned strings, these can be compared using ==, which is faster than equals() method.

Caveats

  1. Performance issue: If interning is done on large number of strings frequently, it can cause a performance overhead.
  2. Garbage Collection: The Interned strings are not eligible for garbage collection so they can potentially cause memory leaks if not use correctly.

Practical Use of intern() method.

It can be used in XML parsing or database applications where there are large number of identical strings.

❮ Java String Class

Top Related Articles:

  1. String Concatenation in Java
  2. Java String charAt() Method example
  3. Java String endsWith() Method with example
  4. Java String indexOf() Method
  5. Java String equals() and equalsIgnoreCase() Methods example

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap