First, the String class

The use of the java.lang.String class

(1) Overview

String: A String represented by a pair of “”.

  1. String is declared final and cannot be inherited

  2. String implements the Serializable interface: String supports serialization. Implements the Comparable interface: means strings can compare sizes

  3. Final char[] value is defined inside a String to store String data

  4. String: represents an immutable sequence of characters. Immutability for short.

    Reflect:

    4.1. When reassigning a value to a string, the specified memory area assignment needs to be overridden. The original value cannot be used for assignment.

    4.2. When concatenating an existing string, it is also necessary to reassign the memory area. The original value cannot be used for assignment.

    4.3. When you call String’s replace() method to modify a specified character or String, you also need to reassign the memory area. The original value cannot be used for assignment.

  5. By literal (as opposed to new assigning to a string, where the string value is declared in the string constant pool).

  6. The String constant pool does not store strings with the same contents (using equals() of the String class, which returns true).

(2) String characteristics

String class: represents a String. All string literals (such as “ABC”) in Java programs are implemented as instances of this class. String is a final class that represents an immutable sequence of characters. Strings are constants and are represented by double quotes. Their values cannot be changed after creation. The character content of a String object is stored in a character array vaue[].

String source constructor:

public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

Copy the code

1. Immutability of String

Description: 1.1

  1. When reassigning a value to a string, the specified memory area assignment must be overridden. The original value cannot be used for assignment.
  2. When concatenating an existing string, you need to assign a new value to the memory area instead of using the original value.
  3. When calling String’sreplace()Method When modifying a specified character or string, you also need to assign a new value to the memory area. The original value cannot be used.

1.2 Code Examples:

String s1 = "abc";// by the way literals are defined
String s2 = "def";
s1 = "hello";

System.out.println(s1 == s2); //false compares the address values of s1 and s2

System.out.println(s1);//hello
System.out.println(s2);//def

System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

String s3 = "abc";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);//def

System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

String s4 ="test";
String s5 = s4.replace("t"."b");
System.out.println(s4);//test
System.out.println(s5);//besb

Copy the code

1.3 Illustration analysis:

2. String instantiation method

2.1 Implementation Method description:

  • Method one: by means of literal definition
  • Method two: through the new + constructor

Interview questions:

String s = new String(“abc”); How many objects are created in memory?

Char [] = ‘ABC’; char[] = ‘ABC’

2.2 Code Examples:

// By literal definition: the s1 and S2 data javaEE is declared in the string constant pool in the method area.
String s1 = "javaEE";
String s2 = "javaEE";
// With the new + constructor, S3 and S4 store the address values of the data after space is created in the heap space.
String s3 = new String("javaEE");
String s4 = new String("javaEE");

System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false

Copy the code

Strings str1 = “ABC”; With String str2= new String(” ABC “); The difference between?

New String memory parsing

3. Comparison of string concatenation values

Description: 3.1

  1. Constant concatenation results in constant pool. And there will be no constant with the same content in the constant pool.
  2. As long as one of them is a variable, the result is in the heap.
  3. If the result of the concatenation is calledintern()Method, the return value is in the constant pool

3.2 Code Examples

String s1 = "javaEE";
String s2 = "hadoop";

String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;

System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false

String s8 = s6.intern();// Return the value of "javaEEhadoop" in the constant value used by S8.
System.out.println(s3 == s8);//true
****************************
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false

final String s4 = "javaEE";/ / s4: constants
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true

Copy the code

Memory parse

4. String Uses traps

  • String s1 = "a";

    Description: CREATES a string literal “A” in the string constant pool.

  • s1=s1+”b”

    Note: In fact, the original “A” string object has been discarded, and now a string s1+”b” (i.e., “ab”) is generated in heap space. Performing these changes multiple times can result in a large number of duplicate string objects remaining in memory, reducing efficiency. If such an operation is placed in a loop, it can greatly affect the performance of the program.

  • String s2=”ab”; Description: Create a string literal of “ab” directly in the string constant pool.

  • String s3=”a”+”b”; S3 refers to the string “ab” that has been created in the string constant pool.

  • String s4=s1.intern(); Description: After calling intern(), the heapspace S1 object assigns the “ab” string that already exists in the constant pool to S4.

5. String class common method

5.1 String Operations

Operation character:

  1. int length(): Returns the length of the string:return value.length
  2. char charAt(int index): Returns the character at an indexreturn value[index]
  3. boolean isEmpty()Check if it is an empty string:return value.length == 0
  4. String toLowerCase(): Converts all characters in String to lowercase using the default locale
  5. String toUpperCase(): Converts all characters in String to uppercase using the default locale
  6. String trim(): Returns a copy of the string, ignoring leading and trailing whitespace
  7. boolean equals(Object obj): Compares whether the contents of strings are the same
  8. boolean equalsIgnoreCase(String anotherString)And:equals()The method is similar, ignoring case
  9. String concat(String str): concatenates the specified string to the end of the string. Equivalent to use+
  10. int compareTo(String anotherString): Compares the size of two strings
  11. String substring(int beginIndex): returns a new string, which is the last substring of the string, starting with beginIndex.
  12. String substring(int beginIndex, int endIndex): Returns a new string that is a substring from beginIndex to endIndex (not included).

Code examples:

@Test
public void test2(a) {
    String s1 = "helloword";
    System.out.println(s1.length());/ / 9
    System.out.println(s1.charAt(4));//o
    System.out.println(s1.isEmpty());//false

    String s2 = "HELLOword";
    System.out.println(s2.toLowerCase());//hellowod
    System.out.println(s2.toUpperCase());//HELLOWORD

    String s3 = " hello word ";
    System.out.println(s3.trim());//hello word
    String s4 = "helloword";
    System.out.println(s4.equals(s1));//true
    System.out.println(s4.equalsIgnoreCase(s2));//true
    String s5 = "hello";
    System.out.println(s5.compareTo(s4));// return 0 if -4 is equal and negative if -4 is small
    System.out.println(s4.compareTo(s1));/ / 0

    System.out.println(s4.substring(5));//word
    System.out.println(s4.substring(5.9));//word, value range left open right closed

}

Copy the code

Judge character:

  1. boolean endsWith(String suffix): tests whether the string ends with the specified suffix
  2. boolean startsWith(String prefix): tests whether the string starts with the specified prefix
  3. boolean startsWith(String prefix, int toffset): tests whether substrings of this string starting with the specified index start with the specified prefix
@Test
public void test3(a) {
    String s1 = "javaEE";
    System.out.println(s1.endsWith("EE"));//true
    System.out.println(s1.startsWith("a"));//false
    System.out.println(s1.startsWith("EE".4));//true

}

Copy the code

5.2 Searching for Characters in a String

  1. Boolean contains (CharSequence s) :Returns true if and only if this string contains the specified sequence of char values
  2. int indexOf(String str): returns the index at the first occurrence of the specified substring in this string
  3. int indexOf(String str, int fromIndex): returns the index of the specified substring at its first occurrence in the string, starting with the specified index
  4. int lastIndexOf(String str): Returns the index of the rightmost occurrence of the specified substring in the string
  5. int lastIndexOf(String str, int fromIndex): Returns the index of the last occurrence of the specified substring in the string, starting with the specified index in reverse search

Note: Both indexOf and lastIndexOf methods return -1 if not found

Code examples:

@Test
public void test3(a) {
    String s2="hello word";
    System.out.println(s2.contains("o"));//true
    System.out.println(s2.indexOf("h"));/ / 0
    System.out.println(s2.indexOf("o".5));/ / 7
    System.out.println(s2.lastIndexOf("o"));/ / 7
    System.out.println(s2.lastIndexOf("l".2));/ / 2
}

Copy the code

5.3 String Operations

  1. Replacement:

    • String replace(char oldChar, char newChar): returns a new string obtained by replacing the oldChar present in the string with newChar.
    • String replace(CharSequence target, CharSequence replacement): Replaces the substrings of the literal target sequence matched by this string with the specified literal replacement sequence.
    • String replaceAll(String regex, String replacement): Replaces the substring of the given regular expression that this string matches with the given replacement.
    • String replaceFirst(String regex, String replacement): Replaces the first substring matching the given regular expression with the given replacement.
  2. Match:

    • boolean matches(String regex): Tells whether the string matches the given regular expression.
  3. Section:

    • String[] split(String regex) : Splits this String based on the match of the given regular expression.

    • String[] split(String regex, int limit) : Splits the String based on matching the given regular expression, up to a limit, if more, all the rest into the last element.

Code examples:

@Test
public void test4(a) {
    String str1 = "Hello Beijing, hello Beijing.";
    String str2 = str1.replace('north'.'the south');

    System.out.println(str1);// Hello Beijing, hello Beijing
    System.out.println(str2);// Hello nanjing, hello Nanjing

    String str3 = str1.replace("Beijing"."Shanghai");
    System.out.println(str3);// Hello Shanghai, hello Shanghai

    System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * *");
    String str = "12hello34world5java7891mysql456";
    // Replace the number in the string with,, if the result has a beginning and end, remove
    String string = str.replaceAll("\\d+".",").replaceAll("^, |, $"."");
    System.out.println(string);//hello,world,java,mysql

    System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * *");
    str = "12345";
    // Check whether the STR string is composed entirely of digits, i.e., 1-n digits
    boolean matches = str.matches("\\d+");
    System.out.println(matches);//true
    String tel = "0571-4534289";
    // Check if this is a hangzhou landline
    boolean result = tel.matches("0571 - \ \ d {7, 8}");
    System.out.println(result);//true


    System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * *");
    str = "hello|world|java";
    String[] strs = str.split("\ \ |");
    for (int i = 0; i < strs.length; i++) {
        System.out.println(strs[i]);// Output hello word Java
    }
    System.out.println();
    str2 = "hello.world.java";
    String[] strs2 = str2.split("\ \.");
    for (int i = 0; i < strs2.length; i++) {
        System.out.println(strs2[i]);// Output hello word Java}}Copy the code

6. Conversion of String to other structures

6.1 Conversion between String and primitive data types and wrapper classes

String –> Basic data type, wrapper class: call static method of wrapper class: parseXxx(STR)

Basic data type, wrapper class –> String: Call valueOf(XXX) of String overload

Code examples:

@Test
public void StringToBasic(a) {
    String str1 = "123";
    int i = Integer.parseInt(str1);
    System.out.println(i);
    System.out.println(i == 123);//true

    int j = 456;
    String s = String.valueOf(j);
    System.out.println(s);
    System.out.println(s.equals("456"));//true
}

Copy the code

6.2 Conversion to and from character arrays

String –> char[]: calls toCharArray() char[] –> String: calls the constructor of String

Code examples:

@Test
public void BasicToString(a) {
    String s1 = "helloword";
    char[] chars = s1.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        System.out.println(chars[i]);
    }

    char[] charArray = new char[] {'h'.'e'.'l'.'l'.'o'};
    String s2 = new String(charArray);
    System.out.println(s2);

}

Copy the code

6.3 Conversion to byte arrays

Encoding: String –> byte[]: Call String getBytes()

Byte [] –> String: calls the constructor of String

Encoding: string –> bytes (readable –> unreadable binary data)

Decoding: The reverse process of encoding, byte > string (unreadable binary data -> readable

Note: When decoding, the character set used for decoding must be the same as the character set used for encoding; otherwise, garbled characters will appear.

@Test
public void StringToByteTest(a) throws UnsupportedEncodingException {
    String s1 ="Hello Java world";
    byte[] bytesArray = s1.getBytes();// Use the default character set encoding
    System.out.println(Arrays.toString(bytesArray));/ / [- 28, 67, 96, 27, 91, 67, 106, 97, 118, 97, to 28, 72, 106, 25, 107, 116]

    byte[] gbks = s1.getBytes("gbk");// Use GBK to encode the collection
    System.out.println(Arrays.toString(gbks));/ / [- 60-29-70, 61, 106, 97, 118, 97, 54, 64, - 67-25)

    System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

    String str1=new String(bytesArray);// Decode with default characters
    System.out.println(str1);// Hello Java world

    String str2 = new String(gbks);// Decode GBK encoding using default characters
    System.out.println(str2);//��� Java code is not compatible with Java code

    String str3 = new String(gbks,"gbk");// Decode in GBK format
    System.out.println(str3);// Hello Java world, decoding correct, reason: encoding and decoding consistent
}

Copy the code

6.4 Conversion to StringBuffer and StringBuilder

1.String –>StringBuffer, StringBuilder: Call StringBuffer, StringBuilder constructor

@Test
public void StringToStringBufferTest(a){
    String str1 ="helloword";

    StringBuffer stringBuffer = new StringBuffer(str1);
    System.out.println(stringBuffer);//helloword

    StringBuilder stringBuilder = new StringBuilder(str1);
    System.out.println(stringBuilder);//helloword

    stringBuffer.append("isStringBuffer");
    System.out.println(stringBuffer);//hellowordandgood

    stringBuilder.append("isStringBuider");
    System.out.println(stringBuilder);
}

Copy the code

2. The StringBuffer, StringBuilder – > String:

Call String constructor; ToString () for StringBuffer and StringBuilder

@Test
public void StringBuiderOrStringBufferToStringTest(a) {
    StringBuffer sb1 = new StringBuffer("hello StringBuffer");
    System.out.println(sb1);

    StringBuilder sb2 = new StringBuilder("hello StringBuider");
    System.out.println(sb2);

    System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

    String str1 = new String(sb1);
    System.out.println(str1);

    String str2 = new String(sb2);
    System.out.println(str2);

    System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
    System.out.println(sb1.toString());
    System.out.println(sb2.toString());
}

Copy the code

7. JVM string constant pool storage location:

JDK 1.6 (JDK 6.0, Java 6.0): String constant pools are stored in the methods area (permanent)

JDK 1.7: String constant pools are stored in heap space

JDK 1.8: String constant pools stored in the method area (meta space)

8. Common algorithms

1) Simulate a trim method that removes whitespace from both ends of the string.

public String myTrim(String str) {
    if(str ! =null) {
        int start = 0;// Record the position index where the first index position from front to back is not a space
        int end = str.length() - 1;// The first index from back to front is not a space position index
        while (start < end && str.charAt(start) == ' ') {
            start++;
        }
        while (start < end && str.charAt(end) == ' ') {
            end--;
        }
        if (str.charAt(start) == ' ') {
            return "";
        }
        return str.substring(start, end + 1);
    }

    return null;
}

Copy the code

2) Invert a string. Reverses the specified portion of a string. For example, “abcdefg” becomes “abfedcg.”

/ / way
public String reverse1(String str, int start, int end) {
    if(str ! =null) {
        //1. Convert to char array
        char[] charArray = str.toCharArray();
        //2. Perform the reverse operation
        for (int i = start, j = end; i < j; i++, j--) {
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        }
        / / 3. The return value
        return new String(charArray);
    }
    return null;
}

2 / / way
// Analysis: The whole string is divided into three parts: non-inverting, inverted, and non-inverting
// Remove the inverted part from the front, and splice the inverted part
public String reverse2(String string, int start, int end) {
    if(string ! =null) {// The first part
    String newStr = string.substring(0, start);
    // Part 2
    for (int i = end; i >= start; i--) {
        newStr += string.charAt(i);
    }
    // Part 3
    newStr += string.substring(end + 1);
	// Splice operation
    return newStr;
    }
    return null;
}

// Use StringBuffer or StringBuilder instead of String optimization
public String reverse3(String str, int start, int end) {
    if(str ! =null) {/ / 1. New StringBuffer
    StringBuffer stringBuffer = new StringBuffer(str.length());
    //2
    stringBuffer.append(str.substring(0, start));
    //3. Part II
    for (int i = end; i >= start; i--) {
        stringBuffer.append(str.charAt(i));
    }
    //4
    stringBuffer.append(str.substring(end + 1));
    //5
    return stringBuffer.toString();  
    }
    return null;
}

Copy the code

3) Gets the number of occurrences of one string in another string. For example, get the number of occurrences of “ab” in “abkkcadkabkeBfkabkskab”

public int count(String mainStr, String subStr) {
    //1. Determine the size of main and partial strings
    if (mainStr.length() >= subStr.length()) {
        int index = 0;
        int count = 0;
        //2. Select subindex from main string and assign the new subindex to main string
        // while ((index = mainStr.indexOf(subStr) )! = 1) {
        // count++;
        // // starts with the next substring already found
        // mainStr = mainStr.substring(index + subStr.length());
        / /}
        // No longer create string, just do position alignment
        while((index = mainStr.indexOf(subStr, index)) ! = -1) {
            index += subStr.length();
            count++;
        }
        return count;
    } else {
        return 0; }}Copy the code

4) Get the maximum number of substrings that are identical between two strings. For example: str1 = “abcwerthelloyuiodef “; Str2 = “cvhellobnm” Tip: Compare the shorter string with the longer one.

// Only one substring exists
public String getMaxSameSubString(String str1, String str2) {
    //1. Determine the size of two strings
    if(str1 ! =null&& str2 ! =null) {
        String maxStr = (str1.length() >= str2.length()) ? str1 : str2;
        String minStr = (str1.length() < str2.length()) ? str1 : str2;

        int len = minStr.length();
        //2. Use the smaller ones to compare the larger ones
        for (int i = 0; i < len; i++) {// This layer of the for loop determines the number of characters that need to be compared
            for (int x = 0, y = len - i; y <= len; x++, y++) {
                if (maxStr.contains(minStr.substring(x, y))) {
                    returnminStr.substring(x, y); }}}}return null;
}

// There are multiple substrings of the same type
// Return String[], which can be replaced by ArrayList
public String [] getMaxSameSubStrings(String str1, String str2) {
    //1. Compare the size of the two substrings
    if(str1 ! =null&& str2 ! =null) {
        StringBuffer stringBuffer = new StringBuffer();
        String maxStr = (str1.length() > str2.length()) ? str1 : str2;
        String minStr = (str1.length() > str2.length()) ? str2 : str1;
        //2. Use small ones to match big ones
        int len = minStr.length();
        for (int i = 0; i < len; i++) {
            for (int x = 0, y = len - i; y <= len; x++,y++ ){
                String subString = minStr.substring(x,y);
                //3. Fetch the matched substring
                if (maxStr.contains(subString)){
                    stringBuffer.append(subString+","); }}//System.out.println(stringBuffer);
            if(stringBuffer.length() ! =0) {break;
            }
        }

        String [] split = stringBuffer.toString().replaceAll("$"."").split(\ \ ",");
        return split;
    }
    return null;
}

Copy the code

5) Sort the characters in the string in a natural order. Tip:

  1. Strings become character arrays.

  2. Arrays.sort(); arrays.sort ();

  3. Turns the sorted array into a string.

@Test
public void charTest(a) {
    String str1 = "hello java";
    char[] charArray = str1.toCharArray();

    Arrays.sort(charArray);

    String str2 = new String(charArray);
    System.out.println(str2);
}

Copy the code

StringBuffer and StringBuilder

(a) StringBuffer class

1. Overview:

Java.lang.string. Buffer represents a mutable sequence of characters, and as stated in JDK1.0, String contents can be added or deleted without creating new objects. A lot of methods are the same as String and when you pass them as arguments, you can change the value inside the method.

abstract class AbstractStringBuilder implements Appendable.CharSequence {
    /** * The value is used for character storage. */
    char[] value;// Value does not have a final declaration, value can be continuously expanded

    /** * The count is the number of characters used. */
    int count;//count Indicates the number of valid characters

Copy the code
  • The StringBuffer class differs from String in that its object must be generated using a constructor.
  • There are three constructors:
    • StringBuffer(): string buffer with an initial size of 16
    • StringBuffer(int size): constructs a string buffer of specified capacity
    • StringBuffer(String str): initializes the content to the specified string content
String s= new String("I like to learn.");
StringBuffer buffer= new StringBuffer("I like to learn.");
buffer. append("Mathematics");

Copy the code

2. Common methods:

  1. StringBuffer append(xxx): Offers a lot ofappend()Method for string concatenation
  2. StringBuffer delete(int start,int end): Deletes the content at the specified location
  3. StringBuffer replace(int start, int end, String str): Replaces the [start,end) position with STR
  4. StringBuffer insert(int offset, xxx): Inserts XXX in the specified position
  5. StringBuffer reverse(): Reverses the current character sequence

When append and INSERT, if the original vaue array length is not enough, you can expand it. These methods support method chain operations. Principle of method chain:

@Override
public StringBuilder append(String str) {
    super.append(str);
    return this;
}

Copy the code
  • public int indexOf(String str): returns the subscript of the substring
  • public String substring(int start,int end): returns a substring of an interval from start to the end of the index
  • public int length(): Gets the length of the string
  • public char charAt(int n ): Returns the character at the specified position
  • public void setCharAt(int n ,char ch): sets the character at the specified position

Conclusion:

Add: append (XXX);

Delete: delete(int start,int end);

SetCharAt (int n,char ch)/replace(int start, int end, String STR);

CharAt (int n);

Insert (int offset, XXX);

Length: length ();

Traverse: for() + charAt()/toString();

Code examples:

@Test
public void stringBufferMethodTest(a){
    StringBuffer s1 = new StringBuffer("abc");
    System.out.println(s1);

    System.out.println(s1.append("1"));//abc1
    System.out.println(s1.delete(0.1));//bc1
    System.out.println(s1.replace(0.1."hello"));//helloc1
    System.out.println(s1.insert(3."v"));//helvloc1
    System.out.println(s1.reverse());//1colvleh
}

Copy the code

(2) StringBuilder class

StringBuilder is very similar to StringBuffer in that it represents a mutable sequence of characters and provides the same functionality, except that the StringBuilder class does not have a thread lock and is more efficient.

1. Comparison of String, StringBuffer, and StringBuilder

  • String: immutable sequence of characters; The underlying usechar[]Storage; Memory footprint (constantly creating and reclaiming objects)
  • StringBuffer: a variable sequence of characters; Thread-safe, inefficient; Thread safety; The bottom layer uses char[] for storage;
  • StringBuilder: mutable character sequences; Jdk5.0 new, thread unsafe, high efficiency; Threads are not safe; The underlying usechar[]storage

Note: When passed as a parameter, Stng inside the method does not change its value, StringBuffer and StringBuilder do.

2. Memory parsing of StringBuffer and StringBuilder

Take StringBuffer for example:

String str = new String();//char[] value = new char[0];
String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};

StringBuffer sb1 = new StringBuffer();//char[] value = new char[16]; The bottom layer creates an array of length 16.
System.out.println(sb1.length());//
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';

StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];

Copy the code

StringBuffer constructor:

public StringBuffer(String str) {
    super(str.length() + 16);
    append(str);
}

Copy the code

Q.1 System. Out. Println (sb2. The length ()); / / 3

Problem 2. Capacity expansion Problem: If the underlying array to be added is not enough, you need to expand the underlying array. By default, the size is doubled + 2 and the elements in the original array are copied into the new array.

