Java se -- phase 2

Posted by suz_1234 on Wed, 22 Dec 2021 23:47:10 +0100

1. Enumerations and annotations

1. Enumeration introduction

Enumeration classes [pieces: one by one: examples, that is, the classes that instantiate specific objects one by one are called enumeration classes]

2. Custom class implementation enumeration

  • You do not need to provide a setXxx method, because enumeration object values are usually read-only

  • The enumerating objects / attributes are decorated with final+static to realize the underlying optimization

  • Enumerating object names usually use all uppercase

  • Enumeration objects can also have multiple properties as needed

  • Constructor privatization

  • Create a set of objects inside this class

  • Expose objects externally (usually add public final static for objects)

  • You can provide a get method instead of a set method

public class Enumeration02 {
    public static void main(String[] args) {
        System.out.println(Season.AUTUMN);
        System.out.println(Season.SPRING);
    }
}

//Demo word definition enumeration implementation
class Season {//class
    private String name;
    private String desc;//describe

    //Four objects are defined, fixed
    public static final Season SPRING = new Season("spring", "warm");
    public static final Season WINTER = new Season("winter", "cold");
    public static final Season AUTUMN = new Season("autumn", "pleasantly cool");
    public static final Season SUMMER = new Season("summer", "scorching hot");


    //1. Privatize the constructor to prevent direct new
    //2. Remove the setXxx method to prevent the attribute from being modified
    //3. Create fixed objects directly in Season
    //4. For optimization, the final modifier can be added
    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

3. enum keyword implements enumeration

1. Precautions

  • When developing an enumeration class with enum keyword, it will inherit an enum class by default, and it is a final class. After using enum keyword, you can't inherit other classes, but you can implement the interface

    • Using javap decompile, you can view

  • When using a parameterless constructor to create an enumerated object, the argument list and parentheses can be omitted

  • When there are multiple enumerated objects, use comma spacing and end with a semicolon

  • The enumeration object must be stored at the beginning of the line of the enumeration class

2. Common methods

  • toString:Enum class has been overridden. It returns the current object name. Subclasses can override this method to return the property information of the object
  1. Name: returns the current object name (constant name), which cannot be overridden in subclasses
  2. ordinal: returns the location number of the current object, starting from 0 by default
  3. values: returns all constants in the current enumeration class
  • valueOf: to convert a string into an enumeration object, the string must be its own constant name, otherwise an exception will be reported!
  1. compareTo: compare two enumeration constants. The comparison is the location number!
public class Enumeration03 {
    public static void main(String[] args) {
        System.out.println(Season2.AUTUMN);
        System.out.println(Season2.SUMMER);
    }
}
//Demonstrates the use of enum keywords to implement enumeration classes
enum  Season2 {//class

    //Four objects are defined, fixed
//    public static final Season SPRING = new Season("spring", "warm");
//    public static final Season WINTER = new Season("winter", "cold");
//    public static final Season AUTUMN = new Season("autumn", "cool");
//    public static final Season SUMMER = new Season("summer", "hot");
    //If enum is used to implement the enumeration class
    //1. Use the keyword enum instead of class
    //2. public static final Season SPRING = new Season("spring", "warm") for direct use
    //   SPRING("spring", "warm") interprets constant names (argument list)
    //3. If there are multiple constants (objects), use the interval between numbers
    //4. If enum is used to implement enumeration, it is required to define constant objects and write them in front
    //5. If we use a parameterless constructor to create a constant object, we can omit ()
    SPRING("spring", "warm"), WINTER("winter", "cold"), AUTUMN("autumn", "pleasantly cool"),
    SUMMER("summer", "scorching hot")/*, What()*/;

    private String name;
    private String desc;//describe

    private Season2() {//Parameterless constructor

    }

    private Season2(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}


4. jdk built-in basic annotation types

1. Annotation

  • Annotations, also known as metadata, are used to modify and interpret data information such as packages, classes, methods, properties, constructors, local variables, etc.

  • Like annotations, annotations do not affect program logic, but annotations can be compiled or run, equivalent to supplementary information embedded in code.

2. Three basic notes

  • @Override: defines a method and overrides the parent method. This annotation can only be used for methods

    • @Target(ElementType.METHOD)
  • @Deprecated: used to indicate that a program element (class, method, etc.) is obsolete

    • @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE,MODULE,PARAMETER, TYPE})
  • @SuppressWarnings: suppress compiler warnings

    • @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})

    • @SuppressWarning Property introduction and property description in
      
      all,Suppress all warnings
      boxing,Suppression and encapsulation/Warnings related to disassembly and assembly
      cast,Suppress warnings related to forced transition operations
      dep-ann,Suppress warnings related to obsolete comments
      deprecation,Suppress warnings related to obsolescence
      fallthrough,Inhibition and switch Omission in statement break Related warnings
      finally,Suppression and non return finally Block related warnings
      hiding,Suppresses warnings related to local variables of hidden variables
      incomplete-switch,Inhibition and switch indicative mood(enum case)Warnings about missing items in
      javadoc,Inhibition and javadoc Related warnings
      nls,Inhibition and non nls String text related warnings
      null,Suppress warnings related to null analysis
      rawtypes,Inhibition and use raw Type related warnings
      resource,Inhibition and use Closeable Warnings about resources of type
      restriction,Suppress warnings related to the use of deprecated or prohibited references
      serial,Suppress class omissions with serializability serialVersionUID Field related warnings
      static-access,Suppress warnings related to incorrect static access
      static-method,Suppression and possible declaration as static Method related warnings
      super,Suppression is related to the replacement method but does not include super Call warning
      synthetic-access,Suppress warnings related to suboptimized access to internal classes
      sync-override,Suppress warnings about missing synchronization because of permutation synchronization methods
      unchecked,Suppress warnings related to unchecked jobs
      unqualified-field-access,Suppress warnings related to unqualified field access
      unused,Suppress warnings related to unused and disabled code
      

