Home Java javaTutorial Example introduction to detailed explanation of Java strings

Example introduction to detailed explanation of Java strings

Dec 19, 2016 pm 02:20 PM

1. Create objects

For direct string constants in Java programs, the JVM will use a string pool to save them. When a string direct constant is used for the first time, the JVM will put it into the string pool for caching. Under normal circumstances, string objects in the string pool will not be garbage collected. When the program needs to use the string again, the reference variable can directly point to the existing string in the string without re-creating a new string. The string object created using the new operation does not point to the object in the string pool, but you can use the intern() method to point it to the object in the string pool.

public class StringDemo1 {
     public static void main(String[] args){
         String str1 ="abc";
         String str2 ="abc";
         String str3 =new String("abc");
         System.out.println(str1==str2);//true
         System.out.println(str1==str3);//false
         }
 }
Copy after login

FAQ

String str3 =new String("abc");
Copy after login

How many objects are created?
Answer: How many objects have been created by two

String str ="ab"+"cd";
Copy after login

?


Answer: One. "ab" and "cd" are constants placed in the string pool. Therefore, only one abcd string pool is created and the string abcd is saved in the string pool.

public class StringDemo1 {
    public static void main(String[] args){
        String str1 ="ab";
        String str2 ="cd";
        String str3 ="ab"+"cd";//创建对象并加入字符串池
        String str4 =str1+str2;
        String str5 =str1+"cd";
        System.out.println(str3==str4);//false
        System.out.println(str3==str5);//false

        }
}
Copy after login

It can be seen from the above code: Only String objects created with quotation marks containing text can be added to the string pool. For "+" connection expressions containing new objects created by the new method, the new objects generated by them will not be added. into the string pool.


But there is a situation that needs our attention:

public class StringDemo1 {
    private final static String str1 ="ab";
    private final static String str2 ="cd";
    public static void main(String[] args){
        String str3 ="ab"+"cd";//创建对象并加入字符串池
        String str4 =str1+str2;
        String str5 =str1+"cd";
        System.out.println(str3==str4);//true
        System.out.println(str3==str5);//true

        }
}
Copy after login

Why is this? The reason is this, for constants. Its value is fixed and therefore can be determined at compile time.


Slightly change the above code and see what happens.

public class StringDemo1 {
     private final static String str1 ;
     private final static String str2;
     static{
     str1="ab";
     str2="cd";
     }
     public static void main(String[] args){
         String str3 ="ab"+"cd";//创建对象并加入字符串池
         String str4 =str1+str2;
         String str5 =str1+"cd";
         System.out.println(str3==str4);//false
         System.out.println(str3==str5);//false

         }
 }
Copy after login

Although str1 and str2 are defined as constants, they are assigned values ​​immediately. Before the value of s is calculated, when they are assigned and what value they are assigned are variables, so their properties are the same as variables. Can only be created at runtime.


2. String method

Getting method

•int length()
•char charAt(int index) gets a character based on the position
•int indexOf(int ch) returns ch in the string The position of the first occurrence in
•int indexOf(int ch,int fromIndex) Starting from the position specified by fromIndex, get the position of the first occurrence of ch in the string
•int indexOf(String str)
•int indexOf(String str,int fromIndex)
•int lastIndexOf(int ch)

Judgment method

•boolean contains(String str) Another judgment method: if(str.index(str)!=-1)
•boolean startsWith( String str)
•boolean endsWith(String str)
•bolean isEmpty(String str)
•boolean equals(String str)
•boolean equalsIgnoreCase(String str);

Conversion method

•Convert character array to string

Constructor

1.String(char[] chs)

2.String(char[] chs, offset, count) converts part of the character array into a string.

Static method

1.static String copyValueOf(char[] chs)

2.static String copyValueOf(char[] chs,int offset,int count)

3.static String valueOf(char[] )

4.static String valueOf(char[] chs,int offset,int count)

•Convert a string to a character array

char[] toCharArray

•Convert a character array to a string
•Convert a string to Byte array
byte[] toBytes

Replacement method

String replace(olderStr,newStr)

Cut method

String split(regex)

Get substring [Edit Category]

String subString(begin)

String subString (begin, end) includes the head but not the tail

Convert the string to upper and lower case Android (10)

String toUpperCase()

String toLowerCase()

Remove the spaces at both ends of the string

String trim ()

Compare two strings in natural order

int compareTo(String str)

3.String practice

1. String flipping

public class StringDemo2 {
     public static void main(String[] args){
         String str = "avdkfasjks";
         reverseMethod_1(str);
     }
     public static void reverseMethod_1(String str){
         for(int i=str.length();i>0;i--){
             System.out.print(str.charAt(i-1));
         }
     }
 }
Copy after login

2. Get the largest identical substring

public class StringDemo2 {
    public static void main(String[] args){
        String str1 = "avdkfasjks";
        String str2 = "ewavdrtte";
        System.out.println(commonMaxSubstring(str1, str2));
    }
    public static String commonMaxSubstring(String str1,String str2){
        int len = str1.length();
        String str3 = null;
        outer:
            //i为子串的长度
            for(int i = len;i>0;i--){
                //j为子串的脚标
                for(int j=0;j<len-i+1;j++){
                    str3=str1.substring(j,j+i);
                    if(str2.contains(str3))
                        break outer;

                }
            }
        return str3;
    }
}
Copy after login

That’s it Examples of detailed explanations of Java strings are introduced. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

See all articles