Java intern () method, javaintern Method

Source: Internet
Author: User

Java intern () method, javaintern Method

Intern () method:

Public String intern ()

JDK source code is as follows:

Returns the canonicalized representation of string objects.

A String pool that is null at the beginning, which is privately maintained by the String class.

When the intern method is called, if the pool already contains a String equal to this String Object (this Object is determined by the equals (Object) method ),

Returns the string in the pool. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows s and t for any two strings. if and only when s. equals (t) is true, s. intern () = t. intern () is true.

All literal value strings and string value assignment expressions are internal.

Return Value:

A string with the same content as this string, but it is always from the string pool.

Although calling the intern method in the output does not have any effect, the background method actually performs a series of actions and operations.

The "AB" is returned when the "AB". intern () method is called. However, this method first checks whether the "AB" string exists in the string pool,

If yes, the string reference is returned. Otherwise, the string is added to the string pool, and the string reference is returned.

For example:

public class Str2{public static void test(){String a="a";String b=a+"b";String c="ab";String d=new String (b);System.out.println(b==c);System.out.println(d==c);System.out.println(c==d.intern());System.out.println(b.intern()==d.intern());}public static void main(String []args){new Str2().test();}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.