Quick learning of Java syntax - dark horse programmer (personal finishing version)

Introduction to java basic video tutorial, zero foundation self-study of Java, preferred introduction to Java for dark horse programmers (including Java projects and Java real problems)_ Beep beep beep_ bilibili in order to help the majority of zero foundation students who are interested in Java and are determined to enter the industry, this set of courses came into being. It abandoned the lengthy theory and combined with the real application needs of software companies to strengthen everyone's understanding and mastery of knowledge. The knowledge of this course is comprehensive and thorough, and the cases are extremely rich. After the completion of this stage of the course, it is equipped with comprehensive practical cases, with a large number of elegant and high-quality codes for beginners to train. It is clear and practical to learn and work hand in hand! It is an excellent introductory video for Java zero foundation students. The course covers the introduction of Java language, the principle of program development and execution, and the design of integrated development tool IDEAhttps://www.bilibili.com/video/BV1Cv411372m?p=128

This article is P1-P127, and the following contents are not learned because the project is temporarily unavailable

Java hierarchy

Basic format

package com.itheima.test;    //Package name: generally written backwards for the company's website

public class Test {    //Class name: Test
}

main function

main plus tab

package com.itheima.test;

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

    }
}

Output statement

System.out.println();
package com.itheima.test;

public class Test {
    public static void main(String[] args) {
        System.out.println("HelloWorld");
    }
}

notes

Single line note

//Single-Line Comments 
package com.itheima.note;

public class NoteDemo {
    public static void main(String[] args) {
        //Single-Line Comments 
    }
}

multiline comment

/*
    Note content 1
    Note content 2
*/
package com.itheima.note;

public class NoteDemo {
    public static void main(String[] args) {
        /*
            Note content 1
            Note content 2
        */
    }
}

Document comments: the contents of document comments can be extracted into a program description document

/**
    Documentation Comments 
*/
package com.itheima.note;
/**
    Documentation Comments 
*/

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

variable

int a=10;
double b=2.0;
float c=3.0;

input

import java.util.Scanner;
        Scanner sc=new Scanner(System.in);
        int age =sc.nextInt();
        String name =sc.next();
package com.itheima.scanner;

import java.util.Scanner;

// 1. Package guide operation (it doesn't need to be written by yourself, but can be imported by tools later)
public class ScannerDemo {
    public static void main(String[] args) {
        //2. Get a keyboard scanning object
        Scanner sc=new Scanner(System.in);
        //3. Call the function of sc object and wait for the data entered by the user
        //This code will wait for the user to enter the data until the user enters the data and presses the Enter key to get the data
        System.out.println("Please enter your age:");
        int age =sc.nextInt();
        System.out.println("Your age is:"+age);

        System.out.println("Please enter your name:");
        String name =sc.next();
        System.out.println("welcome:"+name);
    }
}

if

if (Conditional expression) {

    Statement body; 

}
if (Conditional expression) {
    Statement body 1;	
} else {
    Statement body 2;	
}
if (Conditional expression 1) {
    Statement body 1;	
} else if (Conditional expression 2) {
    Statement body 2;	
} else if (Conditional expression 3) {
    Statement body 3;	
} 
. . .
else {
    Statement body n+1;
}

switch

switch(expression){
    case Value 1:
        Execute code 1;
        break;
    case Value 2:
        Execute code 2;
        break;
    ...
    default:
        Execute code n;
        //break;

for loop

for (Initialization statement; Cycle condition; Iterative statement)  {	Loop body statement(Repeatedly executed code);
}
// Output HelloWorld 3 times
for (int i = 0; i < 3; i++) {   
    System.out.println("Hello World");
}

while Loop

Initialization statement;
while (Cycle condition) {
    Loop body statement(Repeatedly executed code);
    Iterative statement;
}
int i = 0;
while (i < 3) {
    System.out.println("Hello World");
    i++;
}

do-while Loop

Initialization statement;
do {
    Loop body statement;
    Iterative statement;
} while (Cycle condition);
int i = 0;
do {
       System.out.println("Hello World!");
       i++;
} while( i < 3);

Dead cycle

for(;;){
}
while(true){
}
do{
}while(true);

Random number

import java.util.Random;
        Random r = new Random();
        int data = r.nextInt(10); // 0 - 9 does not contain 10 (before package, not after package)
package com.itheima.random;

import java.util.Random;

public class RandomDemo1 {
    public static void main(String[] args) {
        // Objective: learn to use the Random number class Random provided by Java
        // 1. Guide Package
        // 2. Create random number object
        Random r = new Random();

        // 3. Calling the nextInt function (method) can return an integer random number to you
        for (int i = 0; i < 20; i++) {
            int data = r.nextInt(10); // 0 - 9 does not contain 10 (before package, not after package)
            System.out.println(data);
        }

        System.out.println("-----------------------");
        // 1 - 10 ==> -1 ==> (0 - 9) + 1
        int data = r.nextInt(10) + 1;
        System.out.println(data);

        // 3 - 17 ==> -3 ==> (0 - 14) + 3
        int data1 = r.nextInt(15) + 3;
        System.out.println(data1);
    }
}

array

// Full format
 data type[]  Array name = new data type[]{Element 1, element 2, element 3 };
double[] scores = new double[]{89.9, 99.5, 59.5, 88.0};
int[] ages = new int[]{12, 24, 36}
// Simplified format
 data type[] Array name = { Element 1, element 2, element 3 };
int[] ages = {12, 24, 36};

"Data type [] array name" can also be written as "data type array name []"

int[] ages =...;  
int ages[] =...;  

double[] scores = ...;
double scores[] = ...;

Access to arrays

// Value
System.out.println(arr[0]); // 12
// assignment
arr[2] = 100;
System.out.println(arr[2]); // 100

Length attribute of array: length

// Get the length of the array (that is, the number of array elements)
System.out.println(arr.length); // 3

Dynamic initialization of array

data type[]  Array name = new data type[length];
int[] arr = new int[3];//Create three new shaping spaces

Method (function)

Modifier return value type method name( parameter list  ){
         Method body code(Function code to be executed)
         return Return value;
}
public static int add(int a,int b){
    int c=a+b;
    return c;
}

Method call format

//Method name (...); 
int sum = add(10, 20);
System.out.println(sum);

Method overloading

public class Test {
    //(1) Default to send a weapon
    public static void fire(){
            System.out.println("Default to launch a weapon to the United States!");
    }

    //(2) A weapon can be fired from a designated area.
    public static void fire(String location){
        System.out.println("to"+location+"Launch a weapon!");
    }

    //(3) Multiple weapons can be fired in designated areas.
    public static void fire(String location , int nums){
        System.out.println("to"+location+"launch"+nums+"A weapon!");
    }
}

fire();
fire("United States");
fire("island country" , 1000);

object-oriented programming

Define the class to get the object

public class Class name{
    1,Member variables (representing attributes))
    2,Member method (representative behavior))
    3,constructor (Back learning)
    4,Code block(Back learning)
    5,Inner class(Back learning)
}
public class Car{
    String name;
    double price;
    
    public void start(){
        system.out.println(name+"It's on! ");
    }
    public void run(){
        system.out.println("The selling price is:" + price +"of" +name+"Run fast! ");
    }
}

Get the object of the class

//Class name object name = new class name ();
Car c2 = new Car();

Use object

Object Member variables; Object Member method (...)

car.name;
car.price;
car.start();

constructor

public class Car {
    //Parameterless constructor (default)
}
public class Car {
    //Parameterless constructor (need to write it out)
    public Car(){
    }
    //Parametric structure
    public car(String n,String b){
    }
}

this keyword: the address of the current object

public class car {
    String name;
    double price;
    public car(string name , double price){
    this.name = name;
    this.price = price;
    }
}
public class car {
    String name;
    double price;
    public void gowith(String name){
    system.out.println(this.name +"And"+name +"Play together!!");
    }
}

Encapsulation: hide implementation details and expose appropriate access methods. (reasonable concealment and reasonable exposure)

public class Student {
    private int age;
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 0 && age <= 200) {
            this.age = age;
        }else {
            System.out.println("Please check the age value");
        }
    }
}

String string creation

String s1 = "abc" ;
String s2 = "abc" ;
System.out.println(s1 == s2); //true


char[] chs = {'a', 'b', 'c'};
string s3 = new String(chs);
String s4 = new String(chs);
System.out.println(s3 == s4); //false

Content comparison of string

It is recommended to use the "equals" comparison provided by the String class: only care about the same content

public boolean equals (Object anobject)

Compares this string with the specified object. Only care about whether the character content is consistent!

public boolean equalsIgnorecase (string anotherString)

Compares this string with the specified object, ignoring the case comparison string. Only care about whether the character content is consistent!

if(okName.equals(name ) && okPassword.equals(password)){
    System.out.println("Login succeeded!");
}else {
    System.out.println("Wrong user name or password!");
}

ArrayList collection

package com.itheima.arraylist;

import java.util.ArrayList;

/**
      Goal: create an ArrayList object to represent the collection container and add elements to it.
 */
public class ArrayListDemo1 {
    public static void main(String[] args) {
        // 1. Create an object for the ArrayList collection
        ArrayList list = new ArrayList();

        // 2. Add data
        list.add("Java");
        list.add("Java");
        list.add("MySQL");
        list.add("dark horse");
        list.add(23);
        list.add(23.5);
        list.add(false);
        System.out.println(list.add('in'));
        System.out.println(list);

        // 3. Inserts an element at the specified index location
        list.add(1, "Zhao Min");
        System.out.println(list);
    }
}

true
[Java, Java, MySQL, dark horse, 23, 23.5, false, medium]
[Java, Zhao Min, Java, MySQL, dark horse, 23, 23.5, false, medium]

ArrayList generic

//Using generics: < data type >
ArrayList<String> list1 = new ArrayList();//This collection can only manipulate elements of string type

Common methods of ArrayList collection

package com.itheima.arraylist;

import java.util.ArrayList;

/**
    Objective: to master the common API s of ArrayList collection
 */
public class ArrayListDemo3 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Java");
        list.add("MySQL");
        list.add("MyBatis");
        list.add("HTML");

        // 1. public E get(int index): get the element value at an index position
        String e = list.get(3);
        System.out.println(e);

        // 2. public int size(): get the size of the collection (number of elements)
        System.out.println(list.size());

        // 3. Complete the traversal of the collection
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

        // 4. public E remove(int index): deletes the element value at an index position and returns the deleted element value
        System.out.println(list); // [Java, Java, MySQL, MyBatis, HTML]
        String e2 = list.remove(2);
        System.out.println(e2);
        System.out.println(list);

        // 5. public boolean remove(Object o): directly delete the element value, return true if the deletion succeeds, and return false if the deletion fails
        System.out.println(list.remove("MyBatis"));
        System.out.println(list);

        ArrayList<String> list1 = new ArrayList<>();
        list1.add("Java");
        list1.add("Wang Baoqiang");
        list1.add("Java");
        list1.add("MySQL");
        System.out.println(list1);
        // Only the first occurrence of this element value will be deleted, and the subsequent ones will not be deleted
        System.out.println(list1.remove("Java"));
        System.out.println(list1);


        // 6. public E set(int index,E element): modify the element value at an index position.
        String e3 = list1.set(0 , "Jia Nailiang");
        System.out.println(e3);
        System.out.println(list1);


    }
}

MyBatis
5
Java
Java
MySQL
MyBatis
HTML
[Java, Java, MySQL, MyBatis, HTML]
MySQL
[Java, Java, MyBatis, HTML]
true
[Java, Java, HTML]
[Java, Wang Baoqiang, Java, MySQL]
true
[Wang Baoqiang, Java, MySQL]
Wang Baoqiang
[Jia Nailiang, Java, MySQL]

Static static

static can modify member variables and member methods.

Member variable

static modifies a member variable, which means that only one copy of the member variable is stored in memory and can be shared, accessed and modified.

public class User {
    // Member variable
    public static int onlineNumber= 161;
    
    private String name;
    private int age;
    ...
}

Recommended access method: class name Static member variable

User.onlineNumber

Member method

Static member methods (decorated with static and belonging to class) are recommended to be accessed by class name or object.

Instance member methods (without static decoration, belonging to objects) can only trigger access with objects.

package com.itheima.d2_static_method;

public class Student {
    private String name;
    private int age;

    /**
        Instance method: no static modification. It belongs to an object. It usually represents the object's own behavior and can access the object's member variables
     */
    public void study(){
        System.out.println(name + "Study hard and make progress every day~~");
    }

    /**
        Static method: decorated with static, it belongs to class and can be shared and accessed by class and object.
     */
    public static void getMax(int a, int b){
        System.out.println(a > b ? a : b);
    }

    public static void main(String[] args) {
        // 1. Class name Static method
        Student.getMax(10, 100);
        // Note: access to static members in the same class can omit the class name
        getMax(200, 20);

        // 2. Object Example method
        // study(); //  Error reporting
        Student s = new Student();
        s.name = "Whole egg";
        s.study();

        // 3. Object Static method (not recommended)
        s.getMax(300,20);
    }
}

Starving Han single case design mode

When using the class to get the object, the object has been created for you in advance

Design steps:

Define a class and make the constructor private

Define a static variable to store an object

/** a,Define a singleton class */
public class SingleInstance {
    /** c.Define a static variable to store an object: it belongs to a class and is loaded once with the class */
    public static SingleInstance instance = new SingleInstance ();

    /** b.Singleton must be a private constructor*/
    private SingleInstance (){
        System.out.println("Created an object");
    }
}

Lazy singleton design pattern

Create an object only when you really need it (delay loading object).

Design steps:

Define a class and make the constructor private

Define a static variable to store an object.

Provides a method that returns a singleton object

/** Define a singleton class */
class SingleInstance{
    /** Define a static variable to store an object: it belongs to a class and is loaded once with the class */
    public static SingleInstance instance ; // null

    /** Singleton must be a private constructor*/
    private SingleInstance(){}

    /** A method must be provided to return a singleton object  */
    public static SingleInstance getInstance(){
        ...
       return ...;
    }
}

inherit

Java provides a keyword extends. With this keyword, we can establish a parent-child relationship between one class and another.

Student s are called subclasses (derived classes), and People are called parent classes (base classes or superclasses)

public class Student extends People {}

① Subclasses can inherit the properties and behaviors of the parent class, but subclasses cannot inherit the constructor of the parent class.

② Java is a single inheritance mode: a class can only inherit one direct parent class.

③ Java does not support multi inheritance, but supports multi-layer inheritance.

④ All classes in Java are subclasses of the Object class.

Parent class file people java

package com.itheima.d7_extends;

public class People {
    private String name;
    private int age;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Subclass file student Java inheritance

package com.itheima.d7_extends;

public class Student extends People{
    /**
       Unique behavior
     */
    public void study(){
        System.out.println(getName() + "Students begin to learn~~~~~");
    }
}

test

package com.itheima.d7_extends;

public class Test {
    public static void main(String[] args) {
        // Create a subclass object to see if the properties and behavior of the parent class can be used
        Student s = new Student();
        s.setName("west gate"); // Parent class
        s.setAge(25);// Parent class
        System.out.println(s.getName());// Parent class
        System.out.println(s.getAge());// Parent class
        s.study();
    }
}

west gate
25
Simon students began to study~~~~~

super keyword: Specifies the member that accesses the parent class

keyword

Accessing member variables

Access member method

Access construction method

this

this. Member variable

Access the member variables of this class

this. Member method (...)

Access member methods of this class

this(...)

Accessing this class constructor

super

super. Member variable

Accessing parent class member variables

super. Member method (...)

Accessing parent class member methods

super(...)

Accessing the parent constructor

    public Student(String name, int age, String className) {
        super(name, age);
        this.className = className;
    }

this() accesses this class constructor

When creating object encapsulation data in the background, if the user does not enter the school, the "dark horse training center" is used by default. If the user enters a school, the school information entered by the user is used

public class Student {        
    private String schoolName;
    private String name;
   
    public Student(String name){
          this(name , ""Dark horse training center");	
    }	
     
    public Student(String name , String schoolName ){
          this.name = name;
          this.schoolName = schoolName;
    }	
}

package

Packages are used to manage different types by categories, similar to folders and packages, which is conducive to the management and maintenance of programs

The syntax format of Package Building: reverse the domain name of package company Technical name. It is suggested that all entries should be in lowercase and meaningful

The build package statement must be in the first line. General IDEA tools will help create it

package com.itheima.javabean;
public class Student {
       
}

Guide Package

Classes under the same package can be accessed directly. Classes under different packages must be imported before they can be used! Import package format: import package name Class name;

If different classes need to be used in a class, and the names of the two classes are the same, only one class can be imported by default, and the other class should be accessed with package name

package com.itheima.d1_package;


import com.itheima.d1_package.demo1.Animal;
import com.itheima.d1_package.demo1.Cat;

public class Test {
    public static void main(String[] args) {
        // Guided package: classes under the same package can be accessed directly.
        Student s = new Student();

        // Classes under different packages must be imported before they can be used
        Animal a = new Animal();

        // Class using the default import package: cat under demo1
        Cat c1 = new Cat();
        c1.run();

        // Specify the Cat class under demo2
        com.itheima.d1_package.demo2.Cat c2 = new  com.itheima.d1_package.demo2.Cat();
        c2.run();
    }
}

Permission modifier

Permission modifier: it is used to control the scope that a member can be accessed

Self defined members (methods, member variables, constructors, etc.) generally meet the following requirements:

  1. Member variables are generally private.
  2. Methods are generally open.
  3. If the member only wants this class to access, use the private modifier.
  4. If the member only wants this class and other classes and subclasses under the same package to access, use the protected modifier

Modifier

In the same class

In the same package

Other classes

Under different packages

Subclass

Under different packages

Irrelevant class

private

default

protected

public

package com.itheima.d2_modifier.itcast;

public class Fu {
    // 1.private can only be accessed in this class
    private void show1() {
        System.out.println("private");
    }

    // 2. Default: this class is in the class under the same package.
    void show2() {
        System.out.println("default");
    }

    // 3.protected: this class is the subclass of other packages in the class under the same package
    protected void show3() {
        System.out.println("protected");
    }

    // 4. Anywhere
    public void show4() {
        System.out.println("public");
    }

    public static void main(String[] args) {
        //Create Fu objects and test to see what methods can be used
        Fu f = new Fu();
        f.show1();
        f.show2();
        f.show3();
        f.show4();
    }
}

private
default
protected
public

Final final

Final keyword is the final meaning and can be modified (method, variable, class)

Modification method: indicates that this method is the final method and cannot be rewritten.

class Animal{
    public final void run(){
        System.out.println("Animals can run~~");
    }
}

class Tiger extends Animal{
//    @Override
//    public void run() {
//        System.out.println("the tiger runs fast ~ ~");
//    }
}

Modified variable: it means that the variable cannot be assigned again after the first assignment (if any, it can only be assigned once).

There are several variables:
   Local variables.
   Member variables.
        --1. Static member variables.
        --2. Instance member variables. final is basically not used to modify instance member variables, which is meaningless!
public static void main(String[] args) {
       // final modifies a variable, which has and can only be assigned once.
        final int age;
        age = 12;
        // age = 20; //  The second assignment is wrong!
}

Decorated class: indicates that this class is the final class and cannot be inherited.

final class Animal{
}
class Cat extends Animal{    //An error is reported. You cannot inherit the class decorated by final
}

Attention to final modifier variables

The variable modified by final is the basic type: the data value stored in the variable cannot be changed.

The variable modified by final is a reference type: the address value stored in the variable cannot be changed, but the content of the object pointed to by the address can be changed.

package com.itheima.d3_final;

public class Test2 {
    public static void main(String[] args) {
        // Precautions for final modification variables:
        // 1. final modifies a basic type variable whose data cannot be changed
        final double rate = 3.14;
        // rate = 3.15; //  Error is reported for the second assignment

        // 2. The final modifier refers to a variable of data type. The address stored in the variable cannot be changed, but the content of the object pointed to by the address can be changed.
        final int[] arr = {10, 20, 30};
        System.out.println(arr);
        // arr = null; //  For the second assignment, the address in arr cannot be changed
        arr[1] = 200;
        System.out.println(arr);
        System.out.println(arr[1]);
    }
}

constant

Constants are member variables decorated with public static final. They must have initialization values, and their values cannot be changed during execution.

Functions and benefits of constants: they can be used for system configuration information to facilitate program maintenance and improve readability.

Constant naming specification: all English words are capitalized, and multiple words are connected by underscores.

public class Constant {
    public static final String SCHOOL_NAME  = "Intellectual education";
    public static final String LOGIN_NAME  = "admin";
    public static final String PASS_WORD  = "123456";
} 

enumeration

 Modifier  enum Enumeration name{
            The first line lists the names of the enumeration class instances.
}
The first row of enumeration must list the object names of enumeration classes. It is recommended to use uppercase
public enum Season{
    SPRING , SUMMER , AUTUMN , WINTER;
}
Make information signs and classification
public enum Orientation {
    UP, DOWN, LEFT, RIGHT;
}

Case: the super Mary game developed now needs to receive signals in four directions (up, down, left and right) input by the user in order to control the direction of Mary's movement

package com.itheima.d5_enum;

import javax.swing.*;
import java.awt.event.ActionEvent;

/**
    Objective: other functions of constants, such as information marking and information classification (in fact, it is also a form of configuration)
 */
public class EnumDemo2 {
    public static void main(String[] args) {
        // 1. Create a window object (table)
        JFrame win = new JFrame();
        // 2. Create a panel object (tablecloth)
        JPanel panel = new JPanel();
        // 3. Put the tablecloth on the table
        win.add(panel);
        // 4. Create four button objects
        JButton btn1 = new JButton("upper");
        JButton btn2 = new JButton("lower");
        JButton btn3 = new JButton("Left");
        JButton btn4 = new JButton("right");
        // 5. Add the button object to the tablecloth
        panel.add(btn1);
        panel.add(btn2);
        panel.add(btn3);
        panel.add(btn4);
        // 6. Display window
        win.setLocationRelativeTo(null);
        win.setSize(300,400);
        win.setVisible(true);


        btn1.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                move(Orientation.UP) ; // Let Mary jump up
            }
        });
        btn2.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                move(Orientation.DOWN) ; // Let Mary jump
            }
        });
        btn3.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                move(Orientation.LEFT) ; // Let Mary run to the left
            }
        });
        btn4.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                move(Orientation.RIGHT) ; // Let Mary run to the right
            }
        });
    }

    public static void move(Orientation o){
        // Control Mary's movement
        switch (o) {
            case UP:
                System.out.println("Mary flew up~~");
                break;
            case DOWN:
                System.out.println("Mary squatted down~~");
                break;
            case LEFT:
                System.out.println("Mary ran to the left~~");
                break;
            case RIGHT:
                System.out.println("Mary to→run~~");
                break;
        }
    }
}

abstract class

The specific implementation of a method in a class cannot be determined

Modifier  abstract class Class name{  }
Modifier  abstract Return value type method name(parameter list );
public abstract class Animal{
    public abstract void run();
}

Interface interface

The interface is defined by the keyword interface. The interface cannot create an object

public interface Interface name {
       // constant
       // Abstract method
} 
public interface SportManInterface {
    // Members in the interface: before JDK 1.8, there were only constants and abstract methods
    // public static final can be omitted and not written. The interface will be added for you by default!
    // public static final String SCHOOL_NAME = "dark horse";
    String SCHOOL_NAME = "dark horse";

    // 2. Abstract method
    //  public abstract can be omitted and not written. The interface will be added for you by default!
    // public abstract void run();
    void run();

    // public abstract void eat();
    void eat();
}

Interface class implements

Interfaces are used to be implemented by classes. Classes that implement interfaces are called implementation classes. Implementation classes can be understood as so-called subclasses

Modifier  class Implementation class implements Interface 1, Interface 2, Interface 3 , ... {
}
public interface Law {
    void rule(); // Abide by laws and regulations
}

public interface SportMan {
    void run();
    void competition();
}

/**
   Implementation class (subclass)
 */
public class PingPongMan implements SportMan , Law{
    private String name;
    public PingPongMan(String name) {
        this.name = name;
    }

    @Override
    public void rule() {
        System.out.println(name + "We should abide by the laws and regulations. We should not go out at will, drink alcohol or date~~~");
    }

    @Override
    public void run() {
        System.out.println(name + "You have to run~~");
    }

    @Override
    public void competition() {
        System.out.println(name + "Need to participate in international competitions~~");
    }
}

public class Test {
    public static void main(String[] args) {
        PingPongMan p = new PingPongMan("Zhang Jike");
        p.rule();
        p.run();
        p.competition();
    }
}

Zhang Jike should abide by the laws and regulations. He should not go out at will, drink alcohol or date~~~
Zhang Jike must run~~
Zhang Jike needs to participate in international competitions~~

Interface: add method after JDK8

Default method: default modification, which implements the call of class object.

Static method: static modification, which must be called with the current interface name

Private method: private modification, which is only available at the beginning of jdk9 and can only be called inside the interface.

They will all be decorated by public by default.

package com.itheima.d13_interface_jdk8;

public interface SportManInter {
    /**
       1,JDK 8 Start: default method (instance method)
       -- It must be decorated with default, and it is decorated with public by default
       -- By default, the interface cannot create an object. This method can only be inherited to the implementation class and called by the object of the implementation class.
     */
    default void run(){
        go();
        System.out.println("Run fast~~~");
    }

    /**
      2,Static method
        static modification must be used, and public modification is used by default
        -- The static method of the interface must be called by the interface name itself.
     */
    static void inAddr(){
        System.out.println("We are all learning Java The syntax of the new method, which is Java The source code itself will be used~~~");
    }

