search
HomeJavajavaTutorialDetailed explanation of intern() in String object

1. First of all, String does not belong to the 8 basic data types. String is an object.
Because the default value of the object is null, the default value of String is also null; but it is a special object and has some characteristics that other objects do not have.

2. New String() and new String("") both declare a new empty string, which is an empty string and not null;

3. String str="kvill";
String str=new String (“kvill”); The difference:

Here, we don’t talk about the heap or the stack, we just simply introduce the constantpool. the concept of.

The constant pool refers to some data that is determined during compilation and saved in the compiled .class file. It includes constants in classes, methods, interfaces, etc., as well as string constants.

Look at Example 1:

String s0=”kvill”; 
String s1=”kvill”; 
String s2=”kv” + “ill”; 
System.out.
print
ln( s0==s1 ); 
System.out.println( s0==s2 );

The result is:

true 
true

First of all, we need to know that Java will ensure that there is only one copy of a string constant.

Because the "kvill" in s0 and s1 in the example are both string constants, they are determined at compile time, so s0==s1 is true; and "kv" and "ill" are also They are all string constants. When a string is concatenated by multiple string constants, it must itself be a string constant, so s2 is also parsed into a string constant at compile time, so s2 is also a constant pool. A quote of "kvill".
So we get s0==s1==s2;
The string created with new String() is not a constant and cannot be determined at compile time, so the string created with new String() does not contain constants In the pool, they have their own address space.

Look at Example 2:

String s0=”kvill”; 
String s1=new String(”kvill”); 
String s2=”kv” + new String(“ill”); 
System.out.println( s0==s1 ); 
System.out.println( s0==s2 ); 
System.out.println( s1==s2 );

The result is:

false 
false 
false

In Example 2, s0 is still the application of "kvill" in the constant pool. Because s1 cannot be determined at compile time, it is a reference to the new object "kvill" created at runtime. Because s2 has the second half of new String ("ill"), it cannot be determined at compile time, so it is also a new Create the application of object "kvill"; if you understand this, you will know why this result is obtained.

4. String.intern():

One more point: the constant pool that exists in the .class file is loaded by the JVM during runtime and can be expanded. The intern() method of String is a method to expand the constant pool; when a String instance str calls the intern() method, Java searches for whether there is a string constant with the same Unicode in the constant pool, and if so, returns its reference. If If not, add a Unicode string equal to str in the constant pool and return its reference; it will be clear by looking at Example 3

Example 3:

String s0= “kvill”; 
String s1=new String(”kvill”); 
String s2=new String(“kvill”); 
System.out.println( s0==s1 ); 
System.out.println( “**********” ); 
s1.intern(); 
s2=s2.intern(); //把常量池中“kvill”的引用赋给s2 
System.out.println( s0==s1); 
System.out.println( s0==s1.intern() ); 
System.out.println( s0==s2 );

The result is:

false 
********** 
false //虽然执行了s1.intern(),但它的返回值没有赋给s1 
true //说明s1.intern()返回的是常量池中”kvill”的引用 
true

Finally, I will dispel another misunderstanding:

Someone said, "Use the String.intern() method to save a String class into a global String table. If a Unicode string with the same value is already in this table, then this method returns the address of the string already in the table. If there is no string with the same value in the table, register its own address into the table. "If I If we interpret the global String table he mentioned as a constant pool, his last sentence, "If there is no string with the same value in the table, register your own address in the table" is wrong:

Look at Example 4:

String s1=new String("kvill"); 
String s2=s1.intern(); 
System.out.println( s1==s1.intern() ); 
System.out.println( s1+" "+s2 ); 
System.out.println( s2==s1.intern() );

Result:

false 
kvill kvill 
true

We did not declare a "kvill" constant in this class, so there was no constant in the constant pool at the beginning. "kvill", when we call s1.intern(), a new "kvill" constant is added to the constant pool. The original "kvill" that is not in the constant pool still exists, which means it is not "registering its own address" into the constant pool".

s1==s1.intern() is false, indicating that the original "kvill" still exists;

s2 is now the address of "kvill" in the constant pool, so s2==s1. intern() is true.

5. About equals() and ==:

For String, this is simply to compare whether the Unicode sequences of two strings are equivalent, and return true if they are equal; while == compares two strings. Whether the addresses of the strings are the same, that is, whether they are references to the same string.

6. There is a lot to say about String being immutable. As long as you know that a String instance will not change once it is generated, for example: String str=" kv"+"ill"+" "+"ans";
There are 4 string constants. First, "kv" and "ill" generate "kvill" and store it in the memory, and then "kvill" and " " Generate "kvill" and store it in the memory, and finally generate "kvill ans"; and assign the address of this string to str, because the "immutability" of String generates many temporary
variables
, This is why it is recommended to use StringBuffer, because StringBuffer is changeable
[Related recommendations]

1. Java free video tutorial

2. In-depth analysis of the intern() method in Java

3. JAVA Summary of experience in using intern() method

4. What is the concept of intern method in java

5. Analysis of intern in Java The function of ()

The above is the detailed content of Detailed explanation of intern() in String object. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor