What does intern() method in java?



The intern() method of the String method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.

For any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned.

Example

 Live Demo

import java.lang.*; public class StringDemo {    public static void main(String[] args) {       String str1 = "This is TutorialsPoint";       // returns canonical representation for the string object       String str2 = str1.intern();             // prints the string str2       System.out.println(str2);             // check if str1 and str2 are equal or not       System.out.println("Is str1 equal to str2 ? = " + (str1 == str2));    } }

Output

This is TutorialsPoint Is str1 equal to str2 ? = true
Updated on: 2019-07-30T22:30:21+05:30

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements