Table of Contents
1. Understanding String
1. String in JDK
2. Four ways to create strings
3. String literal
4. String comparison is equal
2. String constant pool
1. What is the string constant pool
2. Manual pool entry method
3. Immutability of strings
1. Why is it immutable
2. How to modify the string content
3. Specific use of the StringBuilder class
Home Java javaTutorial How to use java's String class

How to use java's String class

Apr 19, 2023 pm 01:19 PM
java string

How to use java's String class

1. Understanding String

1. String in JDK

First let’s take a look at the source code of the String class in JDK, which implements many interfaces , you can see that the String class has been modified by final, which means that the String class cannot be inherited, and there is no subclass of String. In this way, all people who use the JDK will use the same String class. If String is allowed to be inherited, Everyone can extend String, and the String used by everyone is not the same version. Two different people use the same method and show different results, which makes it impossible to develop the code.
Inheritance and While method overriding brings flexibility, it also brings many problems with inconsistent behavior of subclasses
How to use java's String class

2. Four ways to create strings

Methods One: Direct assignment (commonly used)
String str = " hello word "

Method two: Generate objects through the construction method
String str1 = new String(" hello word ");

Method 3: Generate objects through character arrays
char[] data = new char[]{'a', 'b','c'};

Method 4: Through static methods of String valueOf(any data type) = >Convert to string (commonly used)
String str2 = String.valueOf(10);
How to use java's String class

3. String literal

Literal: The value written directly is called a literal
10 – > int literal
10.1 --> double literal
true --> boolean literal
" abc " – > String literal
The string literal is actually a string object
String str = “hello word”;
String str2 = str;
At this time, this is both a The literal value of a string is also an object of the string. For the convenience of understanding, let’s draw a picture. At this time, for the convenience of understanding, we temporarily think that it is stored on the heap. In fact, it is stored in the method area.
How to use java's String class
If str2 = "Hello" is set at this time; it has no effect on the output of str at this time, because Hello enclosed by " " is also a string object, indicating that a new space is opened on the heap at this time, and at this time str2 saves the address space of the new object and has no effect on str
How to use java's String class

4. String comparison is equal

When comparing all reference data types for equality, use Equals method comparison, common classes in JDK have overridden the equals method, you can use it directly
The reference data type uses == to compare the address
The following picture shows two references pointing to the same address space. It is related to the constant pool of strings
How to use java's String class
The following figure generates two objects and two address spaces. Using == returns false
How to use java's String class
The comparison size of equals is Case-sensitive comparison
How to use java's String class
The equalsIgnoreCase method is case-insensitive comparison
How to use java's String class

2. String constant pool

1. What is the string constant pool


How to use java's String class## When using the direct assignment method to generate a string object , the JVM will maintain a string constant pool. If the object does not exist in the heap, it will generate a string object and add it to the string constant pool; when continuing to use the direct assignment method to generate a string object, the JVM finds The content pointed to by this reference already exists in the constant pool. At this time, there is no need to create a new string object, but directly reuse the existing object. This is why the three references in the picture above point to the same address.

How to use java's String class When the object is generated for the first time, there is nothing in the constant pool, so a string object is generated and stored in the constant pool. When the object is generated for the second and third time, the JVM finds the constant. If the same content already exists in the pool, no new objects will be generated, pointing directly to the same address space as str1


  1. #

How to use java's String class
The program is executed from right to left. At this time, the right side of the first line of code is a string constant, which is also a string object, so first in the constant pool Create a space in the heap, and then create a new string object and store it. The program executes to the left and encounters the new keyword. At this time, a new object is created and stored in the heap. Then str1 points to the object in the heap, and then points to the second line. After three lines of code, it is found that the object already exists in the constant pool. No new creation is required. When the new keyword is encountered, a new object is created. The memory diagram is as follows:
How to use java's String class

2. Manual pool entry method

The intern method provided by the String class, this is a local method:
How to use java's String class
Calling the intern method will save the object pointed to by the current string reference to the string constant pool. There are two types Situation:
1. If the object already exists in the current constant pool, no new object will be generated, and the String object in the constant pool will be returned
2. If the object does not exist in the current constant pool, then The object is put into the pool and the address after being put into the pool is returned.

1. Take a look at the output of the following lines of code
How to use java's String class
Because the intern method has a return value, str1 only calls the intern method at this time and does not receive the return value. So str1 still points to the object in the heap, str2 points to the object in the constant pool, so false is returned;
How to use java's String class
As long as the return value of calling the intern method is received, true will be returned;
How to use java's String class
At this point, the object pointed to by str1 is manually added to the pool. The object already exists in the pool. Directly let str1 point to the object.
How to use java's String class
2. Take a look at the following lines of code Output
How to use java's String class
When manually entering the pool, there is nothing in the pool, so it is moved directly into the constant pool
How to use java's String class


3. Immutability of strings

1. Why is it immutable

Note: The so-called immutable string refers to the immutability of the content of the string, not that the reference to the string cannot be changed
How to use java's String class
The immutable here refers to "hello", "world", "helloworld", "!!!", and the spliced ​​"helloworld!!!" these already created string objects, once these objects are declared Its content cannot be modified later, but the reference can be changed. One moment it points to hello, another moment it points to helloworld, and now it points to hello world! ! ! , this is all possible
How to use java's String class
A string is just a character array -> char[], the string is actually stored in the character array. Why can't the content of the string be changed? Let's take a look at the source code of the string and find out.
How to use java's String class
We can see that the character array inside String is encapsulated. This character array cannot be accessed from outside the String class, let alone changing the content of the string
String str = " hello ";
How to use java's String class

2. How to modify the string content

1. Destroy the encapsulation of the value array through reflection at runtime
2. Use StringBuilder or StringBuffer instead Class - - is no longer a type
a.StringBuilder: thread-safe, strong performance
b.StringBuffer: thread-safe, poor performance
In addition, the usage of the two classes is exactly the same

If you need to splice strings frequently, use the append method of the StringBuilder class. Only one object is generated here, which will become hello for a while and hello world for a while.
How to use java's String class

3. Specific use of the StringBuilder class

The StringBuilder class and String are two independent classes. The StringBuilder class was created to solve the problem of string splicing.
Mutual conversion between the StringBuilder class and the String class :

1.StringBuilder becomes String class and calls toString method
How to use java's String class

2.String class is transformed into StringBuilder class, use StringBuilder's constructor or append method
How to use java's String class
How to use java's String class
Other commonly used methods:
a. String reversal operation, reverse() provided by sb;
How to use java's String class

b. Delete the specified range of data, delete (int start, int end); delete everything starting from start to end, closed on the left and open on the right.
How to use java's String class

c .Insert operation, insert(int start, various data types): insert from the start index position, the starting index of insertion is start
How to use java's String class

The above is the detailed content of How to use java's String class. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles