0% found this document useful (0 votes)
4 views

Interning a Java

Uploaded by

risiwe3439
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Interning a Java

Uploaded by

risiwe3439
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

In Java, "interning" a string refers to the process of adding a string to the internal pool of

strings maintained by the Java Virtual Machine (JVM). When you intern a string, the JVM
checks if an equivalent string is already present in the pool. If it is, the existing string
reference is returned; otherwise, the string is added to the pool and its reference is
returned.This concept is primarily used for memory optimization and to facilitate efficient
comparison of string literals. Interning a string can be done explicitly using the intern()
method of the String class.
Here’s a brief example:
String str1 = "Hello"; // This string is automatically interned
String str2 = new String("Hello").intern(); // Explicitly interned

// Checking if both strings point to the same reference


System.out.println(str1 == str2); // This will print trueIn the example above:str1 is
automatically interned because it's a string literal.str2 is explicitly interned using the intern()
method after creating a new String object.By using string interning, you can save memory by
ensuring that duplicate strings are not unnecessarily duplicated in memory.

You might also like