Introduction to Java zero foundation 5: Java string

🍅 Supporting articles for Java learning route: Brick movers counter attack Java Architects

🍅 Classic Java interview questions: Summary of 208 classic Java interview questions with 100000 words (with answers)

🍅 Introduction: high quality creator in Java field 🏆, CSDN the author of the official account of the Na Zha ✌ , Java Architect striver 💪

🍅 Scan the QR code on the left of the home page, join the group chat, learn and progress together  

🍅 Welcome to praise 👍 Collection ⭐ Leaving a message. 📝  

catalogue

1, String

2, Substring

3, String splicing "+"

1. Implementation principle of "+" connector

2. Efficiency of "+" connector

5, Detects whether the strings are equal

1,equals()

2. Ignore case comparison equalsIgnoreCase

3. Generally, = = is not used to judge whether the strings are equal

6, null and empty

7, String API

8, Build string

1, String

A Java string is a sequence of Unicode characters, such as String name = "Nezha";

2, Substring

The subString method of String can intercept a subString from a long String, for example:

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name = "CSDN nezha";
        System.out.println(name.substring(1));// SDN Nezha
        System.out.println(name.substring(4,6));// nezha
        System.out.println(name.subSequence(4,6));// nezha
    }
}

name.substring a parameter indicates that it is intercepted from the current parameter until the end.

When there are two parameters, the first is the start position of interception (included), and the second is the end position (not included).

What is the difference between substring and subSequence?

substring source code

public String substring(int beginIndex, int endIndex) {
	if (beginIndex < 0) {
		throw new StringIndexOutOfBoundsException(beginIndex);
	}
	if (endIndex > value.length) {
		throw new StringIndexOutOfBoundsException(endIndex);
	}
	int subLen = endIndex - beginIndex;
	if (subLen < 0) {
		throw new StringIndexOutOfBoundsException(subLen);
	}
	return ((beginIndex == 0) && (endIndex == value.length)) ? this
			: new String(value, beginIndex, subLen);
}

subSequence source code

public CharSequence subSequence(int beginIndex, int endIndex) {
    return this.substring(beginIndex, endIndex);
}

subSequence also calls substring, but the return value is different.

subSequence has been overridden in the String class. Call the subSequence method to directly convert it to a String object.

3, String splicing "+"

1. Implementation principle of "+" connector

String connection is realized through StringBuilder (or StringBuffer) class and its append method. Object conversion to string is realized through toString method. This method is defined by object class and can be inherited by all classes in Java.

We can verify the following by decompiling:

public class Test {
    public static void main(String[] args) {
        int i = 10;
        String s = "nezha";
        System.out.println(s + i);
    }
}
 
/**
 * After Decompilation
 */
public class Test {
    public static void main(String args[]) { 
        ...
        byte byte0 = 10;      
        String s = "nezha";      
        System.out.println((new StringBuilder()).append(s).append(byte0).toString());
    }
}

From the above code, we can see that the bottom layer of the "+" connection string is actually completed by the StringBuilder object through append and then calling toString.

2. Efficiency of "+" connector

When using the "+" connector, the JVM will implicitly create a StringBuilder object. This method will not cause efficiency loss in most cases, but it is different when splicing strings in a loop.

Because a large number of StringBuilder objects will be created in heap memory, which is certainly not allowed, it is recommended to create a StringBuilder object outside the loop, and then call the append method inside the loop for manual splicing.

In another special case, if "+" splices strings in string constants, the compiler will optimize and directly splice the two string constants.

Therefore, the "+" connector is very efficient for directly added string constants, because its value is determined during compilation; However, for indirect addition, the efficiency will become lower. It is recommended to use StringBuilder for single thread and StringBuffer for multithreading.

[Java basics 8] detailed explanation of String, StringBuilder and StringBuffer

4, Immutable string

String does not provide a method to modify a string, so string is immutable in Java.

5, Detects whether the strings are equal

1,equals()

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name = "CSDN nezha";
        System.out.println(name.equals("nezha"));//false
    }
}

2. Ignore case comparison equalsIgnoreCase

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name = "CSDN nezha";
        System.out.println(name.equalsIgnoreCase("csdn nezha"));//true
    }
}

3. Generally, = = is not used to judge whether the strings are equal

String class is an object type that is frequently used in our projects. In order to improve performance, reduce overhead and avoid repeated creation of strings, the JVM maintains a special memory space, namely string constant pool. When a string needs to be used, first go to the string constant pool to check whether the string already exists. If it exists, it can be used directly; If not, initialize and put the string into the string constant pool.

public class StringTest {
    public static void main(String[] args) {
        // 1. Create a new reference s1 to the object s1 in the heap with the value of "CSDN"
        String s1=new String("CSDN")+new String("nezha");
        // 2. Create a new reference s2 to the object s2 in the heap with the value "CSDN"
        String s2=new String("CS")+new String("DN nezha");
        // 3. Executing s1.intern() will create a new reference "CSDN Nezha" in the string constant pool, which points to the address of s1 in the heap, and a new reference s3 points to "CSDN Nezha" in the string constant pool
        String s3=s1.intern();
        // 4. Executing s2.intern() will not create a new reference in the string constant pool, because "CSDN Nezha" already exists, so only the operation of creating a new reference s4 to "CSDN Nezha" in the string constant pool is performed
        String s4=s2.intern();
        // s3 and s4 point to the "CSDN Nezha" in the string constant pool, and this "CSDN Nezha" points to the address of s1 in the heap
        System.out.println(s1==s3); // true
        System.out.println(s1==s4); // true
        // The address in the final Association heap of s3 and s4 is object s1
        System.out.println(s2 == s3);// false
        System.out.println(s2 == s4);// false
    }
}

6, null and empty

Empty means "" with a length of 0. You can use str.length() to determine whether the string is empty.

Null. If the general object is not assigned a value, the default value is null.

Here, we must pay attention to the problem of null pointer exception. When using the object, we must initialize it first, otherwise it will report null pointer exception.

In actual development, it is generally necessary to judge that the string is neither null nor empty.

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name = "CSDN nezha";
        if(name == null || name.length() == 0){
            System.out.println(name + "Empty");
            return;
        }
        System.out.println(name.equalsIgnoreCase("csdn nezha"));//true
    }
}

Judge null first. Do you know why?

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name = null;
        if(name.length() == 0 || name != null){
            System.out.println(name + "Empty");
            return;
        }
        System.out.println(name.equalsIgnoreCase("csdn nezha"));
    }
}

The console reported null pointer exception, because name called the length method, but name is null, so the method cannot be called, and when judged= When null, if it is null, the judgment of. length() == 0 will not be performed.

7, String API

8, Build string

Many times, a String needs to be spliced by multiple small strings. If + is used to splice, the efficiency will be relatively low, because each connection String will build a new String object, which is time-consuming and a waste of space.

Using StringBuilder can avoid this problem.

package com.nezha.javase;

public class Test {
    public static void main(String[] args) {
        String name1 = "CSDN";
        String name2 = "nezha";
        String name3 = "Very strong";
        String name4 = name1 + name2 + name3;
        System.out.println("+Splicing:"+name4);
        StringBuilder builder = new StringBuilder();
        builder.append(name1);
        builder.append(name2);
        builder.append(name3);
        System.out.println("StringBuilder Splicing:"+builder.toString());
    }
}

Console output:

+Splicing: CSDN Nezha is very strong
StringBuilder splicing: CSDN Nezha is very strong  

Previous: Introduction to Java zero foundation 4: Java operator

Next: stay tuned

 

Add wechat, remark 1024, and give away the thinking map of Java learning route  

Tags: Java Back-end

Posted on Wed, 10 Nov 2021 18:34:58 -0500 by jeremy0