    /**
       3,Private method (instance method)
         -- JDK 1.9 Only at the beginning.
         -- Must be inside the interface to be accessed
     */
    private void go(){
        System.out.println("Start running~~~");
    }

}

class PingPongMan implements SportManInter{
}

class Test{
    public static void main(String[] args) {
        PingPongMan p = new PingPongMan();
        p.run();


        SportManInter.inAddr();
        // PingPongMan.inAddr();
    }
}

Start running~~~
Run fast~~~
We are all learning the syntax of new methods in Java, which will be used by the Java source code itself~~~

polymorphic

Objects of the same type will behave differently if they perform the same behavior

Member access characteristics in polymorphism:

Feature method call: compile to the left and run to the right.

Variable call: see the left for compilation and the left for operation

The premise of polymorphism: Inheritance / realization relationship; A parent class reference points to a child class object; There is a way to rewrite.

Common forms of polymorphism

Parent type object name = new Subclass constructor;
Interface     Object name = new Implementation class constructor;
/**
    Parent class
 */
public class Animal {
    public String name = "Animal name";
    public void run(){
        System.out.println("Animals can run~~");
    }
}

public class Dog extends Animal{
    public String name = "Dog name";
    @Override
    public void run() {
        System.out.println("🐕The running thief slipped away~~~~~");
    }
}

public class Tortoise extends Animal{
    public String name = "Tortoise name";

    @Override
    public void run() {
        System.out.println("🐢Run very slowly~~~");
    }
}


public class Test {
    public static void main(String[] args) {
        // Objective: to understand the form of polymorphism first
        // Parent object name = new subclass constructor ();
        Animal a = new Dog();
        a.run(); // Method call: compile to the left and run to the right
        System.out.println(a.name); // Variable call: compile and run on the left, animal name

        Animal a1 = new Tortoise();
        a1.run();
        System.out.println(a1.name); // Animal name
    }
}

🐕 The running thief slipped away~~~~~
Animal name
🐢 Run very slowly~~~
Animal name

In class transformation mechanism in polymorphic form

1. How many types of reference data types can be converted?

  • Automatic type conversion, forced type conversion.

2. What problems can forced type conversion solve? What should we pay attention to when casting.

  • It can be converted to a real subclass type to call the unique functions of the subclass.
  • Two types with inheritance relationship / implementation can be cast, and there is no problem in compilation.
  • When running, if it is found that the cast type is not the real type of the object, an error will be reported.
  • Type conversion exception: ClassCastException
/**
    Parent class
 */
public class Animal {
    public String name = "Animal name";
    public void run(){
        System.out.println("Animals can run~~");
    }
}

public class Dog extends Animal {
    public String name = "Dog name";
    @Override
    public void run() {
        System.out.println("🐕The running thief slipped away~~~~~");
    }

    /**
      Unique function
     */
    public void lookDoor(){
        System.out.println("🐕Watching🚪!!!");
    }
}

public class Tortoise extends Animal {
    public String name = "Tortoise name";

    @Override
    public void run() {
        System.out.println("🐢Run very slowly~~~");
    }

    /**
     Unique function
     */
    public void layEggs(){
        System.out.println("🐢Laying eggs~~~");
    }
}

/**
     Objective: to learn the transformation mechanism in class in polymorphic form.
 */
public class Test {
    public static void main(String[] args) {
        // Automatic type conversion
        Animal a = new Dog();
        a.run();
//        a.lookDoor(); //  Functions unique to subclasses cannot be called under polymorphism

        // Forced type conversion: it can realize the function of calling the unique function of subclasses
        Dog d = (Dog) a;
        d.lookDoor();

        // Note: type conversion exceptions may occur if you directly force type conversion under polymorphism
        // It stipulates that two types with inheritance or implementation relationship can be forced to type conversion, and there may be problems at run time.
        // Tortoise t1 = (Tortoise) a;
        // It is recommended to judge the real type of the variable pointing to the object before cast.
        if(a instanceof Tortoise){
            Tortoise t = (Tortoise) a;
            t.layEggs();
        }else if(a instanceof Dog){
            Dog d1 = (Dog) a;
            d1.lookDoor();
        }

        System.out.println("---------------------");
        Animal a1 = new Dog();
        go(a1);
    }

    public static void go(Animal a){
        System.out.println("get set~~~");
        a.run();
        // Unique function
        if(a instanceof Tortoise){
            Tortoise t = (Tortoise) a;
            t.layEggs();
        }else if(a instanceof Dog){
            Dog d1 = (Dog) a;
            d1.lookDoor();
        }
        System.out.println("end~~~~");
    }
}

🐕 The running thief slipped away~~~~~
🐕 Watching 🚪!!!
🐕 Watching 🚪!!!
---------------------
Prepare~~~
🐕 The running thief slipped away~~~~~
🐕 Watching 🚪!!!
End~~~~

Inner class

An internal class is a class defined in a class. The internal class can be understood as (parasitism) and the external class can be understood as (host)

public class People{
    // Inner class
    public class Heart{
    }
}

Static inner class

  • It is decorated with static and belongs to the external class itself.
  • Its characteristics and use are exactly the same as those of ordinary classes. It has some components of classes, but it is located in others
  • Static members of external classes can be accessed directly, but instance members of external classes cannot be accessed directly
public class Outer{
        // Static member inner class
        public static class Inner{
        }
}

The format of the object created by the static inner class

Format: external class name.Internal class name object name = new External class name.Inner class constructor;
example: Outer.Inner in =  new Outer.Inner();

Member inner class

  • Objects belonging to external classes without static decoration.
  • Before JDK16, static members cannot be defined in the inner class of members. Static members can also be defined from JDK 16
  • Static members of external classes can be accessed directly, and instance members of external classes can be accessed directly in instance methods
public class Outer {
    // Member inner class
    public class Inner {
    
    }
}

The format of the object created by the inner class of the member

Format: external class name.Internal class name object name = new  External class constructor.new Inner class constructor();
example: Outer.Inner in =  new Outer().new Inner();

Local inner class

  • Local internal classes are placed in executors such as methods, code blocks, constructors, etc.
  • The class file name of the local internal class is: external class $N internal class class

Anonymous Inner Class

It is essentially a local internal class without a name, which is defined in methods, code blocks, etc.
Function: it is convenient to create subclass objects. The ultimate purpose is to simplify code writing.

new class|Abstract class name|Or interface name() {
    override method ;
};
Animal a = new Animal() {
    public void run() {
    }
};
a. run();
public class Test {
    public static void main(String[] args) {
        Animal a = new Animal(){
            @Override
            public void run() {
                System.out.println("Tiger running block~~~");
            }
        };
        a.run();
    }
}

//class Tiger extends Animal{
//    @Override
//    public void run() {
//        System.out.println("tiger running block ~ ~");
//    }
//}

abstract class Animal{
    public abstract void run();
}

Understanding of the use form of anonymous internal classes in development

A school needs to let teachers, students and athletes participate in swimming competitions together

/*Swimming interface*/
public interface Swimming {
    void swim();
}
/* Test class*/
public class JumppingDemo {
    public static void main(String[] args) {
        //Requirements: goSwimming method
    }
     
    // Define a way for all characters to come in and play together
    public static void goSwimming(Swimming swimming) {
        swimming.swim();
    }
}

API

  • API(Application Programming interface).
  • Simply put: it's some methods that Java has written for us. We can take them directly and use them.

Object class

  • The method of Object class can be used directly by all subclass objects, so we need to learn the method of Object class.
  • A class either inherits the Object class by default or indirectly. The Object class is the ancestor class in Java

toString method of Object

The meaning of the parent toString() method is to be rewritten by the subclass to return the content information of the object, not the address information!!  

Student s = new Student("Xiong Zhou", 'male', 19);
System.out.println(s);

To + Tab key to quickly rewrite toString method in object

package com.itheima.d9_api_object;

import java.util.Objects;

public class Student { //extends Object{
    private String name;
    private char sex;
    private int age;

    public Student() {
    }

    public Student(String name, char sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }
}


package com.itheima.d9_api_object;

/**
    Objective: master the use of toString method in Object class.
 */
public class Test1 {
    public static void main(String[] args) {
        Student s = new Student("Xiong Zhou", 'male', 19);
        // Output object variables directly. By default, you can omit toString calls that are not written
        System.out.println(s);
    }
}

Student{name = 'Zhou Xiong', sex = male, age=19}

equals method of Object

The meaning of the parent class equals method is to be overridden by the subclass so that the subclass can customize the comparison rules by itself

Objects.equals(s1, s2)
package com.itheima.d9_api_object;

import java.util.Objects;

public class Student { //extends Object{
    private String name;
    private char sex;
    private int age;

    public Student() {
    }

    public Student(String name, char sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     Customize equality rules.
     If the contents of two objects are the same, they are considered equal
     s1.equals(s2)
     Compared by: s1 == this
     Compared by: S2 = = > o
     */
    @Override
    public boolean equals(Object o) {
        // 1. Judge whether it is the same object comparison. If so, return true.
        if (this == o) return true;
        // 2. If o is null, return false. If o is not a student type, return false Student !=  .. Pig
        if (o == null || this.getClass() != o.getClass()) return false;
        // 3. Description o must be student type and not null
        Student student = (Student) o;
        return sex == student.sex && age == student.age && Objects.equals(name, student.name);
    }


    /**
       Rewrite equals and customize the equality rules yourself.
        If the contents of two objects are the same, they are considered equal
     s1.equals(s2)
     Compared by: s1 == this
     Compared by: S2 = = > o
     */
 /*   @Override
    public boolean equals(Object o){
        // 1,Judge whether o is a student type
        if(o instanceof Student){
            Student s2 = (Student) o;
            // 2,Judge whether the contents of the two objects are the same.
//            if(this.name.equals(s2.name) &&
//                 this.age == s2.age && this.sex == s2.sex){
//                return true;
//            }else {
//                return false;
//            }
            return this.name.equals(s2.name) && this.age == s2.age
                    && this.sex == s2.sex ;

        }else {
            // Students can only compare with students, otherwise the result must be false
            return false;
        }
    }*/


    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }
}


package com.itheima.d9_api_object;

import java.util.Objects;

/**
    Objective: master the use of equals method in Object class.
 */
public class Test2 {
    public static void main(String[] args) {
        Student s1 = new Student("Xiong Zhou", 'male', 19);
        Student s2 = new Student("Xiong Zhou", 'male', 19);
        // equals by default is to compare whether the addresses of two objects are the same. After subclass rewriting, subclass rewriting will be called to compare whether the contents are the same.
        System.out.println(s1.equals(s2));
        System.out.println(s1 == s2);

        System.out.println(Objects.equals(s1, s2));
    }
}

StringBuilder

StringBuilder is a variable string class, which can be regarded as an object container.

StringBuilder is recommended for splicing and reversing strings:

String: the content is immutable, and the performance of splicing string is poor.

StringBuilder: the content is variable, the splicing string performance is good, and the code is elegant.

Usage

Define String use String

String builder is used for splicing, modifying and other operation strings

public StringBuilder()

Create a blank variable string object that contains nothing

public StringBuilder(String str)

Creates a variable string object that specifies the content of the string

Public StringBuilder append (any type)

Add data and return the StringBuilder object itself

public StringBuilder reverse()

Invert the contents of an object

public int length()

Return object content length

public String toString()

You can convert StringBuilder to String by toString()

public class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("a");
        sb.append("b");
        sb.append("c");
        System.out.println(sb);
    }
}

Math class

Contains methods that perform basic numeric operations. The Math class does not provide an exposed constructor.

How to use members in a class? See whether the members of the class are static. If so, you can call it directly through the class name

Common methods of Math class

Method name

explain

public static int abs​(int a)

Get absolute value of parameter

public static double ceil​(double a)

Round up

public static double floor​(double a)

Round down

public static int round​(float a)

rounding

public static int max​(int a,int b)

Gets the larger of the two int values

public static double pow​(double a,double b)

Returns the value of a to the power of b

public static double random​()

Random value with return value of double, range [0.0,1.0]

package com.itheima.d12_math;

/**
    Goal: use of Math class.
    Math Used for mathematical operations.
    Math The methods in the class are all static methods, which can be called directly with the class name.
    method:
          Method name Description
          public static int abs(int a)                   Get the absolute value of parameter a:
          public static double ceil(double a)            Round up
          public static double floor(double a)           Round down
          public static double pow(double a, double b)   Get the b power of a
          public static long round(double a)             Rounding
    Summary:
          Remember.
 */
public class MathDemo {
    public static void main(String[] args) {
        // 1. Take absolute value: return a positive number
        System.out.println(Math.abs(10)); // 10
        System.out.println(Math.abs(-10.3)); // 10.3

        // 2. Rounding up: 5
        System.out.println(Math.ceil(4.00000001)); // 5.0
        System.out.println(Math.ceil(4.0)); // 4.0
        // 3. Rounding down: 4
        System.out.println(Math.floor(4.99999999)); // 4.0
        System.out.println(Math.floor(4.0)); // 4.0

        // 4. Find exponential power
        System.out.println(Math.pow(2 , 3)); // 2^3 = 8.0
        // 5. Rounding 10
        System.out.println(Math.round(4.49999)); // 4
        System.out.println(Math.round(4.500001)); // 5

        System.out.println(Math.random());  // 0.0 - 1.0 (before package but not after package)

        // Expansion: random number between 3 - 9 (0 - 6) + 3
        //  [0 - 6] + 3
        int data =  (int)(Math.random() * 7) + 3;
        System.out.println(data);


    }
}

System class

System is also a tool class, which represents the current system and provides some system related methods.

Common methods of System class

Method name

explain

public static void exit​(int status)

Terminate the currently running Java virtual machine. Non zero indicates abnormal termination

public static long currentTimeMillis​()

Returns the time of the current system in milliseconds

Public static void array copy (data source array, start index, destination array, start index, number of copies)

Array copy

Terminate the currently running Java virtual machine

System.exit(0); // JVM terminated!

Returns the time of the current system in milliseconds

long time = System.currentTimeMillis();
System.out.println(time);//1643334543214

