Javase--13 -- common classes

Posted by backinblack on Wed, 09 Mar 2022 03:21:33 +0100

13 - common classes

13 - 1 packaging

1. Reference corresponding to eight basic data types - packaging class;

2. By wrapping the class, you can call the method of the corresponding class;

Basic data typePackaging
The direct parent class of Boolean and Character is Object
There are six kinds of, and the direct parent class is Number

13-1-1 conversion of packaging class and basic data type

1. Manual packing and unpacking before JDK5

Manual packing

// Boxing int -- > integer
int a = 99;
Integer integer01 = new Integer(a);
Integer integer02 = Integer.valueOf(a);

Manual unpacking

// Unpacking integer -- > int
Integer integer03 = new Integer(66);
int b = Integer.intValue(integer03);

2. Automatic packing and unpacking after JDK5 (including JDK5)

  • The bottom layer of automatic packing automatically calls the valueOf() method, and the bottom layer of automatic unpacking calls the intValue() method

Automatic packing

int a1 = 36;
//The bottom layer is integer, integer1 = integer valueOf(a1)
Integer integer1 = a1; 

Automatic unpacking

Integer integer2 = new Integer(666);
//Underlying int A2 = integer intValue(integer02);
int a2 = integer2;

Test topic

//What is the output?
Object obj1 = true ? new Integer(1) : new Double(2.0);
System.out.println(obj1); //Output 1.0

   be careful:
   1,Ternary operators are a whole;
   2,Pay attention to the priority of basic data types;

13-1-2 conversion of packing class and String type

1. Integer type ----- > string type

Integer a = 888; //Automatic packing
  Mode 1
  be careful:
  1,The string converted from a as the basic value has no effect on the type of the original a;
String str1 = a + "";

//Mode 2
String str2 = a.toString();

//Mode 3
String str3 = String.valueOf(a);

2. String type ----- > integer type

String str4 = "6688";
//Mode 1 
Integer i1 = Integer.parseInt(str4); //Automatic packing is used here
//Mode 2
Integer i2 = new Integer(str4); //Through constructor

13-1-3 common methods

1. There are many methods, the core: you can check the API. You should understand the API. Loose. It is not recommended to rely on translation software to help you translate. You should try to read the original English file and use the understanding. Unless you really can't translate in some places, you can't use the translation software!!!

13-1-4 classic topics

1. Topic 1

Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j); //False
Note: This method will always cache values in the range -128 to 127
 Tips from Lao Han:
   1,If i is between - 128 and 127, it is returned from the array;
   2,How to directly return new Integer(i) if i is not between - 128 ~ 127;
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
Integer m = 1; //Underlying integer valueOf(1);  Look at the source code above
Integer n = 1;//Underlying integer valueOf(1);
System.out.println(m == n); //T
Integer x = 128;//Underlying integer valueOf(1);
Integer y = 128;//Underlying integer valueOf(1);
System.out.println(x == y);//F

2. Topic 2

Integer i11=127;
int i12=127;
//There are only basic data types, which judge whether the values are the same
System.out.println(i11==i12); // T

13 - 2 String class

1. String object is used to save a string, that is, a set of character sequences;

2. String constant object - a sequence of characters enclosed in double quotes, such as "hello"

3. The characters of the string are encoded with Unicode characters, and one character occupies two bytes (no distinction between letters or Chinese characters);

4. String class diagram:

(1) String implements the Serializable interface, which shows that string can be serialized and transmitted on the network;

(2) String implements the Comparable interface, which shows that string objects can compare sizes;

5. String class is a final modifier and cannot be inherited by other classes;

6. String has attribute private final char value []; Used to store string content;

  • Value is a final type and cannot be modified: that is, value cannot point to a new address, but the content of a single character can be changed;

13-2-1 String two ways to create objects

1. Direct assignment: String s = "hsp";

  • First, check whether there is "hsp" data space from the constant pool. If so, point to it directly; If not, recreate and point to. s finally points to the spatial address of the constant pool.

2,constructor: String s2 = new String("hsp");

  • First, create a space in the heap with the value attribute, which points to the hsp space of the constant pool; If there is no "hsp" in the constant pool, recreate it. If there is, point to it directly through value. The final point is the spatial address in the heap.