5. Meta annotation: annotate the annotation (understand)

  • Retention / / specify the scope of E solution. There are three kinds of source, class and runtime
  • Target / / specifies where annotations can be used
  • Documented / / specifies whether the annotation will be reflected in the javadoc
  • Inherited / / the subclass inherits the annotation of the parent class
public class Homework08 {
    public static void main(String[] args) {
        //Demonstrate that enumerations are worth using with switch
        Color green = Color.GREEN;
        green.show();
        //Compare it
        //switch(), put the enumeration object
        //After each case, write it directly in the enumeration class and define the enumeration object
        switch (green) {
            case YELLOW:
                System.out.println("Match to yellow");
                break;
            case BLACK:
                System.out.println("Match to black");
                break;
            default:
                System.out.println("No match found..");
        }
    }
}

/*
Enumeration class
 Create a Color enumeration class
1.There are five enumerated values / objects: red, blue, black, yellow and green;
2.Color There are three properties redValue, greenValue, blueValue,
3.Create a construction method. The parameters include these three attributes,
4.Each enumeration value must assign a value to these three attributes, and the corresponding values of the three attributes are
red: 255,0,0  blue:0,0,255  black:0,0,0  yellow:255,255,0  green:0,255,0
5.Define the interface. There is a method show in it. Color is required to implement the interface
6.show Method to display the values of the three properties
7. Match enumeration objects in switch statements

 */
interface IMyInterface {
    public void show();
}

enum Color implements IMyInterface {
    RED(255, 0, 0), BLUE(0, 0, 255), BLACK(0, 0, 0), YELLOW(255, 255, 0), GREEN(0, 255, 0);
    private int redValue;
    private int greenValue;
    private int blueValue;

    Color(int redValue, int greenValue, int blueValue) {
        this.redValue = redValue;
        this.greenValue = greenValue;
        this.blueValue = blueValue;
    }

    @Override
    public void show() {
        System.out.println("The attribute value is" + redValue + "," + greenValue + "," + blueValue);
    }
}

2. Abnormal

1. Concept of exception

In the Java language, abnormal conditions during program execution are called "exceptions". (syntax errors and logic errors in the development process are not exceptions)

Abnormal events during execution can be divided into two categories

  • Error: a serious problem that the Java virtual machine cannot solve.
  • Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example, null pointer access, trying to read non-existent files, network connection interruption, etc...
    • Runtime exception [an exception that occurs when a program is running]
    • Compile time exception [exception detected by compiler during programming]

2. Exception handling

  • Try catch - finally, the programmer catches the exceptions in the code and handles them by himself
  • throws: throw the exception to the caller (method) for processing. The top handler is the JVM
  • Try catch: multiple catch statements can be used to catch different exceptions. It is required that the parent exception is in the back and the child exception is in the front
  • Try finally: the program will crash directly if no exception is caught
public class TryCatchDetail {
    public static void main(String[] args) {

        //Lao Han's interpretation
        //1. If an exception occurs, the code after the exception will not be executed and directly enters the catch block
        //2. If the exception does not occur, the code blocks of try will be executed sequentially and will not enter the catch
        //3. If you want to execute a piece of code (such as closing a connection, releasing resources, etc.) regardless of whether an exception occurs or not, use the following code - finally
        try {
            String str = "oracle ";
            int a = Integer.parseInt(str);
            System.out.println("Number:" + a);
        } catch (NumberFormatException e) {
            System.out.println("Abnormal information=" + e.getMessage());
        } finally {
            System.out.println("finally Code blocks are executed...");
        }

        System.out.println("The program continues...");

    }
}
class ExceptionExe01 {
    public static int method() {
        int i = 1;//i = 1
        try {
            i++;// i=2
            String[] names = new String[3];
            if (names[1].equals("tom")) { //Null pointer
                System.out.println(names[1]);
            } else {
                names[3] = "hspedu";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            return 2;
        } catch (NullPointerException e) {
            return ++i;  // I = 3 = > Save temporary variable temp = 3;
        } finally {
            ++i; //i = 4
            System.out.println("i=" + i);// i = 4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());// 3
    }
}

3. throws exception handling

1. Basic introduction

  • If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to handle this exception, the method should explicitly declare to throw an exception, indicating that the method will not handle these exceptions, but the caller of the method is responsible for handling them.
  • In the method declaration, the throw statement can be used to declare the list of exceptions thrown. The exception type after throws can be the exception type generated in the method or its parent class.

2. Precautions

  • For compilation exceptions, they must be handled in the program, such as try catch or throws

  • For runtime exceptions, if they are not handled in the program, they are handled by throws by default

  • When a subclass overrides a method of a parent class, the rules for throwing exceptions: for a method overridden by a subclass, the type of exception thrown is either the same as the exception thrown by the parent class, or it is a subtype of the type of exception thrown by the parent class

  • In the process of throws, if there is a method try catch, it is equivalent to handling exceptions, so you don't have to throw

public class ThrowsDetail {
    public static void main(String[] args) {
        f2();
    }

    public static void f2() /*throws ArithmeticException*/ {
        //1. Compile exceptions must be handled in the program, such as try catch or throws
        //2. For runtime exceptions, if they are not handled in the program, they are handled by throws by default

        int n1 = 10;
        int n2 = 0;
        double res = n1 / n2;
    }

    public static void f1() throws FileNotFoundException {
        //Here you can think about the problem and call f3() to report an error
        //Lao Han's interpretation
        //1. Because the f3() method throws a compilation exception
        //2. At this time, f1() must handle this compilation exception
        //3. In f1(), either try catch finally or continue to throw the compilation exception
        f3(); // Throw exception
    }
    public static void f3() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("d://aa.txt");
    }

    public static void f4() {
        //Lao Han's interpretation:
        //1. calling method f5() in f4() is OK.
        //2. The reason is that f5() throws an operation exception
        //3. In java, programmers are not required to display processing, because there is a default processing mechanism
        f5();
    }
    public static void f5() throws ArithmeticException {

    }
}

class Father { //Parent class
    public void method() throws RuntimeException {
    }
}

class Son extends Father {//Subclass
    //3. When the subclass overrides the method of the parent class, the provisions on throwing exceptions: the method overridden by the subclass,
    //   The exception type thrown is either the same as the exception thrown by the parent class or a subtype of the exception type thrown by the parent class
    //4. In the process of throws, if there is a method try catch, it is equivalent to handling exceptions, so you don't have to throw
    @Override
    public void method() throws ArithmeticException {
    }
}

4. Custom exception

public class CustomException {
    public static void main(String[] args) /*throws AgeException*/ {

        int age = 180;
        //The range is required to be between 18 – 120, otherwise a custom exception will be thrown
        if(!(age >= 18 && age <= 120)) {
            //Here we can set the information through the constructor
            throw new AgeException("The age needs to be 18~120 between");
        }
        System.out.println("Your age range is correct.");
    }
}
//Customize an exception
//Lao Han's interpretation
//1. In general, our custom exception inherits RuntimeException
//2. That is to say, we can make the custom exception into a runtime exception. For the benefit, we can use the default processing mechanism
//3. It is more convenient
class AgeException extends RuntimeException {
    public AgeException(String message) {//constructor 
        super(message);
    }
}

5. The difference between throw and throws

significancepositionWhat follows
throwsA way of exception handlingMethod declaration OfficeException type
throwKeywords for manually generating exception objectsMethod bodyException object
public class ThrowException {
    public static void main(String[] args) {
        try {
            ReturnExceptionDemo.methodA();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        ReturnExceptionDemo.methodB();

    }
}

class ReturnExceptionDemo {
    static void methodA() {
        try {
            System.out.println("Entry method A");
            throw new RuntimeException("Manufacturing exception");
        } finally {
            System.out.println("use A Methodical finally");
        }
    }

