Java Basics (02): special string classes and related extension APIs

1、 Introduction to string class

1. Basic introduction

String is a special data type and belongs to reference type. String class is decorated with the keyword final in Java, so this class cannot inherit, extend and modify its methods. The string class is very useful. When initializing a string object, like the wrapper type of a basic type, you can construct an object without using the new keyword. (it's really enchanting...)

2. Class construction and methods

Features: final keyword modification to realize serializable serialization interface, comparable comparison interface and charsequence character sequence interface.

final class String
    implements java.io.Serializable,Comparable<String>,CharSequence

There are two ways, constants and creating objects.

String var1 = "cicada" ;           
String var2 = new String("smile") ;

VAR1: it declares a constant, which is obviously placed in the constant pool.

Var2: creates a string object, which is stored in heap memory.

2、 Common applications

1. Comparative judgment

Constant pool is used to store constants; Heap memory is used to store new reference objects.

public class String02 {
    public static void main(String[] args) {
        String var1 = "cicada" ;
        String var2 = "cicada" ;
        // true;true
        System.out.println((var1==var2)+";"+var1.equals(var2));
        String var3 = new String("cicada");
        String var4 = new String("cicada");
        // false;true
        System.out.println((var3==var4)+";"+var3.equals(var4));
        // false;true
        System.out.println((var1==var4)+";"+var2.equals(var4));
        String var5 = "ci"+"cada";
        // true;true
        System.out.println((var1==var5)+";"+var5.equals(var4));
        String var6 = new String02().getVar6 () ;
        // true;true
        System.out.println((var1==var6)+";"+var6.equals(var4));
    }
    public String getVar6 (){
        return "cicada" ;
    }
}

==: for basic types, values are compared; for reference types, address values are compared;

Equals: this method is derived from one of the most basic general methods in object. In the object method, = = is used to judge the address value, but it is rewritten in the string class for character content comparison. The change of this method in inheritance relationship and tracking JDK source code is very clear.

2. Code analysis

The string is represented by a char [] array inside the string, and the characters are represented by Unicode unified encoding. The character encoding of char type is derived from this.

If you look at the construction method here, you will understand the above conceptual logic.

private final char value[];
public String() {this.value = "".value;}
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

Different countries and regions may use different codes. Utf8 codes are the most commonly used in the Internet. Once in program development, it is often necessary to convert between codes.

public class String03 {
    public static void main(String[] args) throws Exception {
        String value = "Hello,知了";
        // UTF-8
        byte[] defaultCharset = value.getBytes(Charset.defaultCharset());
        System.out.println(Arrays.toString(defaultCharset));
        System.out.println(new String(defaultCharset,"UTF-8"));
        // GBK
        byte[] gbkCharset = value.getBytes("GBK");
        System.out.println(Arrays.toString(gbkCharset));
        System.out.println(new String(gbkCharset,"GBK"));
        // ISO-8859-1:表示的字符范围很窄,无法表示中文字符,转换之后无法解码
        byte[] isoCharset = value.getBytes("ISO8859-1");
        System.out.println(Arrays.toString(isoCharset));
        System.out.println(new String(isoCharset,"ISO8859-1"));
        // UTF-16
        byte[] utf16Charset = value.getBytes("UTF-16");
        System.out.println(Arrays.toString(utf16Charset));
        System.out.println(new String(utf16Charset,"UTF-16"));
    }
}

Two basic concepts:

Encoding encode: the process of converting information from one form to another according to rules, which is called encoding for short;

Decoding: decoding is the reverse process of encoding.

3. Format operation

In daily development, the format of string will not meet the business requirements, and the specified formatting operation is usually required.

public class String04 {
    public static void main(String[] args) {
        // 指定位置拼接字符串
        String var1 = formatStr("cicada","smile");
        System.out.println("var1="+var1);
        // 格式化日期:2020-03-07
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date() ;
        System.out.println(format.format(date));
        // 浮点数:此处会四舍五入
        double num = 3.14159;
        System.out.print(String.format("浮点类型:%.3f %n",num));
    }
    public static String formatStr (String ...var){
        return String.format("key:%s:route:%s",var);
    }
}

The above case demonstrates the application scenario: redis cache key generation, date type conversion, and interception of ultra long floating point numbers.

4. Formal parameter transfer problem

When a string object parameter is passed to a method, it actually passes a copy of the reference.

public class String05 {
    String var1 = "hello" ;
    int[] intArr = {1,2,3};
    public static void main(String[] args) {
        String05 objStr = new String05() ;
        objStr.change(objStr.var1,objStr.intArr);
        // hello  4
        System.out.println(objStr.var1);
        System.out.println(objStr.intArr[2]);
    }
    public void change (String var1,int[] intArr){
        var1 = "world" ;
        intArr[2] = 4 ;
    }
}

What is changed in the case is the copy of the VAR1 reference, the method ends, the execution ends, the formal parameter VAR1 is destroyed, and the reference of the original object remains unchanged. When an array is passed as a parameter, the address value of the array in memory is passed, so the position of the array in memory can be found directly.

5. String tool class

String processing is very common in system development. A tool class is usually provided for unified processing. It can be encapsulated based on the tool classes in a framework or all by itself.

class StringUtil {
    private StringUtil(){}
    public static String getUUid (){
        return UUID.randomUUID().toString().replace("-","");
    }
}

The above is the most basic string tool class. The built-in tool classes in different frameworks are also good.

org.apache.commons.lang3.StringUtils
org.springframework.util.StringUtils
com.alibaba.druid.util.StringUtils

The first one is recommended here. You can also inherit the custom tool class to provide richer public methods.

A long story: the foundation of code neatness is to have a lazy heart and spend some time on the encapsulation of the package and the deletion of the package that should be deleted.

3、 Extension API

1. StringBuffer class

String modification is a common API for splicing. The internal implementation process is similar to that of string.

public class String07 {
    public static void main(String[] args) {
        StringBuffer var = new StringBuffer(2) ;
        var.append("what");
        var.append("when");
        System.out.println(var);
    }
}

See the response of the above lines of code, which can basically reflect the programming age:

One year: API is used like this, no problem;

Three years: StringBuffer is thread safe and its efficiency is relatively low;

Five years: the default character array size is 16. The size of the custom character array here needs to be expanded if the length is not enough, so it is necessary to estimate the possible size of the string to reduce consumption;

A long story: the default size of many container objects in Java is 16, and there is a dynamic capacity expansion mechanism. This is the legendary programming idea. In the development, write two paragraphs according to the gourd painting ladle, which is the style.

2. StringBuilder class

This class appears much later than StringBuffer, from jdk1 5 began to appear.

public class String08 {
    public static void main(String[] args) {
        StringBuilder var = new StringBuilder() ;
        var.append("how").append("what") ;
        System.out.println(var);
    }
}

The usage is similar to that of StringBuffer, but it is a non thread safe operation, which is naturally more efficient.

Supplementary sentence: for thread safe and non safe operations, as well as the logic of initial capacity and expansion, you can view them in the source code, which is a necessary awareness for advanced programmers.

3. Let's look at the problem of transmission parameters

The principle here is explained as above, and the fundamental logic is consistent.

public class String09 {
    public static void main(String[] args) {
        String var1 = new String("A");
        String var2 = new String("B");
        StringBuffer var3 = new StringBuffer("C");
        StringBuffer var4 = new StringBuffer("D");
        join(var1,var2);
        join(var3,var4);
        //A<>B
        System.out.println(var1+"<>"+var2);
        //C<>DD
        System.out.println(var3+"<>"+var4);
    }
    public static void join (String s1,String s2){
        s1 = s2 ;
        s2 = s1+s2 ;
    }
    public static void join (StringBuffer s1,StringBuffer s2){
        s1 = s2 ;
        s2 = s2.append(s1) ;
    }
}

A long word: String related API transmission parameters are basically asked when job hopping in the first three years of work. If you don't understand the basic principle and feel a little flustered, you will basically answer wrong.

4、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>