Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Java's String.intern()?

Tags:

java

string

I know there are two ways of creating String in Java:

String a = "aaa";
String b = new String("bbb");

With the first way Java will definitely create a String object in the string pool and make a refer to it. (Assume "aaa" wan't in the pool before.)

With the second method, an object will be created in the heap, but will jvm also create an object in the string pool?

In this post Questions about Java's String pool, @Jesper said:

If you do this:

String s = new String("abc");

then there will be one String object in the pool, the one that represents the literal "abc", > and there will be a separate String object, not in the pool, that contains a copy of the > content of the pooled object.

If that's true, then every time with the new String("bbb");, a object "bbb" is created in the pool, which means by either way above, java will always create a string object in the pool. Then what is intern() used for ? In the docs http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern(), it says:

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

That means there are cases that a string is not in the pool, is that possible ? Which one is true ?

like image 709
trojantale Avatar asked Mar 18 '14 07:03

trojantale


People also ask

What is String intern () method used for?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

What does intern do in Python?

Interned objects are pre-created objects in memory that can be accessed from anywhere in your program. Before creating a new object in memory, Python will check to see if it already exists as one of these intern objects.

How is Java's string pool used?

Why do we need String Pool in Java? It is created to decrease the number of string objects created in the memory. Whenever a new string is created, JVM first checks the string pool. If it encounters the same string, then instead of creating a new string, it returns a reference existing string to the variable.

What is the use of intern () method show with small example?

Java String intern() method explained with examples This method ensures that all the 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.


2 Answers

As you know that String is an immutable object in Java programming language, which means once constructed can not be altered. Due to this, JVM has the ability to maintain a literal pool which is helpful to reduce the memory usage and to increase the performance. Each time when a String literal is used JVM checks the literal pool. If the literal is already available, the same reference would be returned. If the literal is not available, a new String object will be created and added in the literal pool.

This theory is applied when you try to create a String like a primitive or a literal/constant.

String str = "bbb";

But when you create a new String object

String str = new String("bbb");

the above mentioned rules are overridden and a new instance is created always.

But the intern API in the String class can be used to pick the String reference from the literal pool even though you create a String using new operator. Please check the below given example. Although the str3 is created using new operator since we used the intern method JVM picked up the reference from the literal pool.

public class StringInternExample {

    public static void main(final String args[]) {

        final String str = "bbb";
        final String str1 = "bbb";
        final String str2 = new String("bbb");
        final String str3 = new String("bbb").intern();

        System.out.println("str == str1 : "+(str == str1));
        System.out.println("str == str2 : "+(str == str2));
        System.out.println("str == str3 : "+(str == str3));
    }
}

Output of above code:

str == str1 : true
str == str2 : false
str == str3 : true

You can have a look: Confusion on string immutability

Source of answer: http://ourownjava.com/java/java-string-immutability-and-intern-method/

Shishir

like image 168
Shishir Kumar Avatar answered Sep 23 '22 17:09

Shishir Kumar


There are essentially two ways that our String objects can enter in to the pool:

  • Using a literal in source code like "bbb".
  • Using intern.

intern is for when you have a String that's not otherwise from the pool. For example:

String bb = "bbb".substring(1); // substring creates a new object

System.out.println(bb == "bb");          // false
System.out.println(bb.intern() == "bb"); // true

Or slightly different:

System.out.println(new String("bbb").intern() == "bbb"); // true

new String("bbb") does create two objects...

String fromLiteral = "bbb";                     // in pool
String fromNewString = new String(fromLiteral); // not in pool

...but it's more like a special case. It creates two objects because "bbb" refers to an object:

A string literal is a reference to an instance of class String [...].

Moreover, a string literal always refers to the same instance of class String.

And new String(...) creates a copy of it.

However, there are many ways String objects are created without using a literal, such as:

  • All the String methods that perform some kind of mutation. (substring, split, replace, etc.)
  • Reading a String from some kind of input such as a Scanner or Reader.
  • Concatenation when at least one operand is not a compile-time constant.

intern lets you add them to the pool or retrieve an existing object if there was one. Under most circumstances interning Strings is unnecessary but it can be used as an optimization because:

  • It lets you compare with ==.
  • It can save memory because duplicates can be garbage collected.
like image 32
Radiodef Avatar answered Sep 22 '22 17:09

Radiodef