    static void methodB() {
        try {
            System.out.println("Entry method B");
            return;
        } finally {
            System.out.println("call B Methodical finally");
        }
    }
}

/*
* Enter method A
* finally with method A
* Manufacturing exception
* Enter method B
* finally calling the B method
* */

3. Common class

1. Packaging

1. Wrapper class and basic data type conversion

  • Manual packing and unpacking before jdk5, packing: basic type - > packing type, otherwise, unpacking
  • Automatic packing and unpacking after jdk5 (including jdk5)
  • The underlying call of auto boxing is the valueof method, such as integer valueOf()
public class WrapperExercise02 {
    public static void main(String[] args) {
        Integer i = new Integer(1);
        Integer j = new Integer(1);
        System.out.println(i == j);  //False
        //Therefore, we mainly look at the range - 128 ~ 127, which is a direct return
        /*
        Lao Han's interpretation
        //1. If i is in integercache low(-128)~IntegerCache. High (127) is returned directly from the array
        //2. If it is not - 128 ~ 127, directly new Integer(i)
         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); ->  Read source code
        Integer n = 1;//Underlying integer valueOf(1);
        System.out.println(m == n); //T
        //Therefore, we mainly look at the range - 128 ~ 127, which is a direct return
        //, otherwise, new Integer(xx);
        Integer x = 128;//Underlying integer valueOf(128);
        Integer y = 128;//Underlying integer valueOf(128);
        System.out.println(x == y);//False
    }
}

public class WrapperExercise03 {
    public static void main(String[] args) {
        //Example 1
        Integer i1 = new Integer(127);
        Integer i2 = new Integer(127);
        System.out.println(i1 == i2);//F
		//Example 2
        Integer i3 = new Integer(128);
        Integer i4 = new Integer(128);
        System.out.println(i3 == i4);//F

		//Example 3
        Integer i5 = 127;//Underlying integer valueOf(127)
        Integer i6 = 127;//-128~127
        System.out.println(i5 == i6); //T
		//Example 4
        Integer i7 = 128;
        Integer i8 = 128;
        System.out.println(i7 == i8);//F
		//Example 5
        Integer i9 = 127; //Integer.valueOf(127)
        Integer i10 = new Integer(127);
        System.out.println(i9 == i10);//F

        //Example 6
        Integer i11=127;
        int i12=127;
		//As long as there is a basic data type, the judgment is
		//Are the values the same
        System.out.println(i11==i12); //T
		//Example 7
        Integer i13=128;
        int i14=128;
        System.out.println(i13==i14);//T
    }
}

2. String class

1. Brief introduction

public class String01 {
    public static void main(String[] args) {
        //1. The string object is used to save a string, that is, a set of character sequences
        //2. "jack" string constant, a character sequence enclosed in double quotation marks
        //3. The characters of the string are encoded by Unicode characters. One character (regardless of letters or Chinese characters) occupies two bytes
        //4. The string class has many constructors, which are overloaded
        //   Commonly used are string S1 = new string()//
        //String  s2 = new String(String original);
        //String  s3 = new String(char[] a);
        //String  s4 =  new String(char[] a,int startIndex,int count)
        //String s5 = new String(byte[] b)
        //5. The String class implements the interface Serializable [String can be serialized: it can be transmitted over the network]
        //                 Interface Comparable [String object can compare size]
        //6. String is a final class and cannot be inherited by other classes
        //7. String has the attribute private final char value []; Used to store string contents
        //8. It must be noted that value is a final type and cannot be modified (requires skill): that is, value cannot point to
        //   New address, but the content of a single character can be changed
        String name = "jack";
        name = "tom";
        final char[] value = {'a','b','c'};
        char[] v2 = {'t','o','m'};
        value[0] = 'H';
        //value = v2;  The value address cannot be modified
    }
}

2. Comparison of two methods of creating objects

  • Method 1: directly assign String s = "hsp";
  • Method 2: call the constructor String s2 = new String("hsp");

analysis

  • Method 1: 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

  • Method 2: first create a space in the heap, which maintains the value attribute and 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. Finally, it points to the spatial address in the heap.

  • Memory step by step diagram

Knowledge points

  • When calling the intern method, if the pool already contains a String equal to this String object (determined by the eguals(Object. Method), the String in the pool is returned. Otherwise, add this String object to the pool and return a reference to this String object
  • b. The intern () method finally returns the address (object) of the constant pool

3. Interview questions

  • String is a final class that represents an immutable character sequence
  • The string is immutable. A string object is allocated and its contents are immutable
The following statement creates several objects?
    String s1 = "hello";
	s1="haha"; 
	//2 objects created
String a = "hello" + "abc";
//How many objects were created? Only 1 object
//Interpretation: string a = "hello" + "ABC"; / / = = > Optimize equivalence String a = "helloabc";

//analysis
//1. The compiler is not stupid. Make an optimization to determine whether the created constant pool object has a reference point
//2. Stringa = "hello"+ "abc"; =>String a = "helloabc";
public class StringExercise08 {
    public static void main(String[] args) {
        String a = "hello"; //Create a object
        String b = "abc";//Create b object
        //Lao Han's interpretation
        //1. First create a StringBuilder sb = StringBuilder()
        //2. Execute sb append("hello");
        //3. sb.append("abc");
        //4. String c= sb.toString()
        //Finally, c actually points to the object in the heap (string) value [] - > the "helloabc" in the pool
        String c = a + b;
        String d = "helloabc";
        System.out.println(c == d);//True or false? Is false
        String e = "hello" + "abc";//Look directly at the pool, e pointing to the constant pool
        System.out.println(d == e);//True or false? Is true
    }
}
String a = "hello"; //Create a object
String b ="abc";//Create b object
String c=a+ b;//How many objects were created?
//-There are 3 objects in total
//analysis
//Lao Han's summary: the bottom layer is StringBuilder sb = new StringBuilder(); sb.append(a);sb.append(b); sb is in the heap, and append is appended to the original string
//Important rules, Stringc1 = "ab" + "cd"; Constant addition, looking at the pool. Stringc1 = a + b ; Variables are added in the heap
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';
    }

    public static void main(String[] args) {
        Test1 ex = new Test1();
        ex.change(ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.println(ex.ch);    //Answer: hsp and hava
    }
}

4. Common methods in String

public class StringMethod01 {
    public static void main(String[] args) {
        //1. equals has been mentioned earlier Compare whether the contents are the same, case sensitive
        String str1 = "hello";
        String str2 = "Hello";
        System.out.println(str1.equals(str2));//

        // 2.equalsIgnoreCase ignores case to judge whether the contents are equal
        String username = "johN";
        if ("john".equalsIgnoreCase(username)) {
            System.out.println("Success!");
        } else {
            System.out.println("Failure!");
        }
        // 3.length gets the number of characters and the length of the string
        System.out.println("oracle ".length());
        // 4.indexOf gets the index of the first occurrence of the character in the string object. The index starts from 0. If it is not found, it returns - 1
        String s1 = "wer@terwe@g";
        int index = s1.indexOf('@');
        System.out.println(index);// 3
        System.out.println("weIndex=" + s1.indexOf("we"));//0
        // 5.lastIndexOf gets the index of the last occurrence of the character in the string. The index starts from 0. If it is not found, it returns - 1
        s1 = "wer@terwe@g@";
        index = s1.lastIndexOf('@');
        System.out.println(index);//11
        System.out.println("ter Location of=" + s1.lastIndexOf("ter"));//4
        // 6.substring intercepts substrings in the specified range
        String name = "hello,Zhang San";
        //Below is name Substring (6) intercepts all subsequent contents from index 6
        System.out.println(name.substring(6));//Intercept the following characters
        //name.substring(0,5) means to intercept from index 0 to index 5-1 = 4
        System.out.println(name.substring(2,5));//llo
    }
}
public class StringMethod02 {
    public static void main(String[] args) {
        // 1. Convert touppercase to uppercase
        String s = "heLLo";
        System.out.println(s.toUpperCase());//HELLO
        // 2.toLowerCase
        System.out.println(s.toLowerCase());//hello
        // 3.concat splice string
        String s1 = "Baoyu";
        s1 = s1.concat("Lin Daiyu").concat("Xue Baochai").concat("together");
        System.out.println(s1);//Baoyu Lin Daiyu Xue Baochai together
        // 4.replace replace characters in string
        s1 = "Baoyu and Lin Daiyu Lin Daiyu Lin Daiyu";
        //In s1, replace all Lin Daiyu with Xue Baochai
        // Lao Han's interpretation: S1 After the replace () method is executed, the returned result is replaced
        // Note that there is no effect on s1
        String s11 = s1.replace("Baoyu", "jack");
        System.out.println(s1);//Baoyu and Lin Daiyu Lin Daiyu Lin Daiyu
        System.out.println(s11);//jack and Lin Daiyu Lin Daiyu Lin Daiyu
        // 5.split split split string. For some split characters, we need to escape, such as \ \
        String poem = "Hoe standing grain gradually pawning a midday,Sweat drops under the grass,Who knows Chinese food,Every single grain is the fruit of hard work.";
        //Lao Han's interpretation:
        // 1. Divide the poem based on the, and return an array
        // 2. When splitting a string, if there are special characters, you need to add an escape character\
        String[] split = poem.split(",");
        poem = "E:\\aaa\\bbb";
        split = poem.split("\\\\");
        System.out.println("==Split content===");
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
        }
        // 6.toCharArray to character array
        s = "happy";
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            System.out.println(chs[i]);
        }
        // 7.compareTo 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's interpretation
        // (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
        //     If (C1! = C2) is returned{
        //                return c1 - c2;
        //            }
        // (3) If the previous parts are the same, STR1. 0 is returned len - str2. len
        String a = "jcck";// len = 3
        String b = "jack";// len = 4
        System.out.println(a.compareTo(b)); // The return value is the value of 'c' - 'a' = 2
// 8.format string
        /* Placeholders are:
         * %s String% c character% d integer%. 2f floating point
         *
         */
        String name = "john";
        int age = 10;
        double score = 56.857;
        char gender = 'male';
        //Splice all the information into a string
        String info =
                "My name is" + name + "Age is" + age + ",The result is" + score + "Gender is" + gender + ". I hope you like me!";

        System.out.println(info);
        
        //Lao Han's interpretation
        //1.% s,% D,%. 2F,% C are called placeholders
        //2. These placeholders are replaced by the following variables
        //3.% s indicates that it is replaced by a string
        //4.% d is an integer to replace
        //5.%. 2F means to replace with decimal. After replacement, only two decimal places will be reserved and rounded
        //6.%c replace with char type
        String formatStr = "My name is%s Age is%d,The result is%.2f Gender is%c.I hope you like me!";

        String info2 = String.format(formatStr, name, age, score, gender);

        System.out.println("info2=" + info2);
    }
}

3. StringBuffer class

1. Basic introduction

  • java.lang StringBuffer represents a variable character sequence. You can add or delete string contents.
  • Many methods are the same as String, but StringBuffer is of variable length.
  • StringBuffer is a container.

2,String VS StringBuffer

  • String saves string constants, and the values in them cannot be changed. Each update of string class actually changes the address, which is inefficient / / private final char value [];
  • StringBuffer saves string variables. The values in it can be changed every time; The update of StringBuffer can actually update the content without updating the address every time, which is more efficient / / char[] value/ Put this in the pile
public class StringBuffer01 {
    public static void main(String[] args) {
        //Lao Han's interpretation
        //1. The direct parent class of StringBuffer is AbstractStringBuilder
        //2. StringBuffer implements Serializable, that is, the objects of StringBuffer can be serialized
        //3. AbstractStringBuilder has the attribute char[] value in the parent class, not final
        //   The value array stores the string contents and leads out the values stored in the heap
        //4. StringBuffer is a final class and cannot be inherited
        //5. Because the StringBuffer character content has char[] value, all are changing (add / delete)
        //   It is not necessary to change the address every time (that is, it is not necessary to create a new object every time), so the efficiency is higher than that of String
        StringBuffer stringBuffer = new StringBuffer("hello");
    }
}
public class StringBuffer02 {
    public static void main(String[] args) {
        //Use of constructors
        //1. Create a char [] with a size of 16 to store character content
        StringBuffer stringBuffer = new StringBuffer();
        //2 specify char [] size through constructor
        StringBuffer stringBuffer1 = new StringBuffer(100);
        //3. By creating a StringBuffer for a String, the size of char [] is str.length() + 16
        StringBuffer hello = new StringBuffer("hello");

    }
}

3,String —> StringBuffer

public class StringAndStringBuffer {
    public static void main(String[] args) {

        //See String - > StringBuffer
        String str = "hello tom";
        //Mode 1 using constructors
        //Note: the returned string buffer object has no effect on str itself
        StringBuffer stringBuffer = new StringBuffer(str);
        //Method 2 uses the append method
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1 = stringBuffer1.append(str);

        //Look at StringBuffer - > string
        StringBuffer stringBuffer3 = new StringBuffer("Han Shunping Education");
        //Method 1: use the toString method provided by StringBuffer
        String s = stringBuffer3.toString();
        //Method 2: use the constructor to do it
        String s1 = new String(stringBuffer3);
    }
}

4. Question

public class StringBufferExercise01 {
    public static void main(String[] args) {
        String str = null;// ok
        StringBuffer sb = new StringBuffer(); //ok
        sb.append(str);
        //Depending on the source code, the bottom layer calls the appendNull of AbstractStringBuilder
        /**
         * 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;
         *     }
         */
        System.out.println(sb.length());//4

        System.out.println(sb);//null
        //The following constructor will throw NullpointerException
        StringBuffer sb1 = new StringBuffer(str);//Look at the underlying source code super(str.length() + 16);
        System.out.println(sb1);
    }
}

4. StringBuilder class

1. Basic introduction