JVM memory distribution

13-2-2 classic question of string

1. About the intern() method

  • Lao Han tips: b.intern() finally returns the address of the constant pool;
public class Test {
    public static void main(String[] args) {
        String a = "song";
        String b = new String("song");
        String c = b.intern();
        System.out.println(a == b);

        intern()Method interpretation
         When the intern method is invoked, if the pool already contains a
         string equal to this {@code String} object as determined by
         the {@link #equals(Object)} method, then the string from the pool is
         returned. Otherwise, this {@code String} object is added to the
         pool and a reference to this {@code String} object is returned.
        System.out.println(a == b.intern());// true
        System.out.println(b == b.intern()); // false

Memory distribution map

2. This topic is not difficult. Every time you look at it, it is recommended to draw the memory distribution map by yourself to deepen your understanding;

public class Practice02 {
    public static void main(String[] args) {
        Person p1 = new Person(); = "hspedu";
        Person p2 = new Person(); = "hspedu";
        System.out.println(; //Compare content true
        System.out.println( ==; // true
        System.out.println( == "hspedu"); // true

        String str1 = new String("abc");
        String str2 = new String("abc");
        System.out.println(str1 == str2); //Whether the comparison object points to the same object false

class Person{
    public String name;

    public Person(){}

    public Person(String name) { = name;

13-2-3 characteristics of string

1. String is a final class, which represents an immutable character sequence;

2. Strings are immutable. Once a string object is allocated, its content is immutable;

  * The value is used for character storage.
  Loose, pay attention:
  1,JDK12 The String class in the source code, the value array used for character storage, is changed to byte type;
  2,JDK8 The String class in the source code, the value array used for character storage, is of type char;

private final byte[] value;


1. Question: how many objects were created?

String a = "hello" + "abc";
   Lao Han tips:
   1,The compiler is not a fool. It makes an optimization to judge whether the created constant pool object has a reference point;
   2,String a = "hello" + "abc"; ---> String a = "helloabc";
   Answer: create an object;

2. Question: how many objects were created? Draw a memory map?

  • Create 3 objects
String a = "hello"; //Create a object
String b = "abc"; // Create b object
String c = a + b;

   Lao Han tips:
   1,The bottom layer is StringBuilder sbd = new StringBuilder();
   2,sbd.append(a) ;
   // sbd Is in the heap, and append is appended on the basis of the original string;
   4,String c= sbd.toString();
   Finally: in fact, c points to the object (string) value [] - > in the heap and "helloabc" in the pool
   1,String d = "an" + "wo"; Add constants to see a pool;
   2,String c = a + b; Variables are added in the heap

3. A very comprehensive exercise, mainly looking at the memory map:

public class Practice05 {
    public static void main(String[] args) {
        Test1 ex = new Test1();
        System.out.print(ex.str + " and ");
        //Output: hsp and hava

class Test1{
    String str = new String("hsp");
    final char[] ch = {'j','a','v','a'};
    public void change(String str,char[] ch){
        str = "java";
        ch[0] = 'h';

Memory distribution diagram, loose, follow the code to see the order

13-2-4 common methods of string class

1. split method;

  • When splitting a string, if there are special characters, you need to add the escape character \;

2. compareTo method;

Compare the size of two strings. If the former is large,
// Returns a positive number. If the latter is large, it returns a negative number. If it is equal, it returns 0
// Lao Han tips:
// (1) If the length is the same and each character is the same, 0 is returned
// (2) If the length is the same or different, but the comparison can be case sensitive
// Return if (C1! = C2){
//   return c1 - c2;
// }
//(3) If the previous parts are the same, STR1 is returned len - str2. len

3. format method;

  Lao Han tips:
  1, %s , %d , %.2f %c Called placeholder
  2, %s Indicates that it is replaced by a string;
  3, %d Is an integer to replace
  4,%.2f It means to replace with decimal. After replacement, only two decimal places will be reserved and rounded
  5, %c Replace with char type;

4. There are many methods of String class. Note: for subsequent use, refer to API ----- > here reflects the importance of English, loose!!!

13-3 StringBuffer

1,java.lang.StringBuffer represents a variable character sequence, and can add or delete string contents;

2. The variable length method is the same as String buffer;

3. StringBuffer is a container;

StringBuffer class diagram

4. Lao Han tips:

(1) The direct parent class of StringBuffer is AbstractStringBuilder;

(2) The serialization of objects, i.e. the serialization of objects to the network buffer, can be realized;

(3) In the parent class AbstractStringBuilder, there is the attribute char[] value. The value array stores the string content and references the value stored in the heap;

(4) StringBuffer is a final class and cannot be inherited;

(5) The contents of StringBuffer characters are stored in char[] value, so they are changing (adding / deleting) without changing the address every time (i.e. not creating a new object every time), so the efficiency is higher than that of String;

  • Tip: loose, you don't have to change the address every time (that is, you don't create a new object every time), that is, when there is not enough space, there is a capacity expansion mechanism to play a role. Here you can find the basis according to the source code!!!

13-3-1 String and StringBuffer

1. String saves string constants (stored in the constant pool), and the values in them cannot be changed. Each update of string class actually changes the address, which is inefficient;

  • Note: private final char[] value;

2. StringBuffer saves string variables whose values can be changed. Each update of StringBuffer can actually update the content without updating the address every time, which is more efficient.

  • Note: char[] value; This is stored in the heap

3. Several constructors commonly used in StringBuffer

//Parameterless constructor

StringBuffer sb01 = new StringBuffer();

   Look at the following source code:
   1,Parent class AbstractStringBuilder
   AbstractStringBuilder(int capacity) {
        if (COMPACT_STRINGS) {
            value = new byte[capacity];
            coder = LATIN1;
        } else {
            value = StringUTF16.newBytesFor(capacity);
            coder = UTF16;
    2,Subclass StringBuffer
        public StringBuffer() {
    3,You can see: create a char[] value with a size of 16 to store the character content


// Specify the size of char[] value through the constructor
StringBuffer sb02 = new StringBuffer(100);

  Look at the following source code:
  1,Parent class AbstractStringBuilder
   AbstractStringBuilder(int capacity) {
        if (COMPACT_STRINGS) {
            value = new byte[capacity];
            coder = LATIN1;
        } else {
            value = StringUTF16.newBytesFor(capacity);
            coder = UTF16;
    2,Subclass StringBuffer
    public StringBuffer(int capacity) {
    3,You can see: you can specify the size of char[] value through the constructor;


//By creating a StringBuffer for a String, the size of char [] is str.length() + 16

StringBuffer sb03 = new StringBuffer("hello");

   Look at the following source code:
    1,Parent class AbstractStringBuilder
   AbstractStringBuilder(int capacity) {
        if (COMPACT_STRINGS) {
            value = new byte[capacity];
            coder = LATIN1;
        } else {
            value = StringUTF16.newBytesFor(capacity);
            coder = UTF16;
    2,Subclass StringBuffer
     public StringBuffer(String str) {
        super(str.length() + 16);
    3,You can see:
    (1)First create a StringBuffer object for String. The size of char[] value is str.length + 16;
    (2)Add str to the through the append method;

13-3-2 conversion between string and StringBuffer

Song, look at the hint

  • Looking at the source code may be slower, but looking at the source code is the best!!!

1,String ----> StringBuffer

(1) Use constructor; Note: the returned object is the StringBuffer object, which has no effect on the incoming string itself;

(2) Use the append method;

2,StringBuffer —> String

(1) Use the toString method of StringBuffer to return String;

(2) Use the constructor of String, and the argument is of type StringBuffer;

13-3-3 common methods of StringBuffer

1. Append method ----- > used to append strings;

2. Delete (start, end) - -- > delete characters with > = start & & < end; (left closed right open)

3. replace(start,end, "xxxx") --- > used to replace the characters between start and end in the specified position; (left closed right open)

4. indexOf("xxxx") --- > find the index of the specified substring at the first occurrence of the string. If not found, return - 1;

5. s.insert(9, "Zhao Min") ---- > insert "Zhao Min" at the position of index 9, the original index is 9;

6. Length() ------ > calculate the length of the string

Exercise 1

  • Embodiment -- see the importance of source code
public class Exercise01 {
    public static void main(String[] args) {
        String str = null;
        StringBuffer sb = new StringBuffer();
        *  Tips:
        *  1,Here, the bottom layer calls the appendNull method of AbstractStringBuilder
        *  2,Look at the source code
        *private AbstractStringBuilder appendNull() {
         ensureCapacityInternal(count + 4);
         int count = this.count;
         byte[] val = this.value;
         if (isLatin1()) {
            val[count++] = 'n';
            val[count++] = 'u';
            val[count++] = 'l';
            val[count++] = 'l';
        } else {
            count = StringUTF16.putCharsAt(val, count, 'n', 'u', 'l', 'l');
        this.count = count;
        return this;
        * */
        // Note: the length of StringBuffer sb calculated here is not analyzed from the surface: the length is 0;
        System.out.println(sb.length()); //4
        System.out.println(sb); // null

Exercise 2

public class Exercise02 {
    public static void main(String[] args) {
        String str = null;
        The actual execution reaches this sentence: NullPointerException is thrown
        When an exception is thrown, the JVM interrupts the program;
        This sentence system out. println(sb01);  It won't be executed
        StringBuffer sb01 = new StringBuffer(str);
        //What is the printed output?
        *  1,Should print from surface analysis: null;
        *  2,The actual answer is: throw a NullPointerException
        *  3,When Str is passed in, the constructor StringBuffer(String str) will be called;
        *  4,The answer depends on the source code:
        *     public StringBuffer(String str) {
                  super(str.length() + 16);

            *5,super(str.length() + 16); Because the str passed in is null,
            *   Therefore, NullPointerException will be thrown
        * */

13-3 StringBuilder

1. A variable character sequence.

  • StringBuilder improves an API compatible with StringBuffer, but cannot guarantee synchronization (StringBuilder is not thread safe);
  • StringBuilder is used as a simple replacement for StringBuffer when the string buffer is used by a single thread. If you can, it is recommended to use StringBuilder first, because it is faster than StringBuffer in most implementations.

2. The operation on StringBuilder mainly depends on the append method and insert method, which can be overloaded;

13-3-1 basic knowledge of StringBuilder

1. StringBuilder inherits AbstractStringBuilder;

2. The Serializable interface is implemented, which shows that the StringBuilder object can be serialized (the object can be transmitted through the network and saved to a file);

3. StringBuilder is the final class;

4. The character sequence of the StringBuilder object is still stored in the char[] value of its parent class AbstractStringBuilder. Therefore, the character sequence is in the heap;

5. The StringBuilder method does not handle mutual exclusion, that is, there is no synchronized keyword. Therefore, it is used in the case of single thread and has the highest efficiency;

13-4 comparison between string buffer and StringBuilder

Same pointdifference
StringImmutable character sequence, low efficiency, but high reuse rate;
StringBufferStringBuffer and StringBuilder are very similar, both represent variable character sequences, and the methods are basically the same;Variable character sequence, high efficiency (addition and deletion), thread safety (see the source code);
StringBuilderVariable character sequence, the highest efficiency and unsafe thread;

1. Description of String

//Create a string
String s = "a";

  1,In fact, the original "a" string object has been discarded, and now a new string s + "b" (that is, "ab");
  2,If you perform these operations to change the string content multiple times, it will cause a large number of copy string objects to remain in memory and reduce efficiency.
     If placed in a loop, it will greatly affect the performance of the program.
  1,For the String class, a large number of duplicate strings are stored in memory due to multiple operations to change the contents of the String,
     Therefore, the reuse rate of String class is high;
     In fact, a more direct explanation ----- > in the String class, the String is stored in private final char[] value;
  2,However, if you want to make a lot of modifications to the String, do not use the String class;
s += "b";

2. Efficiency test of string buffer StringBuilder

public class TestEfficiency {
    public static void main(String[] args) {
        long startTime = 0L;
        long endTime = 0L;

        //Test StringBuffer efficiency
        StringBuffer buffer = new StringBuffer("");
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) { //StringBuffer splicing 100000 times
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer Execution time of:" + (endTime - startTime));

        //Test StringBuilder efficiency
        StringBuilder builder = new StringBuilder("");
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {//100000 splices of StringBuilder
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder Execution time of:" + (endTime - startTime));

        // Test String efficiency
        String text = "";
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {//String splicing 100000 times
            text = text + i;
        endTime = System.currentTimeMillis();
        System.out.println("String Execution time of:" + (endTime - startTime));

Operation results

13 - 5 string buffer StringBuilder use selection

Use principle, Lao Han tips

1. If there are a lot of modification operations for strings, StringBuffer / StringBuilder is generally used

2. If there are a lot of string modification operations, and in the case of single thread, StringBuilder is recommended

3. If there are a lot of string modification operations, and in the case of multithreading, StringBuffer is recommended

4. If the String is rarely modified and referenced by multiple objects, it is recommended: String, such as configuration information

13-6 Math class

1. The Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.

2. The methods of Math class are static methods. For the specific use of methods, you can check the API, which is yyds!!!

  • public final class Math
    extends Object
  • The constructor of Math class is a private modifier, so Math cannot create objects; The methods of Math class are static methods, which can be called directly through the class name;

  • Loose, this is also a description - when defining tool classes, you can refer to Math classes;

13-7 Arrays

Arrays contains a series of static methods to manage or manipulate arrays (such as search and sorting)

1. toString returns the string form of an array

  • Arrays.toString(arr);

2. Sort sort - natural sort and custom sort

Custom sorting, a little interesting

(1) According to Lao Han's tips, go again as follows

  • public class ArraysExercise01 {
        public static void main(String[] args) {
            //sort method natural sorting and custom sorting
            //1. Because the array is a reference type, sorting through sort will directly affect the actual parameter arr02;
            //2. sort overloaded can also be customized by passing in an interface Comparator
            //3. When calling custom sort, two parameters are passed in
            //   (1) Sorted array arr
            //   (2) The anonymous internal class of Comparator interface is implemented, and compare is required to be implemented
            //4. Source code execution process
            //(1)Arrays.sort(arr02, new Comparator<Integer>();
            //(2) Finally, static < T > void sort of TimSort class (t [] A, int lo, int Hi, / / comparator <? Super T > C, t [] work, int workbase, int worklen)
            //(3) When executing binarySort(a, lo, hi, lo + initRunLen, c);
            //   The anonymous inner class compare() we passed in will be executed according to the dynamic binding mechanism
            //   private static <T> void binarySort(T[] a, int lo, int hi, int start,
            //                                       Comparator<? super T> c)
            //   while (left < right) {
            //                int mid = (left + right) >>> 1;
            //                if (, a[mid]) < 0)
            //                    right = mid;
            //                else
            //                    left = mid + 1;
            //            }
            //(4)new Comparator<Integer>() {
            //            @Override
            //            public int compare(Integer o1, Integer o2) {
            //                Integer i1 = (Integer) o1;
            //                Integer i2 = (Integer) o2;
            //                return i1 - i2;
            //            }
            //5. You can see that the value returned by public int compare(Integer o1, Integer o2) is > 0 / < 0
            //   It will affect the result of the whole sorting
            //6. Above: comprehensive application of interface programming + dynamic binding + anonymous inner class
            Integer[] arr02 = {-5,0,89,1,-66};
            Arrays.sort(arr02, new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    Integer i1 = (Integer) o1;
                    Integer i2 = (Integer) o2;
                    return i1 - i2;
            System.out.println("====Sorted array====");

Customize the order as follows

  • public class ArraysExercise02 {
        public static void main(String[] args) {
            int[] arr = {-5,3,0,1,66,88,-1};
            arraySort(arr, new Comparator() {
                public int compare(Object o1, Object o2) {
                    int i1 = (Integer) 01;
                    int i2 = (Integer) o2;
                    return i1 - i2;
            System.out.println("===Order after array sorting===");
        public static void arraySort(int[] arr, Comparator c) {
            int temp = 0;
    //                int arrj01;
    //                int arrj02;
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = i; j < arr.length - 1; j++) {
    //                int arrj01 = (Integer) arr[j];
    //                int arrj02 = (Integer) arr[j+1];
                    if ([j], arr[j + 1]) > 0) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
  • The results are as follows: if there is a problem with the results, remember to optimize when looking again

  • There is a problem here. If there are two negative numbers in a group of numbers,

  • (1) Sorting with normal bubbles written by myself or customized sorting written by myself will lead to wrong sorting. I can't optimize it now!

  • (2) However, using the sort method provided by Arrays to sort, the result is no problem;

3. Binary search - search through binary search method, which requires that the order must be arranged first;

  • /*
     1,The array must be ordered. If the array is unordered, binarySearch cannot be used
     2,If there is no corresponding element in the array, return - (low + 1)// key not found.

4. copyOf -- copy of array elements

  • Lao Han tips:

  • /*
       1. Copy arr.length elements from the ARR array to the newArr array
       2. If the length of the copy is > arr.length, null will be added after the new array
       3. If the copy length is < 0, an exception NegativeArraySizeException is thrown
       4. The bottom layer of this method is system arraycopy()

5. fill -- filling of array elements

  • Use a num01 to fill the array, that is, use num01 to replace the original elements;

6. equals -- compare whether the two array elements are consistent

7. asList -- convert a group of values into a list;

  • Lao Han tips:

  • /*
       1,asList Method to convert {1,2,3,4,5,6} data bits into a List set;
       2,Look at the source code and return asList. The compilation type is: List < T > interface
              public static <T> List<T> asList(T... a) {
                    return new ArrayList<>(a);
       3,Run type: class java util. Arrays$ArrayList
             This is the static internal class of Arrays. See below
             private static class ArrayList<E> extends AbstractList<E>
                     implements RandomAccess,
    public class ArraysExercise03 {
        public static void main(String[] args) {
            Integer[] arr = {1, 2, 3, 4, 5, 6};
            List<Integer> integers = Arrays.asList(arr);
            System.out.println("integerList:" + integers);
            //The compilation type of integers is List(Integer). Take a look at the running type

13 - 8 System class

1. Exit method: exit the current program;

   1,exit(0) Indicates that the program exits;
   2,0 Indicates a state, a normal state;

2. arrayCopy method: copy array elements, which is more suitable for the underlying call. Generally, arrays Copyof completes copying the array;

  • public class SystemExercise02 {
        public static void main(String[] args) {
            int[] arr1 = {1,2,3};
            int[] dest = new int[3];
            * Lao Han's hint - that is, if you understand the meaning of these five parameters, it's OK!!!
            *  @param      src      the source array.
             * @param      srcPos   starting position in the source array.
             * @param      dest     the destination array.
             * @param      destPos  starting position in the destination data.
             * @param      length   the number of array elements to be copied.
            * */

3. currentTimeMillens: returns the milliseconds of the current time distance 1970-1-1;

4. GC: run garbage collection mechanism, system gc();

13-9 BigInteger and BigDecimal classes

1. BigInteger: it is suitable for saving large integers;

2. BigDecimal: suitable for saving floating-point numbers (decimals) with higher precision;

3. BigInteger and BigDecimal common methods

(1) Add add

(2) subtract;

(3) multiply;

(4) divide;

BigInteger practice code, combined with the source code of the four methods, with corresponding instructions, we need to see

  • public class BigIntegerExercise01 {
        public static void main(String[] args) {
    //        int i = 99999999999999999999999999999999999999999999111111;
            *  1,Look at the class diagram: the direct parent classes of BigInteger and BigDecimal are number - > object
            *  2,The constructor is:
            *     public BigInteger(String val) {
                      this(val, 10);
            * */
            BigInteger bigInteger = new BigInteger("9999999999999999999999999999" +
            BigInteger bigInteger1 = new BigInteger("100000");
             * add(): Methods have overloads. The specific return type depends on the source code of the specific method called
             * */
    //        bigInteger = bigInteger.add(bigInteger1);
    //        System.out.println(bigInteger);
    //        System.out.println("**********************");
             * subtract(): Methods have overloads. The specific return type depends on the source code of the specific method called
             * */
    //        bigInteger = bigInteger.subtract(bigInteger1);
    //        System.out.println(bigInteger);
            * multiply():Methods have overloads. The specific return type depends on the source code of the specific method called
            * */
    //        bigInteger = bigInteger.multiply(bigInteger1);
    //        System.out.println(bigInteger);
            *  Returns a BigInteger whose value is {@code (this / val)}
            *  Note: the result is that the decimal part is removed;
            * */
            bigInteger = bigInteger.divide(bigInteger1);

BigDecimal practice code, mainly calls the divide method. Please pay attention to it

  • public class BigDecimalExercise01 {
        public static void main(String[] args) {
            double i = 32.22222225555555555555111111111333333888888888d;
            * BigDecimal of
            * 1,add()  subtract()  multiply()
            * 2,divide()Note that sometimes calculations may throw exceptions
            *      ArithmeticException: Non-terminating decimal expansion;
            *              no exact representable decimal result.
            * 3,When calling the divide() method, specify the precision BigDecimal.ROUND_CEILING
            * */
            BigDecimal bigDecimal = new BigDecimal("444444.4444444444444" +
            BigDecimal bigDecimal01 = new BigDecimal("2");

13 - 10 date categories

Generation 10-1 Date

1. Date: accurate to milliseconds, representing a specific moment;

2. SimpleDateFormat: a class that formats and parses dates;

(1) Allow formatting: date - > text;

(2) Parsing (text - > date) and normalization;

  • //You can convert a formatted String to date
     //1. String -- > date, the format defined by SimpleDateFormat should be the same as the given string format,
     //       Otherwise, an exception is thrown: Java text. ParseException

13-10-2 second generation date category - Calendar

1. Calendar class is an abstract class, which provides some methods for the conversion between a specific moment and a group of calendar fields such as YEAR MONTH... And some methods for operating calendar fields;

  • //1. Calendar class is an abstract class;
    //2. constructor is private;
    //3. Obtain the Calendar object through getInstance() method;
    //4. Calendar has no special formatting method, so you have to define it yourself;

13-10-3 third generation date category

1. JDK 1.0 includes a Java util. Date class, but most of its methods were abandoned after JDK 1.1 introduced the Calendar class. However, the Calendar class also has some problems:

(1) Variability: classes such as date and time should be immutable;

(2) Offset: the year in Date starts from 1900 and the month starts from 0;

(3) Formatting: formatting is only useful for Date, but not Calendar;

(4) Date Calendar is not thread safe and cannot handle leap seconds (one second more every two days);

2. LocalDate, Localtime, LocalDateTime -- JDK8 added

(1) LocalDate (date / mm / DD / yyyy): only the date is included, and the date field can be obtained;

  • /*
           *  1,LocalDate Is the final class;
           *  2,constructor It is a private decoration;
           *  3,Get the date object through the now() method
           *     Notes: observations the current date from the system clock 
                                    in the default time-zone.
                  public static LocalDate now() {
                      return now(Clock.systemDefaultZone());
           * */

(2) Local time (date / hour, minute and second): it only contains time, and the time field can be obtained;

(3) LocalDateTime (date / month, day, hour, minute and second): including date + time, which can obtain the field of date and time;

  • /*
            *  1,LocalDateTime Is the final class;
            *  2,constructor It is a private decoration;
            *  3,Get the date time object through the now() method
            *     Notes: observations the current date time from the system clock in the default time zone
                  public static LocalDateTime now() {
                       return now(Clock.systemDefaultZone());
            * */

3. DateTimeFormat - date format class;

  • /*
            *  DateTimeFormatter
            *  1,Is the final class;
            *  2,constructor Is private;
            *  3,Get the DateTimeFormatter object through the ofPattern() method
            *     public static DateTimeFormatter ofPattern(String pattern) {
                    return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();                      
            * */

4. Instant - time stamp

  • Conversion between Date and Instant

  • public class InstantExercise01 {
        public static void main(String[] args) {
            Instant instant =;
            //Instant can be converted to Date through the static from() method of the Date class
            Date from = Date.from(instant);
            //Use the toinst method of date to convert date into an Instant object
            Date date = new Date();
            Instant instant1 = date.toInstant();

5. Several methods and other methods demonstrated. When using them, you can check the API yourself;

  • // Plus or minus the current time

Topics: Java