StringBuffer(int capacity) or StringBuilder(int capacity)

3. Compare the efficiency of String, StringBuffer, and StringBuilder

Order from high to low: StringBuilder > StringBuffer > String

@Test
public void test3(a){
    // Initial Settings
    long startTime = 0L;
    long endTime = 0L;
    String text = "";
    StringBuffer buffer = new StringBuffer("");
    StringBuilder builder = new StringBuilder("");
    // Start comparing
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
        buffer.append(String.valueOf(i));
    }
    endTime = System.currentTimeMillis();
    System.out.println("StringBuffer execution time:" + (endTime - startTime));

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
        builder.append(String.valueOf(i));
    }
    endTime = System.currentTimeMillis();
    System.out.println("StringBuilder execution time:" + (endTime - startTime));

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
        text = text + i;
    }
    endTime = System.currentTimeMillis();
    System.out.println("String execution time:" + (endTime - startTime));

}

Copy the code

Date and time apis prior to JDK 8.0

1. java.lang.System

The System class provides public Static Long currentTimeMillis() to return the time difference in milliseconds between the current time and 00:00:00:00 on January 1, 1970. (timestamp) This method is suitable for calculating time differences.

The main criteria for calculating world time are:

  • Coordinated Universal Time
  • GMT (Greenwich Mean Time)
  • Central Standard Time (CST)

Code examples:

CurrentTimeMillis () in the System class
long time = System.currentTimeMillis();
// Returns the time difference in milliseconds between the current time and 00:00:00:00 on January 1, 1970.
// This is called a timestamp
System.out.println(time);

Copy the code

2. java.util.Dateclass

Represents a specific moment, to the millisecond

2.1 the constructor

Date(): Creates an object with a no-argument constructor to get the local current time

Date(long date)

2.2 Common Methods

GetTime () : Returns the number of milliseconds represented by this Date object since 00:00:00 GMT, January 1, 1970

Tostring () : Converts this Date object to a String of the following form:

  • dow mon dd
  • hh: mm:ss zzz yyyy

DoW is the day of a week (Sun, Mon, Tue, Wed, Thu, Fri, Sat), and ZZZ is the time standard. Many other methods are outdated

2.3 Java. Util. The Date class with Java. SQL. The Date

  • Java. Util. The Date class

  • Java. SQL. The Date class

1. Use of two constructors

  • Constructor 1:Date(): Creates a Date object corresponding to the current time
  • Constructor 2: Creates a Date object with the specified number of milliseconds

2. Use of the two methods

  • toString(): Displays the current year, month, day, hour, minute, and second
  • getTime(): Gets the number of milliseconds corresponding to the current Date object. (Timestamp)

3. Java.sql. Date corresponds to a variable of the Date type in the database

How do I convert a java.util.Date object to a java.sql.Date object

@Test
public void dateTest(a){
    Constructor 1: Date() : creates a Date object corresponding to the current time
    Date date1 = new Date();
    System.out.println(date1.toString());//Sun Apr 19 13:35:12 CST 2020
    System.out.println(date1.getTime());/ / 1587274512876

    Constructor 2: Creates a Date object with the specified number of milliseconds
    Date date2 = new Date(15872745176L);
    System.out.println(date2.toString());
    System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

    // Create a java.sql.Date object
    java.sql.Date date3 = new java.sql.Date(1587274512876L);
    System.out.println(date3.toString());

    // How to convert a java.util.Date object to a java.sql.Date object
    Date date4 = new Date();
    Java.util. Date cannot be cast to java.sql.Date
    // java.sql.Date date6 = (java.sql.Date) date4;
    // System.out.println(date6);
    // The second way
    java.sql.Date date5 = new java.sql.Date(date4.getTime());
    System.out.println(date5);
}

Copy the code

3. java.text.SimpleDateFormat

Most of the AP is not easy to internationalization, the Date class were abandoned, Java. Text. The SimpleDateFormat classes is not a way related to the language environment to specific classes of formatting and parsing the Date.

It allows formatting: date → text, parsing: text → date

Formatting:

SimpleDateFormat() : Default schema and locale to create objects

Public SimpleDateFormat(String Pattern) : This constructor creates an object in the format specified by the pattern argument that calls:

Public String format(Datedate) : Format the date object

Public Date parse(String source) : Parse text from the beginning of a given String to generate a Date

1. SimpleDateFormat Format and parse the Date class

Two operations:

1.1 Formatting: Date –> string

1.2 Parsing: reverse process of formatting, string –> date

2. SimpleDateFormatInstantiation of:New + constructor

Format and parse as specified: call the parameterized constructor

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");

Copy the code

Code examples:

@Test
public void test2(a) throws ParseException {
    // Instantiate the Date object
    Date date1 = new Date();
    // Instantiate the SimpleDateFormate object and format it
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:aaa");
    // Format the date object
    String format = simpleDateFormat.format(date1);
    System.out.println(format.toString());/ / the 2020-09-19 02:09: in the afternoon
    // The string must be in a format recognized by SimpleDateFormat (as indicated by the constructor argument).
    // Otherwise, throw an exception
    Date date2 = simpleDateFormat.parse("2020-04-20 14:20:下午");
    System.out.println(date2.toString());//Tue Jan 21 02:20:00 CST 2020
}

Copy the code

Little practice:

Convert the string “2020-09-08” to java.sql.Date format

@Test
public void test3(a) throws ParseException {
    String brith = "1997-10-15";
    // Create a SimpleDateFormat object and set the time format
    SimpleDateFormat simpBrith = new SimpleDateFormat("yyyy-mm-dd");
    // Format the string time into the Date class
    Date brithday = simpBrith.parse(brith);
    // Use Date's getTime method to convert a Date object to a timestamp in the java.sql. Date constructor
    java.sql.Date brithDate = new java.sql.Date(brithday.getTime());
    System.out.println(brithDate);
}

Copy the code

4. Calendar class: Calendar class, abstract class

Calendar is an abstract base class that is primarily used to perform interoperation between date fields.

  • The method that gets Calenda instance calls the constructor of its subclass GregorianCalendarl using the calendar.getInstance () method.
  • An instance of Calendar is an abstract representation of the system time, with the get(int field) method to get the desired time information. For example, YEAR, MONTH, DAY_OF_WEEK, HOUR_OF_DAY, MINUTE, and SECOND

Note: Get month: January 0, February 1, and so on, December 11 get week: Sunday 1, Tuesday 2… Saturday is 7

4.1 instantiation

Method 1: Create an object that subclasses GregorianCalendar

Method 2: Call its static method getInstance()

Calendar calendar = Calendar.getInstance();

Copy the code

4.2 Common Methods

Get (): Gets the date

Set (): Sets the date

Add (): adds or modifies the date

GetTime: calendar class –>Date

SetTime: Date — > calendar classes

Code examples:

Calendar calendar = Calendar.getInstance();
// System.out.println(calendar.getClass());

//2
//get()
int days = calendar.get(Calendar.DAY_OF_MONTH);// Get the day of the month
System.out.println(days);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));// Get the day of the year

//set()
/ / the calendar variability
calendar.set(Calendar.DAY_OF_MONTH,22);// Set the day of the month
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);

//add()
calendar.add(Calendar.DAY_OF_MONTH,-3);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);

//getTime(): calendar --> Date
Date date = calendar.getTime();
System.out.println(date);

//setTime():Date --> calendar class
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);

Copy the code

New datetime classes in JDK 8.0

1. Iteration of the datetime API:

First generation: JDK 1.0 Date class

The second generation: JDK 1.1 Calendar class, to some extent to replace the Date class

Third generation: JDK 1.8 introduces a new set of apis

2. Problems of the first two generations:

Variability: Classes like date and time should be immutable.

Offset: The year in Date starts at 1900 and the month starts at 0.

Formatting: Formatting only works with Date, not Calendar. In addition, they are not thread-safe; Can’t handle leap seconds and so on.

New java.time API for Java 8.0:

Java 8.0 takes the best of Joda-time and creates a great APl for Java with a fresh start. The new java.time contains all classes for LocalDate, Localtime, LocalDate time, ZonedDate time, and Duration. The long-established Date class adds a tolnstant() method to convert Date into a new representation. These new localized time and date apis greatly simplify the management of date and time and localization.

3. Packages covered by the new datetime API in Java 8.0:

4. Use of local date, local time, local date and time:

LocalDate / LocalTime / LocalDateTime

Description: 4.1

① Indicates the date, time, date, and time of using the ISO-8601 calendar system respectively. They provide a simple local date or time and do not contain current time information or time-zone specific information.

2. LocalDateTime is used more frequently than LocalDate and LocalTime

③ Similar to Calendar

4.2 Common Methods:

Code examples:

@Test
public void test1(a){
    //now(): Gets the current date, time, date time
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    System.out.println(localDate);/ / 2020-04-21
    System.out.println(localTime);/ / 18:52:54. 929
    System.out.println(localDateTime);/ / the 2020-04-21 T18:52:54. 929

    //of(): sets the specified year, month, day, hour, minute, and second. No offset
    LocalDateTime localDateTime1 = LocalDateTime.of(2020.10.6.12.13.12);
    System.out.println(localDateTime1);//2020-10-06T12:13:12

    //getXxx() : get the related attributes
    System.out.println(localDateTime.getDayOfMonth());/ / 21
    System.out.println(localDateTime.getDayOfWeek());//TUESDAY
    System.out.println(localDateTime.getMonth());//APRIL
    System.out.println(localDateTime.getMonthValue());/ / 4
    System.out.println(localDateTime.getMinute());/ / 52

    // Reflect immutability
    //withXxx(): Sets the relevant properties
    LocalDate localDate1 = localDate.withDayOfMonth(22);
    System.out.println(localDate);/ / 2020-04-21
    System.out.println(localDate1);/ / 2020-04-22

    LocalDateTime localDateTime2 = localDateTime.withHour(4);
    System.out.println(localDateTime);/ / the 2020-04-21 T18: Lord. 484
    System.out.println(localDateTime2);/ / the 2020-04-21 T04: Lord. 484

    // immutability
    LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
    System.out.println(localDateTime);/ / the 2020-04-21 T18: Lord. 484
    System.out.println(localDateTime3);/ / the 2020-07-21 T18: Lord. 484

    LocalDateTime localDateTime4 = localDateTime.minusDays(6);
    System.out.println(localDateTime);/ / the 2020-04-21 T18: Lord. 484
    System.out.println(localDateTime4);/ / the 2020-04-15 T18: Lord. 484
}

Copy the code

5. Time point: Instant

Description: 5.1

① AN instant point in time. Conceptually, it simply represents the number of seconds since 00:00:0 (UTC) on January 1, 1970.

Similar to java.util.Date class

5.2 Common Methods:

Code examples:

@Test
public void test2(a){
    //now(): get the standard time corresponding to the prime meridian
    Instant instant = Instant.now();
    System.out.println(instant);: / / 2020-04-21 T11 03:21. 469 z

    // Add time offset
    OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
    System.out.println(offsetDateTime);/ / the 2020-04-21 T19:03:21. 469 + 08:00

    //toEpochMilli(): get the number of milliseconds starting from 0 hour 0 minute 0 second (UTC, 1 January 1970) --> Date getTime()
    long milli = instant.toEpochMilli();
    System.out.println(milli);/ / 1587467105795

    //ofEpochMilli(): get Instant instance with the given number of milliseconds -->Date(long millis)
    Instant instant1 = Instant.ofEpochMilli(1587467105795L);
    System.out.println(instant1);: / / 2020-04-21 T11 05:05. 795 z
}

Copy the code

6. Date-time formatting class:DateTimeFormatter

Description: 6.1

① Format or parse the date and time

② Similar to SimpleDateFormat

6.2 Common Methods:

  1. Instantiation method: Predefined standard format. Such as:ISO\_LOCAL\_DATE\_TIME;
  • ISO_LOCAL_DATE; ISO_LOCAL_TIME localization related format:
  • Such as:ofLocalizedDateTime(FormatStyle.LONG)
  • Custom format: for example:OfPattern (" MM - dd yyyy - hh: MM: ss ")
  1. Common methods:

    Special: custom format. Such as: ofPattern (” MM – dd yyyy – hh: MM: ss “)

    Code examples:

    @Test
    public void test3(a){
        // Method 1: Predefined standard format.
        / / such as: ISO_LOCAL_DATE_TIME; ISO_LOCAL_DATE; ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        // Format: date --> string
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);/ / the 2020-04-21 T19: ". 530
        System.out.println(str1);/ / the 2020-04-21 T19: ". 53
    
        // Parse: string --> date
        TemporalAccessor parse = formatter.parse("The 2000-04-21 T19:" 53");
        System.out.println(parse);//{},ISO resolved to 2000-04-21T19:13:13.530
        // Method 2:
        // Localise the relevant format. Such as: ofLocalizedDateTime ()
        LONG/formatstyle. MEDIUM/formatstyle. SHORT: applies to LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        / / format
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);// 07:16:57 PM on 21 April 2020
    
        // Localise the relevant format. Such as: ofLocalizedDate ()
        LONG/formatstyle. MEDIUM/formatstyle. SHORT: applies to LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        / / format
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);/ / 2020-4-21
    
        // Key: Method 3: custom format. Such as: ofPattern (" MM - dd yyyy - hh: MM: ss ")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String Str4 = formatter3.format(LocalDateTime.now());
        System.out.println(Str4);/ / the 2020-04-21 07:24:04
    
        TemporalAccessor accessor = formatter3.parse("The 2020-02-03 05:23:06");
        System.out.println(accessor);//{SecondOfMinute=6, HourOfAmPm=5, NanoOfSecond=0, MicroOfSecond=0, MinuteOfHour=23, MilliOfSecond=0},ISO resolved to 2020-02-03
    }
    
    Copy the code

7. Use of other APIS:

7.1 Date and Time with Time Zone:

ZonedDateTime / ZoneId

Code examples:

// ZoneId: class contains all time zone information
@Test
public void test1(a){
    //getAvailableZoneIds(): gets the zoneIDS
    Set<String> zoneIds = ZoneId.getAvailableZoneIds();
    for(String s : zoneIds){
        System.out.println(s);
    }
    System.out.println();

    // Get the time corresponding to the Asia/Tokyo time zone
    LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
    System.out.println(localDateTime);


}
//ZonedDateTime: date time with time zone
@Test
public void test2(a){
    //now(): Gets the ZonedDateTime object for the local time zone
    ZonedDateTime zonedDateTime = ZonedDateTime.now();
    System.out.println(zonedDateTime);
    //now(ZoneId ID): gets the ZonedDateTime object for the specified time zone
    ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
    System.out.println(zonedDateTime1);
}

Copy the code

7.2 Time Interval:

Duration– Used to calculate two “time” intervals, in seconds and nanoseconds

Code examples:

@Test
public void test3(a){
    LocalTime localTime = LocalTime.now();
    LocalTime localTime1 = LocalTime.of(15.23.32);
    // Between (): static method that returns a Duration object representing the interval between two times
    Duration duration = Duration.between(localTime1, localTime);
    System.out.println(duration);

    System.out.println(duration.getSeconds());
    System.out.println(duration.getNano());

    LocalDateTime localDateTime = LocalDateTime.of(2016.6.12.15.23.32);
    LocalDateTime localDateTime1 = LocalDateTime.of(2017.6.12.15.23.32);

    Duration duration1 = Duration.between(localDateTime1, localDateTime);
    System.out.println(duration1.toDays());

}

Copy the code

7.3 Date Interval:

Period – Used to calculate the interval between two “dates” measured in years, months, and days

Code examples:

@Test
public void test4(a){
    LocalDate localDate = LocalDate.now();
    LocalDate localDate1 = LocalDate.of(2028.3.18);

    Period period = Period.between(localDate, localDate1);
    System.out.println(period);

    System.out.println(period.getYears());
    System.out.println(period.getMonths());
    System.out.println(period.getDays());

    Period period1 = period.withYears(2);
    System.out.println(period1);

}

Copy the code

7.4 Date and time corrector:TemporalAdjuster

Code examples:

@Test
public void test5(a){
    // What is the next Sunday to get the current date?
    TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);

    LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
    System.out.println(localDateTime);

    // When is the next working day?
    LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){

        @Override
        public Temporal adjustInto(Temporal temporal) {
            LocalDate date = (LocalDate)temporal;
            if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
                return date.plusDays(3);
            }else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
                return date.plusDays(2);
            }else{
                return date.plusDays(1); }}}); System.out.println(The next working day is: + localDate);
}

Copy the code

7.5 Conversion between the new date API and the original API:

Java comparator

1. Background of Java comparator:

  • Objects in Java, normally, can only be compared:= =! =. You can’t use><
  • But in a development scenario, we need to sort multiple objects, and by implication, we need to compare object sizes.
  • How to do that? Use either of two interfaces: Comparable (natural sorting) or Comparator (custom sorting)

2. Natural sort: Use the Comparable interface

2.1 illustrates

  1. The Comparable interface, implemented by things like String or wrapper classes, overrides the compareTo(obj) method and gives a way to compare the sizes of two objects.

  2. When a class like String or wrapper overrides the compareTo() method, it sorts it from smaller to larger

  3. Override compareTo(obj) to return a positive integer if the current object this is greater than the parameter object obj, a negative integer if the current object this is less than the parameter object obj, and zero if the current object this is equal to the parameter object obj.

  4. For custom classes, if we need to sort, we can have our custom classes implement the Comparable interface and override the compareTo(obj) method. Specify how to sort in the compareTo(obj) method

  5. Comparable typical implementations: (Default is to order from smallest to largest) String: compare the Uincode values of the characters in the String Boolean: True the corresponding wrapper class is greater than false the corresponding wrapper class is Date, Time, etc. : The following date time is larger than the preceding date time

2.2 Examples of custom Class code:

public class Goods implements  Comparable{

    private String name;
    private double price;

    // Specify a way to compare the sizes of items: from lowest to highest by price, and from highest to lowest by product name
    @Override
    public int compareTo(Object o) {
        // System.out.println("**************");
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            // Method 1:
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
                // return 0;
                return -this.name.compareTo(goods.name);
            }
            // Method 2:
            // return Double.compare(this.price,goods.price);
        }
        // return 0;
        throw new RuntimeException("Incoming data type inconsistent!");
    }
    Getter, setter, toString(), constructor: omitted
}

Copy the code

3. Custom sorting: Use the Comparator interface

Description: 3.1

  1. Background:

When the java.lang.Comparable interface is not implemented for element types and code cannot be modified, or the sorting rules of the java.lang.Comparable interface are not suitable for current operations, you can use Comparator to sort elements

Compare (Object o1,Object O2) compare(Object o1,Object O2)

  • If the method returns a positive integer, then o1 is greater than O2;
  • If 0 is returned, it is equal;
  • Returns a negative integer indicating that O1 is less than O2.

3.2 Code Examples:

Comparator com = new Comparator() {
    // Specify a way to compare the sizes of items: from lowest to highest by product name, and from highest to lowest by price
    @Override
    public int compare(Object o1, Object o2) {
        if(o1 instanceof Goods && o2 instanceof Goods){
            Goods g1 = (Goods)o1;
            Goods g2 = (Goods)o2;
            if(g1.getName().equals(g2.getName())){
                return -Double.compare(g1.getPrice(),g2.getPrice());
            }else{
                returng1.getName().compareTo(g2.getName()); }}throw new RuntimeException("Inconsistent data types entered"); }}Copy the code

4. Compare the two sorting methods

  • The Comparable interface is structured in a way that ensures that objects of the Comparable interface implementation classes can be sized anywhere.
  • The Comparator interface is a temporary comparison.

Other common classes

1. The System class

  • The System class represents the System, and many of the system-level properties and control methods are placed inside the class. This class is located in the java.lang package.
  • Because the constructor of the class is private, objects of the class cannot be created, that is, the class cannot be instantiated. Its internal member variables and methods are static, so it can be easily called.

Member methods:

  • Native long currentTimeMillis () :

    This method returns the current computer time, expressed as the number of milliseconds between the current computer time and GMT (Greenwich Mean Time) on January 1, 1970.

  • void exit(int status)

    This method exits the program. If the status value is 0, the exit is normal; if the status value is not 0, the exit is abnormal. This method can be used to realize the program exit function in graphical interface programming

  • void gc()

    The purpose of this method is to request the system to do garbage collection. Whether the system collects garbage immediately depends on the implementation of the garbage collection algorithm in the system and the execution of the system.

  • String getProperty(String key)

    The function of this method is to get the value of a property in the system named key. The following table lists common attribute names and their functions:

Code examples:

@Test
public void test1(a) {
    String javaVersion = System.getProperty("java.version");
    System.out.println("java的version:" + javaVersion);

    String javaHome = System.getProperty("java.home");
    System.out.println("java的home:" + javaHome);

    String osName = System.getProperty("os.name");
    System.out.println("The OS name:" + osName);

    String osVersion = System.getProperty("os.version");
    System.out.println("The OS version." + osVersion);

    String userName = System.getProperty("user.name");
    System.out.println("user的name:" + userName);

    String userHome = System.getProperty("user.home");
    System.out.println("The user's home." + userHome);

    String userDir = System.getProperty("user.dir");
    System.out.println("The user dir." + userDir);

}

Copy the code

2. The Math class

Java.lang. Math provides a set of static methods for scientific computing. The arguments and return values of its methods are typically of type double.

3.BigInteger and BigDecimal classes

3.1 BigInteger

The BigInteger of the java.math package can represent immutable integers of arbitrary precision.

BigInteger provides equivalents for all of Java’s basic integer operators and provides all of the related methods of java.lang.Math. In addition, BigInteger provides the following operations: modular arithmetic, GCD calculation, prime number testing, prime number generation, bit manipulation, and a few other operations.

Constructor: BigInteger(String val) : Builds a BigInteger object from a String

Code examples:

@Test
public void test2(a) {
    BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
    BigDecimal bd = new BigDecimal("12435.351");
    BigDecimal bd2 = new BigDecimal("11");
    System.out.println(bi);
    // System.out.println(bd.divide(bd2));
    System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
    System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));

}

Copy the code

3.2 BigDecimal

Requires high numeric precision, using the java.math.BigDecimal class

The BigDecimal class supports immutable, arbitrarily precision signed decimal fixed-point numbers.

The constructor:

public BigDecimal(double val)

public BigDecimal(String val)

Common methods:

public BigDecimal add(BigDecimal augend)

public BigDecimal subtract(BigDecimal subtrahend)

public BigDecimal multiply(BigDecimal multiplicand)

Pawntask Public BigDecimal divide(BigDecimal divisor, int scale, int Pawmode)

Code examples:

@Test
public void test2(a) {
    BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
    BigDecimal bd = new BigDecimal("12435.351");
    BigDecimal bd2 = new BigDecimal("11");
    System.out.println(bi);
    // System.out.println(bd.divide(bd2));
    System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
    System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));

}

Copy the code