  • 1) A variable character sequence. This class provides an API compatible with StringBuffer, but does not guarantee synchronization (StringBuilder is not thread safe). This class is designed as a simple alternative to StringBuffer when the string buffer is used by a single thread. If possible, it is recommended that this class be preferred because it is faster than StringBuffer in most implementations.
  • The main operations on StringBuilder are append and insert methods, which can be overloaded to accept any type of data.
  • Both StringBuilder and StringBuffer represent variable character sequences in the same way, so they are used in the same way as StringBuffer

1.StringBuilder is final
2. It inherits AbstractStringBuilder, attribute char[] value, and the content is saved to value
3. Implement the Serializable interface, serialization (the so-called serialization can save the type and data itself)

public class StringBuilder01 {
    public static void main(String[] args) {
        //Lao Han's interpretation
        //1. StringBuilder inherits AbstractStringBuilder class
        //2. Serializable is implemented, which shows that the StringBuilder object can be serialized (the object can be transmitted over the network and saved to a file)
        //3. StringBuilder is a final class and cannot be inherited
        //4. The character sequence of the StringBuilder object is still the char[] value stored in its parent class AbstractStringBuilder;
        //   Therefore, the character sequence is in the heap
        //5. The StringBuilder method is not mutually exclusive, that is, there is no synchronized keyword, so it is used in the case of single thread
        //   StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
    }
}

5. Comparison of String, StringBuffer and StringBuilder

  • StringBuilder is very similar to StringBuffer. Both represent variable character sequences, and the method is the same

  • String: immutable character sequence, low efficiency, but high reuse rate.

  • StringBuffer: variable character sequence, high efficiency (addition and deletion), thread safety, see the source code

  • StringBuilder: variable character sequence, most efficient, thread unsafe

  • Notes to String usage:

    • String s=“a”; // Created a string
    • s += “b”; // In fact, the original "a" string object has been discarded, and now a string s + "B" (that is, ab ") is generated. If these operations to change the string content are performed multiple times, a large number of duplicate string objects will be stored in memory, reducing efficiency. If such operations are put into the loop, the performance of the program will be greatly affected
    • Conclusion: if we make a lot of changes to String, don't use String
  • Selection of String, StringBuffer and StringBuilder

    • If there are a large number of modification operations on the string, - generally use StringBuffer or StringBuilder
    • If there are a lot of modification operations on the string, and in the case of single thread, use StringBuilder
    • If there are a lot of string modification operations, and in the case of multithreading, use StringBuffer
    • If our String is rarely modified and referenced by multiple objects, use String, such as configuration information

6. Math class

public class MathMethod {
    public static void main(String[] args) {
        //Take a look at Math's common methods (static methods)
        //1.abs absolute value
        int abs = Math.abs(-9);
        System.out.println(abs);//9
        //2.pow exponentiation
        double pow = Math.pow(2, 4);//Two to the fourth power
        System.out.println(pow);//16
        //3.ceil rounds up and returns > = the minimum integer of the parameter (converted to double);
        double ceil = Math.ceil(3.9);
        System.out.println(ceil);//4.0
        //4. The floor is rounded down and returns < = the maximum integer of the parameter (converted to double)
        double floor = Math.floor(4.001);
        System.out.println(floor);//4.0
        //5.round math Floor (this parameter + 0.5)
        long round = Math.round(5.51);
        System.out.println(round);//6
        //6.sqrt calculation
        double sqrt = Math.sqrt(9.0);
        System.out.println(sqrt);//3.0

        //7.random number
        //  Random returns a random decimal between 0 < = x < 1
        // Think: please write a random integer between a and B. A and B are integers, such as a = 2 and B = 7
        //  That is, a number x 2 < = x < = 7 is returned
        // Lao Han interprets math Random() * (B-A) returns 0 < = number < = b-a
        // (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
        // (2) Use specific numbers to introduce a = 2 and B = 7 to small partners
        //  (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
        //  Math.random()*6 returns 0 < = x < 6 decimals
        //  2 + Math.random()*6 returns 2 < = x < 8 decimals
        //  (int)(2 + Math.random()*6) = 2 <= x <= 7
        // (3) The formula is (int)(a + Math.random() * (b-a +1))
        for(int i = 0; i < 100; i++) {
            System.out.println((int)(2 +  Math.random() * (7 - 2 + 1)));
        }

        //Max, min returns the maximum and minimum values
        int min = Math.min(1, 9);
        int max = Math.max(45, 90);
        System.out.println("min=" + min);
        System.out.println("max=" + max);

    }
}

7. Arrays class

public class ArraysMethod01 {
    public static void main(String[] args) {

        Integer[] integers = {1, 20, 90};
        //Traversal array
//        for(int i = 0; i < integers.length; i++) {
//            System.out.println(integers[i]);
//        }
        //Directly use arrays ToString method, display array
//        System.out.println(Arrays.toString(integers));//

        //Demonstrate the use of sort method

        Integer arr[] = {1, -1, 7, 0, 89};
        //Sort
        //Lao Han's interpretation
        //1. You can directly use bubble sorting or sort method provided by Arrays
        //2. Because the array is a reference type, sorting through sort will directly affect the actual parameter arr
        //3. If sort is overloaded, you can also pass in an interface Comparator to realize customized sorting
        //4. When calling custom sorting, pass in the array arr sorted by two parameters (1)
        //   (2) The anonymous internal class of Comparator interface is implemented, and the compare method is required to be implemented
        //5. Demonstrate the effect before explaining
        //6. This shows the way of interface programming. Just look at the source code
        //   Source code analysis
        //(1) Arrays.sort(arr, new Comparator()
        //(2) Finally, go to private static < T > void binarysort of TimSort class (t [] A, int lo, int Hi, int start,
        //                                       Comparator<? super T> c)()
        //(3) The code executed to the binarySort method will execute the code we passed in according to the dynamic binding mechanism c.compare()
        //    compare() of anonymous inner class
        //     while (left < right) {
        //                int mid = (left + right) >>> 1;
        //                if (c.compare(pivot, a[mid]) < 0)
        //                    right = mid;
        //                else
        //                    left = mid + 1;
        //            }
        //(4) new Comparator() {
        //            @Override
        //            public int compare(Object o1, Object o2) {
        //                Integer i1 = (Integer) o1;
        //                Integer i2 = (Integer) o2;
        //                return i2 - i1;
        //            }
        //        }
        //(5) Is the value returned by public int compare (object O1, object O2) > 0 or < 0
        //    It will affect the whole sorting result, which fully reflects the comprehensive use of interface programming + dynamic binding + anonymous internal classes
        //    In the future, the use of the underlying framework and source code will be very common
        //Arrays.sort(arr); //  Default sort method
        //Custom sorting
        Arrays.sort(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2 - i1;
            }
        });
        System.out.println("===After sorting===");
        System.out.println(Arrays.toString(arr));//
    }
}

public class ArraysMethod02 {
    public static void main(String[] args) {
        Integer[] arr = {1, 2, 90, 123, 567};
        // binarySearch searches through binary search method, which requires that it must be arranged well
        // Lao Han's interpretation
        //1. Binary search using binarySearch
        //2. The array is required to be ordered If the array is unordered, binarySearch cannot be used
        //3. If the element does not exist in the array, return - (low + 1)// key not found.
        int index = Arrays.binarySearch(arr, 567);
        System.out.println("index=" + index);

        //Copy of array elements
        // Lao Han's interpretation
        //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 uses system arraycopy()
        Integer[] newArr = Arrays.copyOf(arr, arr.length);
        System.out.println("==After copy execution==");
        System.out.println(Arrays.toString(newArr));

        //Fill of ill array elements
        Integer[] num = new Integer[]{9,3,2};
        //Lao Han's interpretation
        //1. Using 99 to fill the num array can be understood as an element of the replacement principle
        Arrays.fill(num, 99);
        System.out.println("==num After array filling==");
        System.out.println(Arrays.toString(num));

        //equals compares whether the contents of two array elements are exactly the same
        Integer[] arr2 = {1, 2, 90, 123};
        //Lao Han's interpretation
        //1. If the elements of arr and arr2 arrays are the same, the method is true;
        //2. If it is not exactly the same, return false
        boolean equals = Arrays.equals(arr, arr2);
        System.out.println("equals=" + equals);

        //asList converts a set of values into a list
        //Lao Han's interpretation
        //1. asList method will convert (2,3,4,5,6,1) data into a List set
        //2. The returned asList compilation type is list (Interface)
        //3. asList run type Java util. Arrays #arraylist is the name of the arrays class
        //   Static inner classprivate static class ArrayList < E > extends abstractlist < E >
        //              implements RandomAccess, java.io.Serializable
        List asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println("asList=" + asList);
        System.out.println("asList Type of operation" + asList.getClass());
    }
}

//Custom sorting

public class ArraysSortCustom {
    public static void main(String[] args) {

        int[] arr = {1, -1, 8, 0, 20};
        //bubble01(arr);

        bubble02(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int i1 = (Integer) o1;
                int i2 = (Integer) o2;
                return i2 - i1;// return i2 - i1;
            }
        });

        System.out.println("==Customized sorting==");
        System.out.println(Arrays.toString(arr));

    }

    //Use bubble to complete sorting
    public static void bubble01(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                //from small to large
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    //Combined bubbling + customization
    public static void bubble02(int[] arr, Comparator c) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                //Array sorting is determined by the value returned by c.compare(arr[j], arr[j + 1])
                if (c.compare(arr[j], arr[j + 1]) > 0) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

8. System class

  • Exit exit the current program
  • arraycopy: copy array elements, which is more suitable for bottom-level calls. Generally, arrays Copyof completes copying the array
  • current TimeMillens: returns the number of milliseconds from 1970-1-1 in the current time
  • GC: run garbage collection system gc);
public class System_ {
    public static void main(String[] args) {

        //Exit exit the current program

//        System.out.println("ok1");
//        //Lao Han's interpretation
//        //1. exit(0) indicates that the program exits
//        //2.  0 indicates a state, normal state
//        System.exit(0);//
//        System.out.println("ok2");

        //arraycopy: copy array elements, which is more suitable for underlying calls,
        // Generally use arrays Copyof completes copying the array

        int[] src={1,2,3};
        int[] dest = new int[3];// dest is currently {0,0,0}

        //Lao Han's interpretation
        //1. It is mainly to find out the meaning of these five parameters
        //2.
        //     Source array
        //     * @param      src      the source array.
        //     srcPos: which index position of the source array to copy from
        //     * @param      srcPos   starting position in the source array.
        //     dest: target array, that is, the array to which the data of the source array is copied
        //     * @param      dest     the destination array.
        //     destPos: which index of the target array to copy the data of the source array to
        //     * @param      destPos  starting position in the destination data.
        //     length: how many pieces of data are copied from the source array to the target array
        //     * @param      length   the number of array elements to be copied.
        System.arraycopy(src, 0, dest, 0, src.length);
        // int[] src={1,2,3};
        System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]

        //currentTimeMillens: returns the number of milliseconds from 1970-1-1 in the current time
        // Lao Han's interpretation:
        System.out.println(System.currentTimeMillis());
    }
}

9. BigInteger and BigDecimal classes

  • BigInteger is suitable for saving large integers
  • BigDecimal is suitable for saving floating-point type (decimal) with higher precision
public class BigInteger_ {
    public static void main(String[] args) {

        //When we program, we need to deal with large integers, and long is not enough
        //You can use the BigInteger class to do this
//        long l = 23788888899999999999999999999l;
//        System.out.println("l=" + l);

        BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
        BigInteger bigInteger2 = new BigInteger("10099999999999999999999999999999999999999999999999999999999999999999999999999999999");
        System.out.println(bigInteger);
        //Lao Han's interpretation
        //1. When adding, subtracting, multiplying and dividing BigInteger, you need to use the corresponding method, not directly + - */
        //2. You can create a BigInteger to operate, and then operate accordingly
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//
        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);//reduce
        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);//ride
        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);//except
    }
}

public class BigDecimal_ {
    public static void main(String[] args) {
        //When we need to save a number with high precision, double is not enough
        //It can be BigDecimal
//        double d = 1999.11111111111999999999999977788d;
//        System.out.println(d);
        BigDecimal bigDecimal = new BigDecimal("1999.11");
        BigDecimal bigDecimal2 = new BigDecimal("3");
        System.out.println(bigDecimal);

        //Lao Han's interpretation
        //1. If BigDecimal is operated, such as addition, subtraction, multiplication and division, the corresponding method needs to be used
        //2. create a BigDecimal that needs to be operated and then call the corresponding method.
        System.out.println(bigDecimal.add(bigDecimal2));
        System.out.println(bigDecimal.subtract(bigDecimal2));
        System.out.println(bigDecimal.multiply(bigDecimal2));
        //System.out.println(bigDecimal.divide(bigDecimal2));// An exception ArithmeticException may be thrown
        //When calling the divide method, specify the precision BigDecimal.ROUND_CEILING
        //If there is an infinite circular decimal, the precision of the numerator will be preserved
        System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
    }
}

10. Date class

1. First generation date class

    1. Date: accurate to milliseconds, representing a specific moment
    1. SimpleDateFormat: a class for formatting and parsing dates. SimpleDateFormat is a specific class for formatting and parsing dates. It allows formatting (date - > text), parsing (text - > date), and normalization
public class Date01 {
    public static void main(String[] args) throws ParseException {

        //Lao Han's interpretation
        //1. Get the current system time
        //2. The Date class here is in Java Util package
        //3. The default output date format is foreign, so it is usually necessary to convert the format
        Date d1 = new Date(); //Get current system time
        System.out.println("current date=" + d1);
        Date d2 = new Date(9234567); //Gets the time by specifying the number of milliseconds
        System.out.println("d2=" + d2); //Gets the number of milliseconds corresponding to a time
//

        //Lao Han's interpretation
        //1. Create a SimpleDateFormat object and specify the corresponding format
        //2. The letters used in the format here are well specified and can't be scribbled

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day hh:mm:ss E");
        String format = sdf.format(d1); // Format: converts the date to a string in the specified format
        System.out.println("current date=" + format);

        //Lao Han's interpretation
        //1. You can convert a formatted String to the corresponding Date
        //2. When the Date is still output, it is still in the foreign form. If you want to output in the specified format, it needs to be converted
        //3. The format of sdf used in String - > date should be the same as that of the String you gave, otherwise a conversion exception will be thrown
        String s = "1996 January 1, 2010:20:30 Monday";
        Date parse = sdf.parse(s);
        System.out.println("parse=" + sdf.format(parse));
    }
}

2. Second generation date class

  • Calendar class is an abstract class. It provides some methods for the conversion between a specific moment and a group of calendars such as YEAR, MONTH, DAY OF MONTH and HOUR, and provides some methods for operating calendar fields (such as obtaining the date of the next week).
public class Calendar_ {
    public static void main(String[] args) {
        //Lao Han's interpretation
        //1. Calendar is an abstract class, and the constructor is private
        //2. You can get the instance through getInstance()
        //3. Provide a large number of methods and fields to programmers
        //4. Calendar does not provide corresponding formatted classes, so programmers need to combine them to output (flexible)
        //5. If we need to obtain the time in 24-hour base, calendar Hour = = changed to = > calendar HOUR_ OF_ DAY
        Calendar c = Calendar.getInstance(); //Create a calendar class object / / it's simple and free
        System.out.println("c=" + c);
        //2. Get a calendar field of the calendar object
        System.out.println("Year:" + c.get(Calendar.YEAR));
        // Why do you want + 1 here? When Calendar returns the month, it starts with 0
        System.out.println("Month:" + (c.get(Calendar.MONTH) + 1));
        System.out.println("Date:" + c.get(Calendar.DAY_OF_MONTH));
        System.out.println("Hours:" + c.get(Calendar.HOUR));
        System.out.println("minute:" + c.get(Calendar.MINUTE));
        System.out.println("Seconds:" + c.get(Calendar.SECOND));
        //Calender has no special formatting method, so programmers need to combine the display themselves
        System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) +
                " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );

    }
}

3. Third generation date class

Analysis of the first two date classes

  • JDK 1.0 includes a Java util. Date class, but most of its methods have been deprecated since JDK 1.1 introduced the Calendar class. The problem with Calendar is:

  • 1) Variability: classes like 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) In addition, they are not thread safe; Cannot process leap seconds, etc. (1s more every 2 days)

Localdate, Localtime and localdatetime are added to JDK8

  • LocalDate only contains dates. You can get the date field
  • LocalTime only contains time. You can get the time field
  • LocalDateTime contains date + time. You can get the date and time fields
public class LocalDate_ {
    public static void main(String[] args) {
        //Third generation date
        //Lao Han's interpretation
        //1. Use now() to return an object representing the current date and time
        LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
        System.out.println(ldt);

        //2. Use DateTimeFormatter object to format
        // Create DateTimeFormatter object
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(ldt);
        System.out.println("Formatted date=" + format);

        System.out.println("year=" + ldt.getYear());
        System.out.println("month=" + ldt.getMonth());
        System.out.println("month=" + ldt.getMonthValue());
        System.out.println("day=" + ldt.getDayOfMonth());
        System.out.println("Time=" + ldt.getHour());
        System.out.println("branch=" + ldt.getMinute());
        System.out.println("second=" + ldt.getSecond());

        LocalDate now = LocalDate.now(); //You can get the date
        LocalTime now2 = LocalTime.now();//Get time to minute and second


        //plus and minus methods are provided to add or subtract the current time
        //Look at 890 days later, when is the year, day, hour, minute and second
        LocalDateTime localDateTime = ldt.plusDays(890);
        System.out.println("890 Days later=" + dateTimeFormatter.format(localDateTime));

        //See what time it was 3456 minutes ago and output the year, month, day, hour, minute and second
        LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
        System.out.println("3456 Date minutes ago=" + dateTimeFormatter.format(localDateTime2));

    }
}

Topics: JavaSE