Table of contents
1.
Introduction
2.
intern() Method
2.1.
Syntax
2.2.
Parameters
3.
Working Of The String intern() Method
3.1.
Example-1
3.1.1.
Output
3.2.
Example-2
3.2.1.
Output
4.
Frequently Asked Questions
4.1.
What are mutable and immutable objects in Java?
4.2.
Can we compare strings using the == operator? What is the risk?
4.3.
What Is the String Constant Pool?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java String intern() Method

Author Akash Nagpal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A string is just a series of characters(char). In Java, the string is a Class, not a data type like 'int & char'. Thus, the String class represents String characters, and all string objects in Java are instances of this type. The string class is the most useful in Java programming and Selenium WebDriver. In tzhis blog, we will learn about the String class' getChars() Method in Java with the help of a few examples.

intern() Method

The intern() function of the Java String class returns the interned string. It returns the string's canonical representation.

If a new keyword generates it, it can be used to return a string from memory. It duplicates the heap string object in the String Constant Pool.

Syntax

public String intern()  

Parameters

Here is a list of parameters:

  • srcBegin is the index of the first char to copy in the string.
  • srcEnd indexes after the final character to be copied in the string.
  • dst is the array's destination.
  • dstBegin is the offset at which the destination array begins.Return

It returns an interned string, so the return value is a string.

Must Read: Java System Out Println

Working Of The String intern() Method

When a string is initialized in Java, it takes up heap memory. We also know the String class is immutable. As a result, anytime we use the new keyword to construct a string, fresh memory is created in a heap for the matching string, regardless of the array's content. Consider the following line of code: 

String str = new String("Welcome to Coding Ninjas Studio.");   
String str1 = new String("Welcome to Coding Ninjas Studio");  
System.out.println(str1 == str); // prints false  

In the above snippet, since each string literal is given its memory, the println command returns false. As a result, two new string objects, str and str1, are generated in memory, each with a distinct reference.

 

In Java, we know that constructing an object is an expensive process. Java developers devised the notion of String Constant Pool (SCP) to save time. The SCP is a section of heap memory. It contains distinct strings. The intern() function must be used to insert strings into the string pool. Before generating an object in the string pool, the JVM checks to see if the string is already existing. If the string exists, the reference to it is returned.

String str = new String("Welcome to Coding Ninjas Studio").intern(); // statement - 1  
String str1 = new String("Welcome to Coding Ninjas Studio").intern(); // statement - 2  
System.out.println(str1 == str); // prints true  

The intern() function is called on the String objects in the above code sample. As a result, memory is allocated in the SCP. Because the contents of str and str1 are identical in the second statement, no new string object is generated. As a result, str1 receives the reference to the object generated in the first statement. As a result, str and str1 both refer to the same memory. As a result, the print assertion is true.

Example-1

public class InternExample
{  
public static void main(String args[])
{  
String str1=new String("Hello Ninja");  
String str2="Hello Ninja";  
String str3=s1.intern();
//it will return string from pool, therefore it will be same as str2  

System.out.println(str1==str2);
//it will be false because reference variables are pointing to different instance  

System.out.println(str2==str3);
//true because reference variables are pointing to same instance 

}
} 

Output

false
true

Example-2

public class InternExample2 {  
    public static void main(String[] args) {          
        String s1 = "Coding Ninjas Studio";  
        String s2 = s1.intern();  
        String s3 = new String("Coding Ninjas Studio");  
        String s4 = s3.intern();          
        System.out.println(s1==s2); // it will return True  
        System.out.println(s1==s3); // False  
        System.out.println(s1==s4); // it will return True  
        System.out.println(s2==s3); // False  
        System.out.println(s2==s4); // it will return True       
        System.out.println(s3==s4); // False          
    }  
}  

Output

true
false
true
false
true
false


Must Read:  String Args in Java

Frequently Asked Questions

What are mutable and immutable objects in Java?

The value of mutable objects can be altered. Mutable objects include the StringBuilder and StringBuffer. Once created, the value of an immutable object cannot be modified. In Java, a string is an immutable class.

Can we compare strings using the == operator? What is the risk?

Yes, we can use the == operator to compare Strings. When we compare strings with the == operator, we are comparing their object references, determining whether these string variables correspond to the same string object.

Most of the time, developers wish to compare the content of strings, but they compare strings with the == operator rather than the equals() function, which results in an error.

What Is the String Constant Pool?

The String constant pool, sometimes known as the String intern pool, is a specific memory location where the JVM saves String instances.

Conclusion

In this article, we have extensively discussed the String intern() method in Java Programming. We have also discussed its syntax, parameters as well as the return type with the help of examples. We hope this blog has helped you enhance your knowledge regarding string methods in Java Programming. Some official documentation on big data that can help you improve your understanding is String isEmpty().

If you would like to learn more, check out our articles on String contains(), and String format().  Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Recommended Reading - Canonical Cover In DBMS.
 

Recommended problems -

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass