Notes on Java core technology Volume 1: Chapter III Basic programming structure of Java

3.6.5 build string

When String is used to continuously splice strings with circular statements, because String is an immutable class, new objects are generated every time, which is inefficient; Therefore, Java provides StringBuilder and StringBuffer to solve this problem.

public class Main {
    public static void main(String[] args){
        final int SIZE = 1000;
        System.out.println("String Splicing efficiency test:");
        long t1 = System.nanoTime();
        String s = "";
        for(int i = 0; i < SIZE; i++){
            s = s+i;
        }
        System.out.println(s);
        long t2 = System.nanoTime();
        System.out.println("String Splicing time:");
        System.out.println((t2-t1)+"ns");

        System.out.println("StringBuilder Splicing efficiency test:");
        long t3 = System.nanoTime();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < SIZE; i++){
            sb.append(i);
        }
        System.out.println(sb.toString());
        long t4 = System.nanoTime();
        System.out.println("StringBuilder Splicing time:");
        System.out.println((t4-t3)+"ns");

        System.out.println("StringBuffer Splicing efficiency test:");
        long t5 = System.nanoTime();
        StringBuffer sf = new StringBuffer();
        for(int i = 0; i < SIZE; i++){
            sf.append(i);
        }
        System.out.println(sf.toString());
        long t6 = System.nanoTime();
        System.out.println("StringBuffer Splicing time:");
        System.out.println((t6-t5)+"ns");
    }
}

The execution results are shown in the figure. The efficiency of String is significantly lower than that of StringBuffer, and the efficiency of StringBuffer is lower than that of StringBuilder in the case of single thread.  

StringBuilder
namemeaningPersonal evaluation
int length()Character length (note that it is the character length, not the number of code points)Very common
StringBuilder append(String str)Append stringMost commonly used
StringBuilder delete(int startIndex,int endIndex)Delete string in rangeIn general, the more common is to delete the suffix deleteCharAt()
StringBuilder deleteCharAt(int index)
Delete specified characterIn common use, when splicing strings, the last character is often deleted, such as the format of "a,b,c". Often after splicing, there will be an additional comma "a,b,c,d", and the last comma needs to be deleted
String toString()
Convert to stringMost commonly used, otherwise it makes no sense to use this class
StringBuilder reverse()
String inversion, such as "abc", changes to "cba" after inversionGenerally, it will be very convenient if necessary

3.7 input and output

3.7.1 read input

Scanner usage

1. import java.util.*;

2. Create a Scanner object

3. Call , Scanner , the appropriate input type to obtain the input content

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);//Construct Scanner object
        System.out.println("What's your name?");
        String name = sc.nextLine();//Read one line of input from the console
        System.out.println("How old are you?");
        int age = sc.nextInt();//Read a number
        System.out.println("Your are "+name+","+age+" years old.");
    }
}

BufferedReader usage (supplementary)

1. import java.io.*;

2. Throw IOException

3. Create BufferedReader object

4. Call readLine() to get the whole line of input content

import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputContent = br.readLine();
        System.out.println(inputContent);
    }
}

 

Scanner
namemeaningPersonal evaluation
String nextLine()Read one line of inputMost commonly used, general
String next()Read the next word, separated by spacesIf there is next() input in front, it is not recommended to use it continuously, which will cause input confusion
int nextInt()Reads the next entered integerIn general, you can't check the type first. If you make an input error, an exception will be thrown directly

3.8 supplementary knowledge

Personal supplement

Q: what is the difference between String builder and StringBuffer?

A: String is an immutable class. The strings generated in String can be shared among various classes; When String itself is spliced, new StringBuilder objects and String objects will be generated, which is inefficient. The explicit use of StringBuilder/StringBuffer can reduce the objects generated in the String splicing process, so it is more efficient. Where StringBuilder is thread unsafe and StringBuffer is thread safe. When thread safe processing is not required, the efficiency of using StringBuilder is higher than that of StringBuffer.

Author supplement

Q: how to read the password from the console without displaying it directly on the console?

Answer: use the Console class. In particular, you cannot use IDE tools when using this class.

Fail if IDE is used:

Enter the root directory of the package and use the console to get the correct effect.  

public class Main {
    public static void main(String[] args){
        Console console = System.console();
        String username = console.readLine("User name:");
        String password = new String(console.readPassword("Password:"));
        System.out.println("User name is "+username+".");
        System.out.println("Password is "+password+".");
    }
}

Series content:

Notes on Java core technology Volume 1: Chapter 1 overview of Java programming

Notes on Java core technology Volume 1: Chapter 2 Java programming environment

Notes on Java core technology Volume 1: Chapter 3 basic programming structure of Java (1)

Notes on Java core technology Volume 1: Chapter 3 basic programming structure of Java (2)

Notes on Java core technology Volume 1: Chapter 3 basic programming structure of Java (3)

If you like, point a praise ~! Usually do the title, and notes will be updated to the official account.

Pay attention to official account and learn from each other: knowledge of Yu Niang Niang

Keywords: Java Back-end

Added by Pigmaster on Sun, 09 Jan 2022 13:40:38 +0200