Java.lang.String.intern() Method

Advertisements


Description

The java.lang.String.intern() 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.

Declaration

Following is the declaration for java.lang.String.intern() method

public String intern()

Parameters

  • NA

Return Value

This method returns a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Exception

  • NA

Example

The following example shows the usage of java.lang.String.intern() method.

package com.tutorialspoint;

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));
  }
}

Let us compile and run the above program, this will produce the following result:

This is TutorialsPoint
Is str1 equal to str2 ? = true



Advertisements
Advertisements