Calculation of time: Performance Analysis

        long startTime = System.currentTimeMillis();
        // Calculation of time: Performance Analysis
        for (int i = 0; i < 100000; i++) {
            System.out.println("Output:" + i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println((endTime - startTime)/1000.0 + "s");

Make array copy

        /**
         arraycopy(Object src,  int  srcPos,
         Object dest, int destPos,
         int length)
         Parameter 1: copied array
         Parameter 2: which index position to copy from
         Parameter 3: copy target array
         Parameter 4: paste position
         Parameter 5: number of copied elements
         */
        int[] arr1 = {10, 20, 30, 40, 50, 60, 70};
        int[] arr2 = new int[6]; // [0, 0, 0, 0, 0, 0] ==>  [0, 0, 40, 50, 60, 0]
        System.arraycopy(arr1, 3, arr2, 2, 3);
        System.out.println(Arrays.toString(arr2));

[0, 0, 40, 50, 60, 0]

BigDecimal

It is used to solve the problem of precision distortion of floating-point operation

Create an object BigDecimal to encapsulate floating-point data (the best way is to call a method)

public static BigDecimal valueOf(double val):   Packed floating point numbers become BigDecimal object

Method name

explain

public BigDecimal add(BigDecimal b)

addition

public BigDecimal subtract(BigDecimal b)

subtraction

public BigDecimal multiply(BigDecimal b)

multiplication

public BigDecimal divide(BigDecimal b)

division

public BigDecimal divide (another BigDecimal object, exact digits, rounding mode)

division

package com.itheima.d14_bigdecimal;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;

/**
    Target: BigDecimal big data class.

    introduce:
        Direct + * / during floating-point operation may cause data distortion (accuracy problem).
        BigDecimal It can solve the problem of data distortion of floating-point operation.

    BigDicimal Class:
        Package: Java math.
        How to create objects (best way:)
              public static BigDecimal valueOf(double val) :Wrap floating-point numbers into big data objects.
        Method declaration
              public BigDecimal add(BigDecimal value)       Addition operation
              public BigDecimal subtract(BigDecimal value)  Subtraction operation 
              public BigDecimal multiply(BigDecimal value)  Multiplication 
              public BigDecimal divide(BigDecimal value)    Division operation
              public double doubleValue(): Convert BigDecimal to double type.
 */
public class BigDecimalDemo {
    public static void main(String[] args) {
        // Direct + * / during floating-point operation may cause data distortion (accuracy problem).
        System.out.println(0.09 + 0.01);
        System.out.println(1.0 - 0.32);
        System.out.println(1.015 * 100);
        System.out.println(1.301 / 100);

        System.out.println("-------------------------");
        double a = 0.1;
        double b = 0.2;
        double c = a + b;
        System.out.println(c);
        System.out.println("--------------------------");
        // Packaging floating point data into big data object BigDeciaml
        BigDecimal a1 = BigDecimal.valueOf(a);
        BigDecimal b1 = BigDecimal.valueOf(b);
        BigDecimal c1 = a1.add(b1);
        // BigDecimal c1 = a1.subtract(b1);
        // BigDecimal c1 = a1.multiply(b1);
        // BigDecimal c1 = a1.divide(b1);
        System.out.println(c1);

        // Purpose: double
        double rs = c1.doubleValue();
        System.out.println(rs);

        // Note: BigDecimal must be calculated with precision
        BigDecimal a11 = BigDecimal.valueOf(10.0);
        BigDecimal b11 = BigDecimal.valueOf(3.0);
        /**
           Parameter 1: divisor parameter 2: keep decimal places parameter 3: rounding mode
         */
        BigDecimal c11 = a11.divide(b11, 2, RoundingMode.HALF_UP); // 3.3333333333
        System.out.println(c11);


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

0.09999999999999999
0.6799999999999999
101.49999999999999
0.013009999999999999
-------------------------
0.30000000000000004
--------------------------
0.3
0.3
3.33
-------------------

Date class: date and time information of the current system

Date d = new Date();    //Represents the current date and time object of the system
long time = d.getTime();    //Gets the value of the time in milliseconds

//Go back 1 hour 121s from the current time
long time = System.currentTimeMillis();
time += (60 * 60 + 121) * 1000;

//Convert the time millisecond value to the corresponding date object
Date d = new Date(time);

//Modification time
Date d = new Date();
d3.setTime(time);

Fri Jan 28 10:13:30 HKT 2022
1643336010844 

SimpleDateFormat class: formatting operation of date and time

Fri Jan 28 10:13:30 CST 2022 - > January 28, 2022 10:13:30

  • y # year
  • M # month
  • d # day
  • H hour
  • m # min
  • s , sec
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss EEE a");
String rs = sdf.format(d);

long time1 = System.currentTimeMillis()
String rs2 = sdf.format(time1);
        // 1. Date object
        Date d = new Date();
        System.out.println(d);

        // 2. Format this date object (specify the final format)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss EEE a");
        // 3. Start formatting the date object into the preferred string form
        String rs = sdf.format(d);
        System.out.println(rs);

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

        // 4. Format time in milliseconds
        // Demand: what is the time after 121 seconds
        long time1 = System.currentTimeMillis() + 121 * 1000;
        String rs2 = sdf.format(time1);
        System.out.println(rs2);

Fri Jan 28 10:16:17 HKT 2022
Friday morning, January 28, 2022, 10:16:17
----------------------------
Friday morning, January 28, 2022, 10:18:18

SimpleDateFormat parses the string time to become a date object

Date d = sdf.parse(dateStr);
// Objective: learn to use SimpleDateFormat to parse string time and become Date object.
        // There is a time. What is the time after two days, 14 hours, 49 minutes and 06 seconds from 11:11:11 on August 6, 2021.
        // 1. Get the string time into the program
        String dateStr = "2021 August 6, 2011:11:11";

        // 2. Parse the string time into a date object (the focus of this section): the form must be exactly the same as that of the parsed time, otherwise an error will be reported during runtime parsing!
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
        Date d = sdf.parse(dateStr);

        // 3. Go back for 2 days, 14 hours, 49 minutes and 06 seconds
        long time = d.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;

        // 4. Formatting this time in milliseconds is the result
        System.out.println(sdf.format(time));

Calendar: the calendar object corresponding to the current date of the system

Calendar is an abstract class and cannot create objects directly.

    Calendar Syntax for calendar class to create calendar object:
        Calendar rightNow = Calendar.getInstance();
    Calendar How to:
        1.public static Calendar getInstance(): Returns an object of a calendar class.
        2.public int get(int field): Get the information of a field in the date.
        3.public void set(int field,int value): Modify a field information of the calendar.
        4.public void add(int field,int amount): Add for a field/Decrease the specified value
        5.public final Date getTime(): Get the current date object.
        6.public long getTimeInMillis(): Get the current time in milliseconds
package com.itheima.d3_calendar;

import javax.xml.crypto.Data;
import java.util.Calendar;
import java.util.Date;

public class CalendarDemo{
    public static void main(String[] args) {
        // 1. Get the current calendar object of the system
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);

        // 2. Get calendar information: public int get(int field): get the information of a field in the date.
        int year = cal.get(Calendar.YEAR);
        System.out.println(year);

        int mm = cal.get(Calendar.MONTH) + 1;
        System.out.println(mm);

        int days = cal.get(Calendar.DAY_OF_YEAR) ;
        System.out.println(days);

        // 3. public void set(int field,int value): modifies the information of a field of the calendar.
        // cal.set(Calendar.HOUR , 12);
        // System.out.println(cal);

        // 4.public void add(int field,int amount): increase / decrease the specified value for a field
        // What time is it in 64 days
        cal.add(Calendar.DAY_OF_YEAR , 64);
        cal.add(Calendar.MINUTE , 59);

        //  5.public final Date getTime(): get the current date object.
        Date d = cal.getTime();
        System.out.println(d);

        //  6.public long getTimeInMillis(): get the current time in milliseconds
        long time = cal.getTimeInMillis();
        System.out.println(time);

    }
}

java.util.GregorianCalendar[time=1643336750682,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo

[id="Asia/Hong_Kong",offset=28800000,dstSavings=0,useDaylight=false,transitions=71,lastRule=null],

firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=0,WEEK_OF_YEAR=5,WEEK_OF_MONTH=5,

DAY_OF_MONTH=28,DAY_OF_YEAR=28,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=10,

HOUR_OF_DAY=10,MINUTE=25,SECOND=50,MILLISECOND=682,ZONE_OFFSET=28800000,DST_OFFSET=0]
2022
1
28
Sat Apr 02 11:24:50 HKT 2022
1648869890682

JDK8 new date class

LocalDate: a date that does not contain a specific time.
LocalTime: time without date.
LocalDateTime: contains the date and time.
Instant: represents the timestamp.
DateTimeFormatter is used to format and parse time
Duration: used to calculate two "time" intervals
Period: used to calculate the interval between two dates

Instant timestamp

  • Timestamps contain date and time, which is similar to Java util. Date is very similar. In fact, Instant is similar to the date before JDK8.
  • Instant and Date classes can be converted.
package com.itheima.d4_jdk8_time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class Demo05Instant {
    public static void main(String[] args) {
        // 1. Get an Instant timestamp object
        Instant instant = Instant.now();
        System.out.println(instant);

        // 2. What about the timestamp of the system at the moment?
        Instant instant1 = Instant.now();
        System.out.println(instant1.atZone(ZoneId.systemDefault()));

        // 3. How to return Date object
        Date date = Date.from(instant);
        System.out.println(date);

        Instant i2 = date.toInstant();
        System.out.println(i2);
    }
}

2022-01-28T02:34:50.645395800Z
2022-01-28T10:34:50.654372600+08:00[Asia/Hong_Kong]
Fri Jan 28 10:34:50 HKT 2022
2022-01-28T02:34:50.645Z

DateTimeFormatter

Date and time formatter, both positive and negative, can call the format method

package com.itheima.d4_jdk8_time;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo06DateTimeFormat {
    public static void main(String[] args) {
        // Local date time object
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        // Parser / formatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
        // Forward formatting
        System.out.println(dtf.format(ldt));
        // Reverse formatting
        System.out.println(ldt.format(dtf));

        // Parsing string time
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // Parse the current string time to become a local date time object
        LocalDateTime ldt1 = LocalDateTime.parse("2019-11-11 11:11:11" ,  dtf1);
        System.out.println(ldt1);
        System.out.println(ldt1.getDayOfYear());
    }
}

2022-01-28T10:36:24.292803800
2022-01-28 10:36:24 Friday morning
2022-01-28 10:36:24 Friday morning
2019-11-11T11:11:11
315

Duration: used to calculate two "time" intervals

In Java 8, we can use the following classes to calculate the time interval difference: Java time. Duration
A method of measuring the amount of time using time-based values is provided.
Used for comparison between localdatetimes. It can also be used for comparison between Instant.

        // Local date time object.
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // Date time object of birth
        LocalDateTime birthDate = LocalDateTime.of(2021,8
                ,06,01,00,00);

        System.out.println(birthDate);

        Duration duration = Duration.between(  today , birthDate);//The second parameter minus the first parameter

        System.out.println(duration.toDays());//Number of days between two time differences
        System.out.println(duration.toHours());//Hours of difference between two times
        System.out.println(duration.toMinutes());//Minutes between two times
        System.out.println(duration.toMillis());//Number of milliseconds between two time differences
        System.out.println(duration.toNanos());//Nanoseconds of two time differences

Period: used to calculate the interval between two dates

In Java 8, we can use the following classes to calculate the date interval difference: Java time. Period
It is mainly calculated by the Period class methods getYears(), getMonths() and getDays(), which can only be accurate to month, year and day.
Used for comparison between localdates.

        // Current local date
        LocalDate today = LocalDate.now();
        System.out.println(today);//

        // Date of birth
        LocalDate birthDate = LocalDate.of(1998, 10, 13);
        System.out.println(birthDate);

        Period period = Period.between(birthDate, today);//The second parameter minus the first parameter

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

The chrononunit class can be used to measure a period of time in a single time unit

This tool class is the most complete and can be used to compare all time units

package com.itheima.d4_jdk8_time;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Demo09ChronoUnit {
    public static void main(String[] args) {
        // Local date and time object: current date and time
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // Birthday time
        LocalDateTime birthDate = LocalDateTime.of(1990,10,1,
                10,50,59);
        System.out.println(birthDate);

        System.out.println("Years of difference:" + ChronoUnit.YEARS.between(birthDate, today));
        System.out.println("Months of difference:" + ChronoUnit.MONTHS.between(birthDate, today));
        System.out.println("Weeks of difference:" + ChronoUnit.WEEKS.between(birthDate, today));
        System.out.println("Days difference:" + ChronoUnit.DAYS.between(birthDate, today));
        System.out.println("Hours of difference:" + ChronoUnit.HOURS.between(birthDate, today));
        System.out.println("Difference score:" + ChronoUnit.MINUTES.between(birthDate, today));
        System.out.println("Seconds difference:" + ChronoUnit.SECONDS.between(birthDate, today));
        System.out.println("Milliseconds difference:" + ChronoUnit.MILLIS.between(birthDate, today));
        System.out.println("Microseconds difference:" + ChronoUnit.MICROS.between(birthDate, today));
        System.out.println("Nanosecond difference:" + ChronoUnit.NANOS.between(birthDate, today));
        System.out.println("Half day difference:" + ChronoUnit.HALF_DAYS.between(birthDate, today));
        System.out.println("Number of years of difference:" + ChronoUnit.DECADES.between(birthDate, today));
        System.out.println("Centuries of difference:" + ChronoUnit.CENTURIES.between(birthDate, today));
        System.out.println("Millennia of difference:" + ChronoUnit.MILLENNIA.between(birthDate, today));
        System.out.println("Age difference:" + ChronoUnit.ERAS.between(birthDate, today));
    }
}

2022-01-28T10:41:03.186356600
1990-10-01T10:50:59
Year difference: 31
Months difference: 375
Weeks of difference: 1634
Days difference: 11441
Hours of difference: 274607
Difference score: 16476470
Seconds difference: 988588204
Milliseconds difference: 988588204186
Microseconds difference: 988588204186356
Nanosecond difference: 988588204186356600
Half day difference: 22883
Number of years of difference: 3
Centuries of difference: 0
Millennia of difference: 0
Era difference: 0

Packaging

In fact, it is the reference type corresponding to the eight basic data types

In order to realize all objects, Java provides corresponding reference types for eight basic types.

In fact, the following collections and generics can only support wrapper types, not basic data types

Basic data type

Reference data type

byte

Byte

short

Short

int

Integer

long

Long

char

Character

float

Float

double

Double

boolean

Boolean

Automatic packing: data and variables of basic type can be directly assigned to variables of packing type

Automatic unpacking: variables of package type can be directly assigned to variables of basic data type

Unique functions of packaging

  • The default value of the variable of the wrapper class can be null, and the fault tolerance rate is higher.
  • You can convert basic type data to string type (not very useful)
  • You can convert numeric values of string type into real data type (really useful)
int age = Integer.valueOf(number);
double score = Double.valueOf(number1);
package com.itheima.d5_integer;

/**
    Objective: understand the concept of packaging class and use it.
 */
public class Test {
    public static void main(String[] args) {
        int a = 10;
        Integer a1 = 11;
        Integer a2 = a; // Automatic packing
        System.out.println(a);
        System.out.println(a1);

        Integer it = 100;
        int it1 = it; // Automatic unpacking
        System.out.println(it1);

        double db = 99.5;
        Double db2 = db; // Automatic packing
        double db3 = db2; // Automatic unpacking
        System.out.println(db3);

        // int age = null; //  Wrong report!
        Integer age1 = null;
        Integer age2 = 0;

        System.out.println("-----------------");
        // 1. Wrapper classes can convert basic types of data into string form. (useless)
        Integer i3 = 23;
        String rs = i3.toString();
        System.out.println(rs + 1);

        String rs1 = Integer.toString(i3);
        System.out.println(rs1 + 1);

        // You can directly + string to get the string type
        String rs2 = i3 + "";
        System.out.println(rs2 + 1);

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

        String number = "23";
        //Convert to integer
        // int age = Integer.parseInt(number);
        int age = Integer.valueOf(number);
        System.out.println(age + 1);

        String number1 = "99.9";
        //Convert to decimal
        //double score = Double.parseDouble(number1);
        double score = Double.valueOf(number1);
        System.out.println(score + 0.1);
    }
}

10
11
100
99.5
-----------------
231
231
231
-----------------
24
100.0

regular expression

public boolean matches(String regex):Judge whether it matches the regular expression and return true

Character class (matching one character by default)

[abc] can only be a, b, or c

[^ abc] any character except a, b, c

[a-zA-Z] A to z A to Z, including (range)

[a-d[m-p]] A to d, or m through P: ([a-dm-p] joint)

[A-Z & & [def]] d, e, or F (intersection)

[a-Z & & [^ BC]] a to Z, except b and c: ([ad-z] subtraction)

[A-Z & & [^ M-p]] A to Z, except m to p: ([a-lq-z] subtraction)

Predefined character class (matching one character by default)

. any character

\d. a number: [0-9]

\D non numeric: [^ 0-9]

\s is a blank character: [\ t\n\x0B\f\r]

\s non white space character: [^ \ s]

\w [a-zA-Z_0-9] English, number, underline

\W [^ \ w] a non word character

Greedy quantifier (matching multiple characters)

X? X, once or not at all

X * x, zero or more times

X + X, one or more times

X {n} x, exactly n times

X {n,} x, at least N times

X {n,m} x, at least N but not more than m times

        // Only a B C
        System.out.println("a".matches("[abc]")); // true
        System.out.println("z".matches("[abc]")); // false

        // No a, B, C
        System.out.println("a".matches("[^abc]")); // false
        System.out.println("z".matches("[^abc]")); // true

        System.out.println("a".matches("\\d")); // false
        System.out.println("3".matches("\\d")); // true
        System.out.println("333".matches("\\d")); // false
        System.out.println("z".matches("\\w")); // true
        System.out.println("2".matches("\\w")); // true
        System.out.println("21".matches("\\w")); // false
        System.out.println("you".matches("\\w")); //false
        System.out.println("you".matches("\\W")); // true
        System.out.println("---------------------------------");
        //  The above regular matching can only check a single character.

        // Check password
        // It must be a numeric alphabetic underscore with at least 6 digits
        System.out.println("2442fsfsf".matches("\\w{6,}"));
        System.out.println("244f".matches("\\w{6,}"));

        // Verification code must be numeric and character must be 4 digits
        System.out.println("23dF".matches("[a-zA-Z0-9]{4}"));
        System.out.println("23_F".matches("[a-zA-Z0-9]{4}"));
        System.out.println("23dF".matches("[\\w&&[^_]]{4}"));
        System.out.println("23_F".matches("[\\w&&[^_]]{4}"));

 public String replaceAll(String regex,String newStr)

Replace according to the regular expression

public String[] split(String regex):

Divide the string according to the matching content of the regular expression and return an array of strings.

        String names = "path dhdfhdf342 Rong'er 43 fdffdfbjdfaf Xiao He";

        String[] arrs = names.split("\\w+");
        for (int i = 0; i < arrs.length; i++) {
            System.out.println(arrs[i]);
        }

        String names2 = names.replaceAll("\\w+", "  ");
        System.out.println(names2);

path
Rong'er
Xiao He
Xiao He, rong'er, Xiao He

Content in regular expression crawling information

package com.itheima.d6_regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
    Extension: regular expression crawls the contents of information. (understand)
 */
public class RegexDemo05 {
    public static void main(String[] args) {
        String rs = "Come to the dark horse program to learn Java,Tel: 020-43422424,Or contact email" +
                "itcast@itcast.cn,Tel: 1876283263302032323" +
                "mailbox bozai@itcast.cn,400-100-3233 ,4001003232";

        // Requirement: climb out the phone number and email from the above content.
        // 1. Define crawling rules in string form
        String regex = "(\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2})|(1[3-9]\\d{9})" +
                "|(0\\d{2,6}-?\\d{5,20})|(400-?\\d{3,9}-?\\d{3,9})";

        // 2. Compile the crawling rule into a matching object.
        Pattern pattern = Pattern.compile(regex);

        // 3. Get a content matcher object
        Matcher matcher = pattern.matcher(rs);

        // 4. Start looking
        while (matcher.find()) {
            String rs1 = matcher.group();
            System.out.println(rs1);
        }

    }
}

020-43422424
itcast@itcast.cn
18762832633
0203232323
bozai@itcast.cn
400-100-3233
4001003232

Arrays class: array operation tool class, which is specially used to operate array elements.

public static String toString (type [] a)

Returns the contents of an array (in string form)

public static void sort (type [] a)

Default ascending sort for arrays

public static < T > void sort (type [] A, comparator <? Super T > c)

Custom sorting using comparator objects

public static int binarySearch​(int[] a, int key)

For the data in the binary search array, if the index exists, return - 1 if it does not exist

package com.itheima.d7_arrays;

import java.util.Arrays;

public class ArraysDemo1 {
    public static void main(String[] args) {
        // Objective: learn to use the common API s of Arrays class and understand its principle
        int[] arr = {10, 2, 55, 23, 24, 100};
        System.out.println(arr);

        // 1. Return toString (array) of array contents
//        String rs = Arrays.toString(arr);
//        System.out.println(rs);

        System.out.println(Arrays.toString(arr));

        // 2. Sorting API (automatically sort the array elements in ascending order by default)
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        // 3. Binary search technology (the premise array must be arranged in order to support, otherwise there will be a bug)
        int index = Arrays.binarySearch(arr, 55);
        System.out.println(index);

        // Return the rule of non-existent elements: - (location index that should be inserted + 1)
        int index2 = Arrays.binarySearch(arr, 22);
        System.out.println(index2);


        // Note: if the array is not well ordered, the existing elements may not be found, resulting in a bug!!
        int[] arr2 = {12, 36, 34, 25 , 13,  24,  234, 100};
        System.out.println(Arrays.binarySearch(arr2 , 36));
    }

}

[I@776ec8df
[10, 2, 55, 23, 24, 100]
[2, 10, 23, 24, 55, 100]
4
-3
-7

public static void sort (type [] a)

Default ascending sort for arrays

public static < T > void sort (type [] A, comparator <? Super T > c)

Custom sorting using comparator objects

package com.itheima.d7_arrays;

import java.util.Arrays;
import java.util.Comparator;

public class ArraysDemo2 {
    public static void main(String[] args) {
        // Objective: to customize the collation of the array: Comparator comparator object.
        // 1. The sort method of Arrays is the default ascending sort for Arrays with value characteristics
        int[] ages = {34, 12, 42, 23};
        Arrays.sort(ages);
        System.out.println(Arrays.toString(ages));

        // 2. Requirements: sort in descending order! (custom comparator object, can only support sorting of reference types!!)
        Integer[] ages1 = {34, 12, 42, 23};
        /**
           Parameter 1: the sorted array must be an element of reference type
           Parameter 2: anonymous inner class object, which represents a comparator object.
         */
        Arrays.sort(ages1, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                // Specify comparison rules.
//                if(o1 > o2){
//                    return 1;
//                }else if(o1 < o2){
//                    return -1;
//                }
//                return 0;
                // return o1 - o2; //  Default ascending order
                return o2 - o1; //  Descending order
            }
        });
        System.out.println(Arrays.toString(ages1));

        System.out.println("-------------------------");
        Student[] students = new Student[3];
        students[0] = new Student("Wu Lei",23 , 175.5);
        students[1] = new Student("Xie Xin",18 , 185.5);
        students[2] = new Student("Liang Wang",20 , 195.5);
        System.out.println(Arrays.toString(students));

        // Arrays.sort(students);  //  Direct running rout
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                // Specify your own comparison rules
                // return o1.getAge() - o2.getAge(); //  Sort by age in ascending order!
                // return o2.getAge() - o1.getAge(); //  Sort by age in descending order!!
                // return Double.compare(o1.getHeight(), o2.getHeight()); //  Compare floating-point types in ascending order
                return Double.compare(o2.getHeight(), o1.getHeight()); // Compare floating-point types in descending order
            }
        });
        System.out.println(Arrays.toString(students));


    }
}
package com.itheima.d7_arrays;

public class Student {
    private String name;
    private int age;
    private double height;

    public Student() {
    }

    public Student(String name, int age, double height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", height=" + height +
                '}';
    }
}

Common algorithms

Bubble sorting

package com.itheima.d8_sort_binarysearch;

import java.util.Arrays;

/**
    Objective: learn to use the method of selective sorting to sort the array.
 */
public class Test1 {
    public static void main(String[] args) {
        // 1. Define array
        int[] arr = {5, 1, 3, 2};
        //           0  1  2  3

        // 2. Define a cycle control to select several rounds: arr.length - 1
        for (int i = 0; i < arr.length - 1; i++) {
            // i = 0   j =  1  2  3
            // i = 1   j =  2  3
            // i = 2   j =  3
            // 3. Define the internal loop and control the selection several times
            for (int j = i + 1; j < arr.length; j++) {
                // Current bit: arr[i]
                // If there is smaller than the current bit data, the data is exchanged
                if(arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}

Select sort

Binary search

  • Define the left and right positions of variable records.
  • Use the while loop to control the query (the condition is that the left position < = the right position)
  • Get intermediate element index inside loop
  • Judge the current element to be found. If it is larger than the middle element, the left position = middle index + 1
  • Judge the element to be found. If it is smaller than the middle element, the right position = middle index - 1
  • Judge the current element to be found. If it is equal to the intermediate element, return the current intermediate element index
package com.itheima.d8_sort_binarysearch;

/**
    Objective: to understand the principle of binary search and realize it.
 */
public class Test2 {
    public static void main(String[] args) {
        // 1. Define array
        int[] arr = {10, 14, 16, 25, 28, 30, 35, 88, 100};
        //                                            r
        //                                                l
        //
        System.out.println(binarySearch(arr , 35));
        System.out.println(binarySearch(arr , 350));
    }
    /**
     * Implementation of binary search algorithm
     * @param arr  Sorted array
     * @param data Data to find
     * @return  Index. If the element does not exist, return - 1 directly
     */
    public static int binarySearch(int[] arr, int data){
        // 1. Define left and right positions
        int left = 0;
        int right = arr.length - 1;

        // 2. Start the cycle and query in half.
        while (left <= right){
            // Take intermediate index
            int middleIndex = (left + right) / 2;
            // 3. Judge the size of the element in the current middle position and the element to be found
            if(data > arr[middleIndex]) {
                // Look to the right and update the left position to = middle index + 1
                left = middleIndex + 1;
            }else if(data < arr[middleIndex]) {
                // Look to the left, right position = middle index - 1
                right = middleIndex - 1;
            }else {
                return middleIndex;
            }
        }
        return -1; // No such element found
    }

}

Lambda simplifies the code writing of anonymous inner classes

Lambda expressions can only simplify the writing form of anonymous inner classes of functional interfaces

(The formal parameter list of the overridden method of the anonymous inner class) -> {
   The method body code of the overridden method.
}
Note:-> It is a grammatical form and has no actual meaning
package com.itheima.d9_lambda;

public class LambdaDemo2 {
    public static void main(String[] args) {
        // Objective: learn to use Lambda's standard format to simplify the code form of anonymous inner classes
        // Note: Lambda can only simplify the anonymous inner class form (functional interface) with only one abstract method in the interface
//        Swimming s1 = new Swimming() {
//            @Override
//            public void swim() {
//                System.out.println("the teacher swims and the thief slips ~ ~ ~");
//            }
//        };

//        Swimming s1 = () -> {
//            System.out.println("the teacher swims and the thief slips ~ ~ ~");
//        };

        Swimming s1 = () -> System.out.println("The teacher swims and the thief swims~~~~~");
        go(s1);

        System.out.println("---------------------");
//        go(new Swimming() {
//            @Override
//            public void swim() {
//                System.out.println("students have fun swimming ~ ~");
//            }
//        });

//        go(() ->{
//                System.out.println("students have fun swimming ~ ~");
//        });

        go(() -> System.out.println("The students have fun swimming~~~"));


    }

    public static void go(Swimming s){
        System.out.println("Start...");
        s.swim();
        System.out.println("end...");
    }
}

@FunctionalInterface // Once this annotation is added, it must be a functional interface, which can only have one abstract method
interface Swimming{
    void swim();
}

Omission of Lambda expression (further simplification on the basis of Lambda expression)

Parameter types can be omitted and not written.

If there is only one parameter, the parameter type can be omitted, and () can also be omitted.

If the method body code of a Lambda expression has only one line of code. You can omit the braces and omit the semicolon at the same time!

If the method body code of a Lambda expression has only one line of code. Braces can be omitted. At this time, if this line of code is a return statement, you must omit return and not write it. At the same time, you must also omit " Don't write

Keywords: Java Back-end

Added by if on Fri, 28 Jan 2022 12:26:11 +0200