What is Java? I would never learn Java

1. The comments

The importance of annotation is self-evident, no matter what code we write, annotation is essential, so Java annotation writing way and annotation template is how to proceed? Let’s see.

package frist;
/* * @description HelloWorld * @author wang Yanling **/
class HelloWorld {
    /* This is the main entry of our Java program. The main method is also the main thread of our program. * /
    public static void main(String[] arg)
    {
        / / output
       System.out.println("wyl"); }}Copy the code

1.1 annotations

As you can see above, There are three main types of Single-line comments in Java: only the current line can be commented, starting with // and ending with the line

 / / output

Copy the code

Multi-line comment: Comment a paragraph of text starting with /* and ending with */!

 /* This is the main entry of our Java program. The main method is also the main thread of our program. * /

Copy the code

Documentation comments: Used to produce API documentation that works with JavaDoc.

/* * @description HelloWorld * @author wang Yanling **/

Copy the code

1.2 IDEA Annotation Template Configuration

1.2.1 Define comments for Java file headers

File => setting => editor => File and Code Templates-class -Includes

${DATE} * Description Todo **/

Copy the code

This information is used when you create a class

1.2.2 Add annotations to methods in Java classes

First check Enable Live Templates. First check Enable Live Templates in the previous step

Step 2 Create a new Group. Step 2 Open LiveTemplates and create a new Group.

Type the name of the group you want, wyl, in the popup window

Where: Abbreviation is shortcut key. When w is entered, the corresponding method annotation template will be prompted, and j is the annotation template of the class

Click Edit Vaariables to select the corresponding dynamic value.

/ * * @ description: TODO * @ the author Wang Yanling 2021/7/12 * * @ time @ version 1.0 * /
public class wyl {
    /** * @description * @parameter [STR] *@ Return value [java.lang.string] *@ Creator Wang Yanling *@ Creation time 2021/7/12 *@ Modification and other information */
    public String CommentTemplate(String str)
    {
        returnstr; }}Copy the code

2. Key words

The keyword instructions
private One access control mode: private mode
protected One access control mode: protected mode
public One access control mode: shared mode
abstract Indicates that a class or member method has abstract properties
class class
extends Indicates that a type is a subtype of another type. Common types here are classes and interfaces
final Used to indicate final properties, indicating that a class cannot subclass, or that member methods cannot be overridden, or that the value of a member field cannot be changed
implements Indicates that a class implements a given interface
interface interface
native Used to declare that a method is implemented in a computer-related language such as C/C++/FORTRAN
new Used to create a new instance object
static Indicates a static property
strictfp Used to declare that an FP_strict (single-precision or double-precision floating point number) expression complies with the IEEE 754 arithmetic specification
synchronized Indicates that a piece of code needs to be executed synchronously
transient Declare a member domain that is not serialized
volatile Indicates that two or more variables must change synchronously
break Jump a block ahead of time
continue Go back to the beginning of a block
return Returns data from a member method
do Used in a do-while loop
while Used in loop structures
if The lead word of a conditional statement
else Used in conditional statements to indicate a branch when the condition is not set
for A leading word for a circular structure
instanceof Tests whether an object is an instance object of the specified type
switch A guide word for a branch statement structure
case Used in a switch statement to represent one of its branches
default The default, for example, in switch statements, indicates a default branch
try Try a block that might throw an exception
catch Used in exception handling to catch exceptions
throw Throw an exception
throws Declares all exceptions that need to be thrown in the currently defined member method
import Indicates that you want to access the specified class or package
package package
boolean One of the basic data types, the Boolean type
byte One of the basic data types, the byte type
char One of the basic data types, the character type
double One of the basic data types, the double – precision floating – point type
float One of the basic data types, the single-precision floating-point type
int One of the basic data types, the integer type
long One of the basic data types, long integer type
short One of the basic data types, the short integer type
super A reference to or constructor for the parent type of the current object
this A reference to the current instance object
void Declares that the current member method has no return value
goto Reserved keywords without specific meanings
const Reserved keywords without specific meanings

3. Data types

3.1. Data type conversion

3.1.1 Automatic Type conversionAutomatic type conversion: Data types with small capacity can be automatically converted to data types with large capacity.

3.1.2 Cast A cast, also known as a cast, is used to explicitly convert a numeric type to a type. The conversion method is :(type)var. Type in operator “()” indicates the target data type to which the value var is to be converted. The condition is that the converted data types must be compatible.

double x = 3.14;
int nx = (int)x; / / value is 3
char c = 'a';
int d = c+1;
System.out.println(d); / / 98
System.out.println((char)d); //b

Copy the code

3.1.3. Wrapper class transition type conversion

  • Eg1: int I = Integer. ParseInt (” 123 “)

Note: This method can only be used to convert a string to an integer variable

  • Eg2: float f = float. The valueOf (” 123 “). FloatValue ()

In this example, we convert a string to a Float object and then call the floatValue() method to return its Float value.

  • Eg3: Boolean b = Boolean. The valueOf (” 123 “). BooleanValue ()

This example converts a string to a Boolean object, and then calls the object’s booleanValue() method to return its Boolean value.

  • Eg4: double d = double. The valueOf (” 123 “). Doublue ()

The above example converts a string to a Double object, and then calls the object’s doublue() method to return its corresponding Double value.

  • Eg5: long l = long. The valueOf (” 123 “). LongValue ()

The above example converts a string to a Long object, and then calls the object’s longValue() method to return its corresponding Long value.

  • Eg6: char = Character. The valueOf (” 123 “). CharValue ()

The above example converts a string to a Character object

++++++++++++++++++++++++++++++++++++++++++++++++++++++

4. Constants, variables, operators

constant

What is a variable? It’s something that can change! We manipulate the data in the storage space through variables, and variables refer to the storage space! The spatial position is determined, but the value is not determined! Java is a strongly typed language, and every variable must have its type declared.

// Data type variable name = value; Multiple variables of the same type can be declared separated by commas.

Copy the code

Note: Each variable has a type, which can be a primitive or a reference type. The variable name must be a valid identifier. A variable declaration is a complete statement, so each declaration must end with a semicolon. A variable scope class variable (static variable: static variable) : a variable that is independent of a method. Instance variable (member variable: member variable) : a variable independent of a method, but without the static modifier. Lacal variables: Variables in a method of a class.

variable

Constant: The value cannot be changed after initialize! Values that do not change.

finalConstant name = value;final double PI=3.14;

Copy the code

Naming conventions

  1. All variables, methods, and class names: they are known by their names
  2. Class member variables: lowercase and hump principle: monthSalary
  3. Local variables: lowercase and the hump rule
  4. Constants: uppercase and underscore: MAX_VALUE
  5. Class name: Uppercase and hump principle: Man, GoodMan
  6. Method name: Lowercase and hump Rules: run(), runRun()

The operator

The Java language supports the following operators: arithmetic operators: +, -,, /, %, ++, — Assignment operators = relational operators: >, <, >=, <=, ==,! = instanceof logical operators, &&, | |,! Operator: &, | ^. ~, > >, < <, > > > (understand!!!) Conditional operators? : Extends assignment operators :+=, -=, =, /=

Java flow control

if… Else, while, do… While, for, switch… Case is not too tiring here. Return returns from a method and gives control to the calling sequence; Or simply end the current program; In the for, while, and do while loops, the break statement is often used to force out of the current loop; The continue continue statement is used to skip this loop and execute the next one;

Method 6.

So what is the method? Java methods are collections of statements that together perform a function. A method is an ordered combination of steps to solve a class of problems. A method is contained in a class or object. Methods are created in a program and referenced elsewhere. When we design the method, it is best to keep the atomicity of the method, that is, one method only completes one function, which is conducive to our later expansion. The advantages of the method make the program shorter and clearer. Good for program maintenance. Can improve the efficiency of program development. Improved code reuse.

define

Return value type method name (parameter type parameter name){... Method body... creturnThe return value. }Copy the code

** modifier: The ** modifier, which is optional, tells the compiler how to call the method. Defines the access type for the method. ** Return value type: ** methods may return values. ReturnValueType is the data type of the value returned by the method. Some methods perform the desired action but return no value. In this case, returnValueType is the keyword void. ** method name: ** is the actual name of the method. The method name and parameter list together form the method signature. ** Argument type: ** Argument is like a placeholder. When a method is called, the value is passed to the parameter. This value is called an argument or variable. The parameter list refers to the type, order, and number of parameters of a method. Arguments are optional, and methods can contain no arguments. Formal parameters: Data used to receive external input when a method is called. Argument: The data actually passed to the method when it is called. ** Method body: The ** method body contains specific statements that define the function of the method.

Method overloading

This means that two methods of a class have the same name, but have different argument lists.

Variable parameter

In the method declaration, add an ellipsis (…) after the parameter type. . Only one variable parameter can be specified in a method, and it must be the last parameter of the method. Any ordinary parameter must be declared before it.

typeName... parameterName

Copy the code

recursive

Call yourself

An array of 7.

Array definition:

An array is an ordered collection of data of the same type. An array describes several pieces of data of the same type arranged in a certain order. Where each piece of data is called an array element, and each array element can be accessed by a subscript.

Arrays have four basic features:

  1. Its length is certain. Once an array is created, its size cannot be changed.
  2. The elements must be of the same type, with no mixed types allowed.
  3. The elements in an array can be any data type, including primitive and reference types.
  4. Array variables are reference types. Arrays can also be thought of as objects. Each element in an array corresponds to a member variable of that object

The array declaration

dataType[] arrayRefVar; // The preferred methodOr the dataType arrayRefVar [];// Has the same effect, but is not the preferred method

Copy the code

Create an array

arrayRefVar = new dataType[1 arraySize];

Copy the code

The elements of an array are accessed by index. The array index starts at 0, so the index value goes from 0 to ArrayRefvar.length-1.

Three initializations

In addition to generating arrays with the new keyword, static initializers can allocate space and assign values to array elements as they are defined.

int[] a = {1.2.3};
Man[] mans = {new Man(1.1),new Man(2.2)};

Copy the code

Dynamically initializes array definitions, allocates space for array elements, and assigns values separately.

int[] a = new int[2];
a[0] =1;
a[1] =2;

Copy the code

The default array initializer is a reference type whose elements are equivalent to instance variables of the class, so once an array is allocated, each element is implicitly initialized in the same way as an instance variable.

public static void main(String[] args) {
int[] a=new int[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
System.out.println(a[0] +":"+a[1]); / / 0, 0
System.out.println(b[0] +":"+b[1]); //false,false
System.out.println(s[0] +":"+s[1]); //null, null
}

Copy the code

Array bounds

The legal interval of the subscript is [0, length-1]. If the subscript is out of bounds, an error will be reported.

For and for-each loops

for(type element: array){
System.out.println(element);
}

Copy the code
for (int i = 1; i < myList.length; i++) {
System.out.println(myList[i]);
}

Copy the code

Multidimensional array

type[][] typeName = new type[typeLength1][1 typeLength2];

Copy the code

The Arrays class

The Java.util.Arrays class makes it easy to manipulate Arrays. Guide package is required before use! Assign to an array: Use the fill method. Sort arrays: By sort method, in ascending order. Compare arrays: Compares the values of the elements in an array using equals. Find array elements: binarySearch can be used to find sorted arrays. Convert to list: Convert via asList(a)

8. Object oriented

Everything is an object!! An object is a concrete instance of an abstract concept.

Organizing code as a class and organizing (encapsulating) data as objects is object orientation

inheritance

Inheritance is a cornerstone of Java object-oriented programming techniques because it allows the creation of hierarchical classes.

classThe parent class {
}
classA subclassextendsThe parent class {
}

public interface A {
    public void eat(a);
    public void sleep(a);
}

public interface B {
    public void show(a);
}

public class C implements A.B {
}

Copy the code

Why inheritance? Because there is duplication. That’s why we inherited it, and then we know. A parent class is a definition or rule of the common part

Java does not support multiple inheritance (only one class can be inherited), but multiple inheritance is supported.

The characteristics of

  • A subclass has attributes and methods that are not private for its parent class.

  • Subclasses can have their own properties and methods, that is, they can extend their parent class.

  • Subclasses can implement the methods of their parent class in their own way.

  • Java inheritance is single inheritance, but it can be multiple inheritance. Single inheritance means that A subclass can inherit only one parent class. Multiple inheritance means that, for example, class B inherits class A, and class C inherits class B. This is a feature that distinguishes Java inheritance from C++ inheritance.

  • Improved coupling between classes (a drawback of inheritance, high coupling results in closer code connections and less code independence)

Super and this keyword

class Animal {
  void eat(a) {
    System.out.println("animal : eat"); }}class Dog extends Animal {
  void eat(a) {
    System.out.println("dog : eat");
  }
  void eatTest(a) {
    this.eat();   // this calls its own method
    super.eat();  // super calls the superclass method}}public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = newDog(); d.eatTest(); }}Copy the code
animal : eat
dog : eat
animal : eat

Copy the code

Final keyword Final keyword declaration classes can define a class as not inheritable, that is, the final class;

class SuperClass {
  private int n;
  SuperClass(){
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    System.out.println("SuperClass(int n)");
    this.n = n; }}// SubClass class inheritance
class SubClass extends SuperClass{
  private int n;

  SubClass(){ // Automatically calls the parent class's no-argument constructor
    System.out.println("SubClass");
  }  

  public SubClass(int n){ 
    super(300);  // Call the constructor with arguments in the parent class
    System.out.println("SubClass(int n):"+n);
    this.n = n; }}// SubClass2 class inherits
class SubClass2 extends SuperClass{
  private int n;

  SubClass2(){
    super(300);  // Call the constructor with arguments in the parent class
    System.out.println("SubClass2");
  }  

  public SubClass2(int n){ // Automatically calls the parent class's no-argument constructor
    System.out.println("SubClass2(int n):"+n);
    this.n = n; }}public class TestSuperSub{
  public static void main (String args[]){
    System.out.println("------SubClass class inheritance ------");
    SubClass sc1 = new SubClass();
    SubClass sc2 = new SubClass(100); 
    System.out.println("------SubClass2 class inherit ------");
    SubClass2 sc3 = new SubClass2();
    SubClass2 sc4 = new SubClass2(200); }}Copy the code
------SubClass class inheritance ------ SuperClass()SubClass
SuperClass(int n)
SubClass(int n):100 ------SubClass2 inherits ------SuperClass(int n)
SubClass2
SuperClass(a)
SubClass2(int n): 200Copy the code

The constructor

A subclass does not inherit a constructor (constructor or constructor) from its parent; it simply calls (implicitly or explicitly). If the parent class’s constructor takes parameters, the parent class’s constructor must be explicitly called in the subclass’s constructor via the super keyword with the appropriate argument list.

If the superclass constructor has no arguments, then there is no need to call the superclass constructor in the subclass’s constructor with the super keyword, and the system automatically calls the no-arguments constructor of the superclass.

Overrides and Overload

Rewrite (Override)

Overrides are subclasses that rewrite the implementation of the parent class’s accessible methods without changing either the return value or the parameter. That is, the shell is unchanged, the core is rewritten

class Animal{
   public void move(a){
      System.out.println("Animals can move"); }}class Dog extends Animal{
   public void move(a){
      System.out.println("Dogs can run and walk."); }}public class TestDog{
   public static void main(String args[]){
      Animal a = new Animal(); / / Animal object
      Animal b = new Dog(); / / Dog
      a.move();// Execute the Animal class method
      b.move();// Execute the Dog class method}}Copy the code
Animals can move and dogs can run and walkCopy the code

Method rewrite rules

  • The argument list must be exactly the same as the argument list of the method being overridden.

  • The return type can be different from the return type of the overridden method, but it must be a derivative of the value returned by the parent class (Java5 and earlier must have the same return type, and Java7 and later can be different).

  • Access cannot be lower than that of the overridden method in the parent class. For example, if a method of a parent class is declared public, overriding that method in a subclass cannot declare it protected.

  • A member method of a parent class can only be overridden by its subclasses.

  • Methods declared final cannot be overridden.

  • Methods declared static cannot be overridden, but can be declared again.

  • If a subclass is in the same package as its parent, it can override all methods of its parent except those declared private and final.

  • If a subclass and its parent are not in the same package, a subclass can override only non-final methods declared public and protected by the parent class.

  • An overridden method can throw any optional exception, whether or not the overridden method throws an exception. However, overridden methods cannot throw new mandatory exceptions, or more extensive exceptions than those declared by the overridden method, or vice versa.

  • The constructor cannot be overridden.

  • If you cannot inherit from a class, you cannot override the methods of that class.

Overloading (phrase)

Overloading is when methods in a class have the same name but different parameters. The return types can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most common place is constructor overloading.

public class Overloading {
    public int test(a){
        System.out.println("test1");
        return 1;
    }

    public void test(int a){
        System.out.println("test2");
    }   

    // The following two parameters are in different order
    public String test(int a,String s){
        System.out.println("test3");
        return "returntest3";
    }   

    public String test(String s,int a){
        System.out.println("test4");
        return "returntest4";
    }   

    public static void main(String[] args){
        Overloading o = new Overloading();
        System.out.println(o.test());
        o.test(1);
        System.out.println(o.test(1."test3"));
        System.out.println(o.test("test4".1)); }}Copy the code

Overload rules:

  • Overloaded methods must change their argument lists (with different numbers or types of arguments);

  • Overloaded methods can change the return type;

  • Overloaded methods can change access modifiers;

  • Overloaded methods can declare new or broader check exceptions;

  • Methods can be overridden in the same class or in a subclass.

  • Overloaded functions cannot be distinguished by return value types.

    The mark Overloaded methods Overriding methods
    The list of parameters Must be modified It must not be modified
    The return type You can modify It must not be modified
    abnormal You can modify You can reduce or delete exceptions, and must not throw new or broader exceptions
    access You can modify It must not be more restrictive (it can be lower)

polymorphism

Polymorphism is the ability to have many different manifestations or forms of the same behavior.

Polymorphism is the same interface, using different instances to perform different operations.

Polymorphism is the manifestation of multiple forms of objects.

The advantages of polymorphism

  1. Decouple the types
  2. replaceability
  3. scalability
  4. Interface,
  5. flexibility
  6. Simplify the sex

Three necessary conditions for the existence of polymorphism

Parent p = new Child();

class Shape {
    void draw(a) {}}class Circle extends Shape {
    void draw(a) {
        System.out.println("Circle.draw()"); }}class Square extends Shape {
    void draw(a) {
        System.out.println("Square.draw()"); }}class Triangle extends Shape {
    void draw(a) {
        System.out.println("Triangle.draw()"); }}Copy the code

Virtual functions

Virtual functions exist for polymorphism.

In fact, Java does not have the concept of virtual functions, its ordinary functions are equivalent to C++ virtual functions, dynamic binding is the default behavior of Java. If you do not want a function to have virtual function properties in Java, you can add the final keyword to make it non-virtual.

The implementation of polymorphism

Method 1: Rewrite:

Mode 2: Interface

Method three: Abstract classes and methods

An abstract class

Classes that have abstract methods are called abstract classes, which are declared using the abstract keyword.

abstract class A{// Define an abstract class
	public void fun(a){// Common method
		System.out.println("A method that exists a method body.");
	}
	public abstract void print(a);// An abstract method has no method body and is modified with the abstract keyword

}

Copy the code

Inheriting abstract classes

We can inherit the attributes of the Employee class in the following way

(1) An abstract method must be public or protected (because if it is private, it cannot be inherited by a subclass and the subclass cannot implement the method). By default, the method must be public. (2) Abstract classes cannot be instantiated directly, and need to rely on the subclass to adopt the way of upward transformation; (3) An abstract class must have a subclass. Using extends extends, a subclass can inherit only one abstract class. (4) A subclass (if not an abstract class) must override all abstract methods in the abstract class. (If the subclass does not implement the abstract methods of the parent class, the subclass must also be defined as an abstract class.) ;

package com.wz.abstractdemo;

abstract class A{// Define an abstract class

	public void fun(a){// Common method
		System.out.println("A method that exists a method body.");
	}

	public abstract void print(a);// An abstract method has no method body and is modified with the abstract keyword

}
/ / single inheritance
class B extends A{// Class B is a subclass of an abstract class

	@Override
	public void print(a) {// Override mandatory
		System.out.println("Hello World !"); }}public class TestDemo {

	public static void main(String[] args) {
		A a = new B();// Upward transition

		a.print();// The method overridden by the subclass}}Copy the code
Hello World !

Copy the code

encapsulation

Encapsulation refers to a method of wrapping and hiding the implementation details of an abstract function interface.

Encapsulation can be thought of as a protective barrier that prevents the code and data of this class from being randomly accessed by code defined by an external class.

Access to the code and data of this class must be controlled through a strict interface.

The main feature of encapsulation is that we can modify our own implementation code without modifying the snippets that call our code.

Proper encapsulation makes code easier to understand and maintain, and also enhances code security.

Advantages of encapsulation

  1. Good encapsulation reduces coupling.
  2. The structure inside the class can be modified freely.
  3. You can have more precise control over member variables.
  4. Hide information and implement details.

interface

In the JAVA programming language, an abstract type is a collection of abstract methods, usually declared as an interface. A class inherits the abstract methods of an interface by inheriting an interface.

Interface and class similarity

  1. An interface can have multiple methods.
  2. Interface files are stored in files ending in.java, and the filename uses the interface name.
  3. The bytecode file for the interface is saved in a file at the end of.class.
  4. The bytecode file corresponding to the interface must be in the directory structure that matches the package name.

The difference between interfaces and classes

  1. Interfaces cannot be used to instantiate objects.
  2. The interface has no constructor.
  3. All methods in an interface must be abstract methods. After Java 8, non-abstract methods can be modified with the default keyword in an interface.
  4. Interfaces cannot contain member variables, except static and final variables.
  5. Interfaces are not inherited by classes; they are implemented by classes.
  6. Interfaces support multiple inheritance.

Interface features

  1. Each method in the interface is also implicitly abstract. Methods in the interface are implicitly specified as public abstract (only public abstract; other modifiers will return an error).
  2. An interface can contain variables, but variables in the interface are implicitly specified as public static final variables (and only public; using the private modifier raises a compilation error).
  3. Methods in an interface cannot be implemented in an interface, only by the class that implements the interface.

The difference between abstract classes and interfaces

  1. Methods in an abstract class can have a method body, which implements the specific functionality of the method, but not methods in an interface.

  2. Member variables in an abstract class can be of various types, whereas member variables in an interface can only be of public static final type.

  3. Interfaces cannot have static code blocks and static methods (methods decorated with static), whereas abstract classes can have static code blocks and static methods

  4. A class can inherit only one abstract class, while a class can implement multiple interfaces.

[visibility] interface Interface name [extends other interface name] {// Declare variables
        // Abstract methods
}

Copy the code
/* 文件名 : NameOfInterface.java */
import java.lang.*;
/ / into the bag

public interface NameOfInterface
{
   // Final, static fields of any type
   // Abstract methods
}

Copy the code

Interfaces have the following features

  • Interfaces are implicitly abstract and do not use the abstract keyword when declaring an interface.
  • Each method in the interface is also implicitly abstract and does not require the abstract keyword when declared.
  • The methods in the interface are public.

The enumeration

Enumeration is a special class that typically represents a set of constants. Each enumeration is implemented internally via Class, and all enumeration values are public static final.

enum Color
{
    RED, GREEN, BLUE;
}

public class Test
{
    // Execute the output
    public static void main(String[] args)
    { Color c1 = Color.RED; System.out.println(c1); }}Copy the code
RED

Copy the code

Values (), ordinal() and valueOf() methods

Enum classes defined by enum inherit the java.lang. enum class by default and implement java.lang.Comparable interfaces.

The values(), ordinal(), and valueOf() methods are in the java.lang.enum class:

  • Values () returns all the values in the enumeration class.

  • The ordinal() method finds the index of each enumerated constant, just like an array index.

  • The valueOf() method returns an enumeration constant of the specified string value.

    enum Color
    {
        RED, GREEN, BLUE;
    }
    
    public class Test
    {
        public static void main(String[] args)
        {
            / / call the values ()
            Color[] arr = Color.values();
            // Iteration enumeration
            for (Color col : arr)
            {
                // Check the index
                System.out.println(col + " at index " + col.ordinal());
            }
            // Use valueOf() to return enumeration constants. Nonexistent IllegalArgumentException is reported
            System.out.println(Color.valueOf("RED"));
            // System.out.println(Color.valueOf("WHITE"));}}Copy the code
    RED at index 0
    GREEN at index 1
    BLUE at index 2
    RED
    
    Copy the code

    Members of the enumeration

    Enumerations can have their own variables, methods, and constructors just like normal classes. Constructors can only use private access modifiers, so they cannot be called externally.

    enum Color
    {
        RED, GREEN, BLUE;
    
        // constructor
        private Color(a)
        {
            System.out.println("Constructor called for : " + this.toString());
        }
        public void colorInfo(a)
        {
            System.out.println("Universal Color"); }}Copy the code

Package (package)

To better organize classes, Java provides a package mechanism that distinguishes the namespaces of class names.

The three functions of packages are as follows

  1. Distinguish between classes with the same name.

  2. Can manage a large number of classes well.

  3. Control access range.

define

 ```java

Copy the code

Package the package name;

Java package naming rules are as follows: * Package names are all lowercase letters (and multiple words are all lowercase). * If the package name contains multiple levels, use "for each level. Segmentation. * Package names usually start with inverted domain names, such as com.baidu, do not have WWW. * Custom packages cannot start with Java ** package import **Copy the code

Example.Test Test = new example.test ();

' 'c \\import package name + class name; import example.Test; \\or import example.*;Copy the code

The system package

package instructions
java.lang The Java core class library contains essential system classes for running Java programs, such as basic data types, basic mathematical functions, string handling, exception handling, and thread classes. The system loads this package by default
java.io Standard INPUT/output libraries for the Java language, such as basic input/output streams, file input/output, filtered input/output streams, and so on
java.util Contains classes such as Date for handling time, Vector for handling dynamic arrays, and Stack and HashTable
java.awt Libraries for building graphical user interfaces (GUIs), low-level Graphics classes for drawing operations, GRAPHICAL interface components, and layout management (such as Checkbox classes, Container classes, LayoutManger interfaces, and so on), as well as user interface interaction controls and Event responses (such as the Event class)
java.awt.image Java utility class library for processing and manipulating images from the web
java.wat.peer Rarely used directly in programs, making the same Java program run on different hardware and software platforms
java.net The network functions of the library have Socket class, ServerSocket class
java.lang.reflect Provides tools for reflecting objects
java.util.zip Implement file compression
java.awt.datatransfer Utility classes that handle data transfer, including clipboards, string transmitters, and so on
java.sql Implement JDBC class library
java.rmi Provides remote connection and loading support
java. security Provide security support

9. Exception handling

The concept of exception handling

A mechanism in a programming language or computer hardware to handle anomalies in software or information systems (special conditions that go beyond the normal flow of a program).

The keyword

The Java exception mechanism uses the following keywords: try, catch, finally, throw, throws.

Try — for listening. The code to be listened on (code that might throw an exception) is placed inside the try block, and when an exception occurs within the try block, the exception is thrown. Catch — Used to catch exceptions. Catch is used to catch exceptions that occur in a try block. Finally — Finally blocks are always executed. It is primarily used to reclaim physical resources (such as database connections, network connections, and disk files) that are opened in the try block. Only a finally block will return to execute a return or throw statement ina try or catch block. If a statement terminates a method such as a return or throw is used in the finally block, it will not jump back to execution. Throw — Used to throw an exception. Throws — used in a method signature to declare exceptions that the method may throw.

 try{exceptions that may occur}catch(Exception type Exception name (variable)){code for handling exceptions}catch(Exception type Exception name (variable)){code for handling exceptions}... [finally{release resource code;}]Copy the code

Error is different from Exception

An Error is an Error in the system that cannot be changed or handled by the programmer. It is an Error that occurs when the program is compiled and can only be corrected by modifying the program. It usually refers to problems related to virtual machine, such as system crash, virtual machine error, insufficient memory space, method call stack overflow, etc. The application interruption caused by such errors cannot be recovered and prevented by the program itself. It is recommended to terminate the program when such errors occur. Exception represents an Exception that a program can handle, catch, and possibly recover. When you encounter such exceptions, you should handle them as much as possible so that the program can resume running, rather than terminating them arbitrarily.

Throws is different from throws

Throw: to artificially throw an exception object in a method (this exception object may be self-instantiated or thrown to an existing one);throw ThrowableInstance;Throws: Used on the declaration of a method to indicate that the method must handle exceptions when called.throw new NullPointerException("demo");

Java Exception Hierarchy Diagram (Available online)

10. Collection framework

All collection classes are located under the java.util package. Java’s Collection classes are derived primarily from two interfaces: Collection and Map, which are the root interfaces of the Java Collection framework, and which in turn contain subinterfaces or implementation classes.

The collection framework is designed to meet the following goals:

  • The framework must be high-performance. The implementation of basic collections (dynamic arrays, linked lists, trees, hashes) must also be efficient.
  • The framework allows different types of collections to work in a similar way with a high degree of interoperability.
  • The extension and adaptation of a collection must be simple.

The collection framework contains the following:

  • ** interface: ** is an abstract data type that represents a collection. For example, Collection, List, Set, and Map. Multiple interfaces are defined to manipulate collection objects in different ways

  • ** implementations (classes) : ** is a concrete implementation of the collection interface. In essence, they are reusable data structures, such as ArrayList, LinkedList, HashSet, HashMap.

  • ** algorithms: ** are useful calculations performed by methods in objects that implement the collection interface, such as searching and sorting. These algorithms are called polymorphic because the same method can have different implementations on similar interfaces.

Collection is a basic Collection interface that can hold a set of elements in a Collection.

The Collection interface

Collection is the most basic Collection interface. A Collection represents a group of objects, that is, the elements of a Collection. Java does not provide classes that directly inherit from a Collection, but only subinterfaces (such as List and set) that inherit from a Collection.

List

The List interface is an ordered, repeatable Collection of elements, with precise control over where each element is inserted, and access to elements in the List by index (element position in the List, similar to the subscript of an array). The first element has an index of 0 and is allowed to have the same element.

  1. ArrayList

The underlying data structure is an array, which is fast to check and change, slow to add and delete.

Non – thread safe, high efficiency

Methods:

The sorting

import java.util.Collections;  // Introduce the Collections class
Collections.sort(sites); *// alphabetical *

Copy the code
  1. Vector

The underlying data structure is an array, which is fast to check and change, slow to add and delete.

Thread safety and low efficiency

  1. LinkedList

The underlying data structure is linked list, check change slow, add and delete fast.

Non – thread safe, high efficiency

Use LinkedList for the following situations:

  • You need to iterate through the loop to access certain elements in the list.
  • You need to frequently add and remove elements at the beginning, middle, and end of the list.

LinkedList descends from the AbstractSequentialList class.

LinkedList implements the Queue interface and can be used as a Queue.

LinkedList implements the List interface for list-related operations.

LinkedList implements the Deque interface and can be used as a queue.

LinkedList implements the Cloneable interface for cloning.

LinkedList implements the Java.io.Serializable interface, which supports serialization and can be transmitted via serialization.

Methods:

Set

The Set interface stores a unique, unordered Set of objects.

  1. HashSet

The underlying data structure is a hash table. (Unordered **, only **)

We rely on two methods: hashCode() and equals() to ensure element uniqueness

// Introduce the HashSet class
import java.util.HashSet;

public class RunoobTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Runoob");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Runoob");  // Duplicate elements will not be addedSystem.out.println(sites); }}Copy the code

The above code outputs only one Runoob.

  1. LinkedHashSet

The underlying data structures are linked lists and hash tables. (FIFO insert in order, unique)

1. The order of elements is guaranteed by linked lists

2. Hash tables ensure that elements are unique

  1. TreeSet

The underlying data structure is a red-black tree. (Unique, ordered)

How do you make sure the elements are sorted? Natural sort, comparator sort

The difference between Set and List

  • The Set interface instance stores unordered, non-repeating data. The List interface instance stores ordered, repeatable elements.
  • Set retrieval is inefficient, and deletion and insertion are efficient, and insertion and deletion do not cause element positions to change.
  • A List, like an array, can grow dynamically, depending on the size of the data actually stored. Find the elements with high efficiency, low insert removing efficiency, because can lead to other elements position change < ArrayList implementation class, LinkedList, the Vector >.

Map and Collection are juxtaposed. A Map provides the mapping of keys to values. Each Map cannot contain the same key, and each key can Map only one value.

  1. HashMap

Unordered, non-thread-safe, efficient. The HashMap allows null values (both key and value).

  1. HashTable

Disorder, thread safety, low efficiency. Except for constructors, the synchronized keyword is in all public method declarations of HashTable, but not in the source code of HashMap. HashTable does not allow null values (both key and value are allowed).

  1. TreeMap

Ordered, non-thread-safe, efficient (O(logN)), but not as efficient as HashMap (O(1)).

Streams, files, and IO

The java.io package defines multiple stream types (classes or abstract classes) to implement input/output functionality;

Data streams can be classified into InputStream (byte stream), Reader (character stream) and OutPutStream (character stream) (Writer). It can be divided into Byte streams (a Byte is 8 bits) and character streams (a character is 2 bytes) 3 according to the unit of data processed. According to different functions, it can be divided into node flow and processing flow

[image upload failed…(image-da6CBD-1628583810189)]

4. Perform operations by object

InputStream and OutputStream

import java.io.*;

public class fileStreamTest {
    public static void main(String[] args) {
        try {
            byte bWrite[] = { 11.21.3.40.5 };
            OutputStream os = new FileOutputStream("test.txt");
            for (int x = 0; x < bWrite.length; x++) {
                os.write(bWrite[x]); // writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for (int i = 0; i < size; i++) {
                System.out.print((char) is.read() + "");
            }
            is.close();
        } catch (IOException e) {
            System.out.print("Exception"); }}}Copy the code

The above program first creates a file called test.txt and writes the given number in binary form to the file and prints it to the console.

Because the above code is written in binary, there may be garbled characters, you can use the following code example to solve the garbled problem:

// The file name is filestreamtest2.java
import java.io.*;

public class fileStreamTest2 {
    public static void main(String[] args) throws IOException {
        File f = new File("a.txt");
        FileOutputStream fop = new FileOutputStream(f);
        // Build FileOutputStream. If a file does not exist, it will be created automatically
        OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
        // Build an OutputStreamWriter object. The encoding can be specified. The default is the operating system default encoding, which is GBK on Windows
        writer.append("Chinese input");
        // Write to buffer
        writer.append("\r\n");
        / / a newline
        writer.append("English");
        // Flush the cache, write to the file, if there is no writing below, direct close will also write
        writer.close();
        // Turn off the write stream, while writing the buffer contents to the file, so comment out the above
        fop.close();
        // Close the output stream to release system resources
        FileInputStream fip = new FileInputStream(f);
        // Build the FileInputStream object
        InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
        // Construct the InputStreamReader object, encoding the same as writing
        StringBuffer sb = new StringBuffer();
        while (reader.ready()) {
            sb.append((char) reader.read());
            // Char is added to the StringBuffer object
        }
        System.out.println(sb.toString());
        reader.close();
        // Close the read stream
        fip.close();
        // Close the input stream to release system resources}}Copy the code

Reader flow and Writer flow

InputStream, OutputStream, InputStream, InputStream, InputStream, InputStream, InputStream, InputStream, InputStream

Create read directory:

import java.io.File;

public class CreateDir {
    public static void main(String[] args) {
        String dirname = "/tmp/user/java/bin";
        File d = new File(dirname);
        // Now create the directoryd.mkdirs(); }}Copy the code
import java.io.File;

public class DirList {
    public static void main(String args[]) {
        String dirname = "/tmp";
        File f1 = new File(dirname);
        if (f1.isDirectory()) {
            System.out.println("Directory" + dirname);
            String s[] = f1.list(a);for (int i = 0; i < s.length; i++) {
                File f = new File(dirname + "/" + s[i]);
                if (f.isDirectory()) {
                    System.out.println(s[i] + "It's a catalog.");
                } else {
                    System.out.println(s[i] + "It's a file."); }}}else {
            System.out.println(dirname + "Not a directory."); }}}Copy the code

delete

import java.io.File;

public class DeleteFileDemo {
    public static void main(String[] args) {
        // Change this to your own test directory
        File folder = new File("/tmp/java/");
        deleteFolder(folder);
    }

    // Delete files and directories
    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if(files ! = null) {for (File f : files) {
                if (f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete(a); } } } folder.delete();
    }
}

Copy the code

Cache flow

It is a type of processing flow that is “socket” on the corresponding node flow to buffer read/write data, avoiding frequent read/write to disks and improving read/write efficiency. Some new methods have also been added.

BufferedReader(Reader in)
BufferedReader(Reader in,int sz) //sz is the size of the custom buffer
BufferedWriter(Writer out)
BufferedWriter(Writer out,int sz)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in,int size)
BufferedOutputStream(InputStream in)
BufferedOutputStream(InputStream in,int size)

Copy the code

BufferedInputStream

package com.kuang.chapter;
import java.io.*;
public class TestBufferStream {
public static void main(String args[]) {
FileInputStream fis = null;
File f = new File("a.txt");
try {
fis = new FileInputStream( f);
// wrap BufferedInputStream around the FileInputStream node stream
BufferedInputStream bis = new BufferedInputStream(fis);
int c = 0;
System.out.println((char) bis.read());
System.out.println((char) bis.read());
bis.mark(100);// Make a mark at the 100th character
for (int i = 0; i <= 10&& (c = bis.read()) ! =- 1; i++) {
System.out.print((char) c);
}
System.out.println();
bis.reset();// Return to the original mark
for (int i = 0; i <= 10&& (c = bis.read()) ! =- 1; i++) {
System.out.print((char) c);
}
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(Exception e1) { e1.printStackTrace(); }}}Copy the code

BufferedReader

package com.kuang.chapter;
import java.io.*;
public class TestBufferStream{
public static void main(String args[]){
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("a\\Student.txt"));
// Add a layer of BufferedWriter to the FileWriter node
String s = null;
for(int i=0; i<100; i++){ s = String.valueOf(Math.random());Math.random() will generate a series of random numbers between 0 and 1.
// Static String valueOf(double dadoubleThe number of type is converted to a string//valueOf() is a static method, so "type" can be used. Static method name
bw.write(s);// Write a random number string to the specified file
bw.newLine();// call the newLine() method so that each random number is written to a newLine
}
bw.flush();// Call flush() to flush the buffer
BufferedReader br = new BufferedReader(new FileReader("a:\\Student.txt"));
// Add a layer of BufferedReader to the node stream FileReader
while((s = br.readLine())! =null){// Use BufferedReader to read data line by line in the file provided by the String readLine() method in the stream
// The loop ends if the string returned by the readLine() method is nullIndicates that it has read to the end of the file. System.out.println(s); } bw.close(); br.close(); }catch(Exception e){ e.printStackTrace(); }}}Copy the code

Transformation flows

InputStreamReader and OutputStreamWriter are used to convert byte data to character data. InputStreamReader needs to “socket” with InputStream. OutputStreamWriter needs to “socket” with OutputStream. A transformation stream can specify its encoding set at construction time

import java.io.*;
public class TestTransform1 {
public static void main(String args[]) {
try {
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:/char.txt"));
    osw.write("Bear Square is so annoying.");// Write the string to the specified file
    System.out.println(osw.getEncoding());// Use the getEncoding() method to get the default character encoding for the current system
    osw.close();
    osw = new OutputStreamWriter(new FileOutputStream("D:\\java\\char.txt".true), "utf-8");// If true is not added when the FileOutputStream constructor is called, the newly added string replaces the original written string, specifying the character encoding when the constructor is called
    osw.write("I don't want to talk to her.");// Writes a string to the specified file again. The new string is appended to the original string
    System.out.println(osw.getEncoding());
    osw.close();
} catch(Exception e) { e.printStackTrace(); }}}Copy the code

The data flow

DataInputStream DataOutputStream (derived from InputStream and OutputStream, respectively), etc. – Provides the ability to write the underlying data type to a file or to read it out. Provides methods for accessing machine-independent Java primitive type data (int, double, etc.).

public static void main(String args[]){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// when the constructor is called, a ByteArray ByteArray is created in memory
DataOutputStream dos = new DataOutputStream(baos);
// Wrap a data stream around the output stream to handle ints and doubles
try{
    dos.writeDouble(Math.random());// Write the generated random number directly to the byte arrayByteArray containing in the DOS. WriteBoolean (true);// Booleans take up only one byte in memory
    ByteArrayInputStream bais = new
    ByteArrayInputStream(baos.toByteArray());
        System.out.println(bais.available());
    DataInputStream dis = new DataInputStream(bais);
    System.out.println(dis.readDouble());// Call readDouble() to read the written random number
    System.out.println(dis.readBoolean());// What is written in after is read out after. The read order cannot be changed, otherwise incorrect results will be printed
    dos.close();
    bais.close();
}catch(Exception e){ e.printStackTrace(); }}Copy the code

Printing flow

PrintStream is the most convenient class to output information. Note that it includes PrintStream, a byte PrintStream, and PrintWriter, a character PrintStream. Print stream provides very convenient printing function, can print any type of data information, such as: decimal, integer, string.

Object flow

The input/output streams of objects are used to write and read information about objects. Make the object persistent. ObjectInputStream: ObjectInputStream ObjectOutPutStream: ObjectOutPutStream

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

// Create a class to write to disk. This class needs to implement the interface Serializable
class Student implements Serializable{
    // The uniqueness of serialVersionUID is guaranteed here, preventing temporary changes to the attribute variable that could make the write ID different from the read ID
    private static final long serialVersionUID = 1L;
    int id ; // An additional attribute is required
    String name ;
    transient String sex; //transient modifier property, which means temporary, the property will not be written to disk
    transient int age;
    public Student(String name,String sex,int age){
        this.name = name;
        this.sex = sex;
        this.age = age; }}public class objectIO {

    /** * @param args * @throws IOException * @throws ClassNotFoundException */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub

        createObj();
        readObj();
    }
    // Write the object first
    public static void createObj(a) throws IOException {
        //1. Create a target path
        File file = new File("C:\\Users\\bg\\Desktop\\objTest.txt");
        //2. Create a channel
        FileOutputStream fos = new FileOutputStream(file);
        //3. Create an object output stream
        ObjectOutputStream objOP = new ObjectOutputStream(fos);
        //4. Create the class object and initialize it
        Student stu = new Student(Mary Sue."Male".18);
        //5. Write objects to the target path file
        objOP.writeObject(stu);
        //6. Close the resource
        objOP.close();
    }
    // Read the object again
    public static void readObj(a) throws IOException, ClassNotFoundException {
        File file = new File("C:\\Users\\bg\\Desktop\\objTest.txt");
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream objIP = new ObjectInputStream(fis);
        // To read object data, cast the object stream to the type of the object to be written to
        Student stu = (Student)objIP.readObject();
        System.out.println("\n name:"+stu.name+"\n sex:"+stu.sex+"\n age:"+stu.age); objIP.close(); }}Copy the code

The closing order of the stream

  1. Generally speaking, it is: the first open and then closed, and the first closed
  2. Another case: looking at dependencies, if stream A depends on stream B, you should close stream A first and then stream B. For example, if processing flow A depends on node flow B, you should shut down processing flow A and then node flow B
  3. You can just close the processing stream without closing the node stream. When a process stream is closed, the closing method of the node stream it is processing is called.

12. A multithreaded

Processes and threads

Thread creation

Inherit Thread class, Runnable interface, Callable interface

1. Inherit the Thread class

public class ThreadCreateDemo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // Call the start() method to start the thread, which may not execute immediately, and the CPU schedules it}}class MyThread extends Thread {// Inherit the Thread class
    @Override
    public void run(a) {// Override the run() method to write the thread body
        super.run();
        System.out.println("hellow_world!"); }}Copy the code

2. Implement the Runnable interface

public class ThreadCreateDemo2 {
    // Create a thread object and call the start() method to start the thread
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = newThread(runnable); thread.start(); }}class MyRunnable implements Runnable {
    public void run(a) {
        System.out.println("Thread created by Runnable!"); }}Copy the code

The above two creation methods work in the same way. However, implementing the Runable interface is recommended. Address the limitations of single inheritance.

3. Implement the Callable interface

public class ThreadCreateDemo3 implements Callable<Integer>{
    // Implement the call method as the thread body
    public Integer call(a){
        int i = 0;
        for(; i <100 ; i++ ){
            System.out.println(Thread.currentThread().getName()+ "\t" + i);
        }
        The call() method can have a return value
        return i;
    }
    public static void main(String[] args) {
        // Create a Callable object
        ThreadCreateDemo3 myCallableTest = new ThreadCreateDemo3();
        // Use FutureTask to wrap the Callable object
        FutureTask<Integer> task = new FutureTask<Integer>(myCallableTest);
        for (int i = 0 ; i < 100 ; i++){
            System.out.println(Thread.currentThread().getName()+ " \t" + i);
            if (i == 20) {// Threads are essentially created and started with Callable objects
                new Thread(task , "callable").start(); }}try{
            // Get the thread return value
            System.out.println("Callable return value:" + task.get());
        }
        catch(Exception ex){ ex.printStackTrace(); }}}Copy the code
  1. To implement the Callable interface, return value types are required

  2. To override the Call method, throw an exception

  3. Creating the target Object

  4. Create execution services: the ExecutorService ser = Executors. NewFixedThreadPool (1);

  5. Submit: Future result1 = ser.submit(t1);

  6. Boolean r1 = result1.get()

  7. Ser.shutdownnow (); conclusion

  8. The Runnable interface is implemented in much the same way as the Callable interface, except that methods defined in the Callable interface return values and can be declared to throw exceptions. Therefore, implementing the Runnable interface and implementing the Callable interface can be categorized as one way.

  9. The Runnable/Callable interface is used to create multiple threads, so it is ideal for multiple threads to process the same resource. To access the currentThread, thread.currentthread () must be used

  10. Threads are created by inheriting Thread classes, because Thread classes already inherit Thread classes, so they cannot inherit from other parent classes

The life cycle

Once a thread is created and started, it is neither in the execution state as soon as it is started, nor in the execution state as New, Runnable, Running, Blocked, and Dead

Thread. The State:

  1. Initial (NEW) : A NEW thread object is created, but the start() method has not yet been called.

  2. RUNNABLE: Java threads refer to the ready and running states as “RUNNABLE.” After the thread object is created, other threads, such as the main thread, call the start() method of the object. A thread in this state is in the runnable thread pool, waiting to be selected by thread scheduler for CPU usage, and is in the ready state. A thread in the ready state becomes running after obtaining a CPU time slice.

  3. BLOCKED: A thread is BLOCKED from a lock.

  4. WAITING: a thread in this state is WAITING for some specific action (notification or interrupt) from another thread.

  5. TIMED_WAITING: This state is different from WAITING. It can return after a specified time.

  6. TERMINATED: indicates that the thread is TERMINATED

Priority of the thread

Java provides a thread scheduler to monitor all threads in a program that are ready after startup, and the thread scheduler determines which thread should be scheduled for execution based on priority. The priority of a thread is represented by a number ranging from 1 to 10.hread.min_priority = 1; Thread.MAX_PRIORITY = 10; Thread.NORM_PRIORITY = 5; Change or get the priority getPriority().setPriority (int XXX)

Thread method

1 public void start()Causes the thread to start executing;JavaThe VIRTUAL machine invokes the run method of the thread.
2 public void run()If the thread is constructed using a separate Runnable run object, the Runnable object’s run method is called. Otherwise, the method does nothing and returns.
3 public final void setName(String name)Change the thread name to be the same as the parameter name.
4 public final void setPriority(int priority)Changes the priority of a thread.
5 public final void setDaemon(boolean on)Mark this thread as a daemon thread or a user thread.
6 public final void join(long millisec)The maximum time to wait for this thread to terminate is Millis milliseconds.
7 public void interrupt()Interrupt the thread.
8 public final boolean isAlive()Tests whether the thread is active.
9 public static void yield()Thread courtesy: Suspends the currently executing thread object and executes another thread.
10 public static void sleep(long millisec)Thread sleep: To hibernate (suspend execution) the currently executing thread for a specified number of milliseconds, subject to the precision and accuracy of the system timer and scheduler.
11 public static boolean holdsLock(Object x)Returns true if and only if the current thread holds the monitor lock on the specified object.
12 public static Thread currentThread()Returns a reference to the thread object currently executing.
13 public static void dumpStack()Prints the stack trace for the current thread to the standard error stream.

Stop threads: The JDK provides stop, but it is not recommended to stop it yourself

Daemon threads

Threads are classified into foreground threads and background threads (user threads and daemons). The VM must ensure that the user thread completes. The VM does not wait for the daemons thread to complete

Concurrency, queues and locks, deadlocks

Concurrency is the simultaneous operation of the same object by more than one thread.

Multiple threads access the same object and some threads want to modify the object. In this case, we need thread synchronization. Thread synchronization is actually a kind of waiting mechanism. Multiple threads that need to access the object at the same time enter the waiting pool of the object to form a queue, and wait for the previous thread to finish using it before the next thread can use it.

The above concurrency problem will be solved by adding a synchronized. No one comes in here while I lock the door. But with the lock, there will be the following:

  1. Holding a lock by one thread causes all other threads requiring the lock to suspend;

  2. In the multi-thread competition, locking and locking release will lead to more context switching and scheduling delay, resulting in performance problems;

  3. If a high-priority thread waits for a low-priority thread to release the lock, priority inversion can occur, causing performance problems.

    There are four necessary conditions for Java deadlocks to occur:

  • 1. Mutually exclusive use, that is, when a resource is used by one thread, other threads cannot use it

  • 2. No preemption. The resource requester cannot forcibly seize the resource from the resource possessor, and the resource can only be released by the resource possessor.

  • 3. Request and hold, that is, when the resource requester requests other resources while maintaining the possession of the original resource.

  • 4. Cyclic waiting, that is, there is a waiting queue: P1 occupies P2 resources, P2 occupies P3 resources, and P3 occupies P1 resources. This creates a waiting loop.

    If any of these conditions are broken in the case of a deadlock, the deadlock disappears.

import java.util.Date;

public class LockTest {
   public static String obj1 = "obj1";
   public static String obj2 = "obj2";
   public static void main(String[] args) {
      LockA la = new LockA();
      new Thread(la).start();
      LockB lb = new LockB();
      newThread(lb).start(); }}class LockA implements Runnable{
   public void run(a) {
      try {
         System.out.println(new Date().toString() + "Start LockA execution");
         while(true){
            synchronized (LockTest.obj1) {
               System.out.println(new Date().toString() + "LockA locks obj1");
               Thread.sleep(3000); // Wait here to give B a chance to lock up
               synchronized (LockTest.obj2) {
                  System.out.println(new Date().toString() + "LockA locks obj2");
                  Thread.sleep(60 * 1000); // For testing purposes}}}}catch(Exception e) { e.printStackTrace(); }}}class LockB implements Runnable{
   public void run(a) {
      try {
         System.out.println(new Date().toString() + "LockB start execution");
         while(true){
            synchronized (LockTest.obj2) {
               System.out.println(new Date().toString() + "LockB locks obj2");
               Thread.sleep(3000); // Wait here to give A A chance to lock
               synchronized (LockTest.obj1) {
                  System.out.println(new Date().toString() + "LockB locks obj1");
                  Thread.sleep(60 * 1000); // For testing purposes}}}}catch(Exception e) { e.printStackTrace(); }}}Copy the code

The results of

Tue May 05 10:51:06 CST 2015LockB starts executing Tue May05 10:51:06 CST 2015LockA starts executing Tue May05 10:51:06 CST 2015LockB lock obj2 Tue May05 10:51:06 CST 2015Locked obj1 LockACopy the code

To solve

import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class UnLockTest {
   public static String obj1 = "obj1";
   public static final Semaphore a1 = new Semaphore(1);
   public static String obj2 = "obj2";
   public static final Semaphore a2 = new Semaphore(1);

   public static void main(String[] args) {
      LockAa la = new LockAa();
      new Thread(la).start();
      LockBb lb = new LockBb();
      newThread(lb).start(); }}class LockAa implements Runnable {
   public void run(a) {
      try {
         System.out.println(new Date().toString() + "Start LockA execution");
         while (true) {
            if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + "LockA locks obj1");
               if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + "LockA locks obj2");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockA failed to lock obj2"); }}else{
               System.out.println(new Date().toString() + "LockA failed to lock obj1");
            }
            UnLockTest.a1.release(); / / release
            UnLockTest.a2.release();
            Thread.sleep(1000); // Try it right away. In reality, doing something is uncertain}}catch(Exception e) { e.printStackTrace(); }}}class LockBb implements Runnable {
   public void run(a) {
      try {
         System.out.println(new Date().toString() + "LockB start execution");
         while (true) {
            if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + "LockB locks obj2");
               if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + "LockB locks obj1");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockB failed to lock obj1"); }}else{
               System.out.println(new Date().toString() + "LockB failed to lock obj2");
            }
            UnLockTest.a1.release(); / / release
            UnLockTest.a2.release();
            Thread.sleep(10 * 1000); // This is just for demonstration, so tryAcquire only takes 1 second, and B must give A time to execute, otherwise the two will always be deadlocked}}catch(Exception e) { e.printStackTrace(); }}}Copy the code
Tue May 05 10:59:13 CST 2015LockA starts executing Tue May05 10:59:13 CST 2015LockB starts executing Tue May05 10:59:13 CST 2015LockB lock obj2 Tue May05 10:59:13 CST 2015LockA locks obj1 Tue May05 10:59:14 CST 2015LOckB lock obj1 failed Tue May05 10:59:14 CST 2015LOckA lock obj2 failed Tue May05 10:59:15 CST 2015LockA locks obj1 Tue May05 10:59:15 CST 2015LockA lock obj2Copy the code
  1. Lock is an explicit Lock (manually open and close the Lock, but do not forget to close the Lock) synchronized is an implicit Lock, which is automatically released out of the scope
  2. Lock only has code block locks, synchronized has code block locks and method locks. With Lock locks, the JVM spends less time scheduling threads and performs better. And more extensible (more subclasses)
  3. Priority order: Lock > synchronize code block (already in method body, allocated resources) > synchronize method (outside method body)

Thread communication

The goal of thread communication is to enable threads to send signals to each other. Thread communication, on the other hand, enables threads to wait for signals from other threads.

How threads communicate

  1. volatile
  2. Wait/Notify mechanism
  3. The join way
  4. threadLocal
  5. CountDownLatch concurrency tool
  6. CyclicBarrier concurrency tool

volatile

public class Volatile implements Runnable {
  private static volatile Boolean flag = true;

  @Override
  public void run(a) {
    while (flag) {
      System.out.println(Thread.currentThread().getName() + "- Execute");
    }
    System.out.println("Thread terminated");
  }

  public static void main(String[] args) {
    Thread t = new Thread(new Volatile());
    t.start();
    try {
      Thread.sleep(5);
      flag = false;
    } catch(InterruptedException e) { e.printStackTrace(); }}}Copy the code
Thread0- to perform the Thread0- to perform the Thread0- to perform the Thread0- to perform the Thread0- The execution thread endsCopy the code

**WaitNotify **


public class WaitNotify {
  / / state
  private static Object lock = new Object();
  private static Integer i = 0;

  public void odd(a) {
    while (i < 10) {
      synchronized (lock) {
        if (i % 2= =1) {
          System.out.println(Thread.currentThread().getName() + "-" + i);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          i++;
          lock.notify();
        } else {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public void even(a) {
    while (i < 10) {
      synchronized (lock) {
        if (i % 2= =0) {
          System.out.println(Thread.currentThread().getName() + "-" + i);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          i++;
          lock.notify();
        } else {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public static void main(String[] args) {

    WaitNotify waitNotify = new WaitNotify();

    Thread t1 = new Thread(() -> waitNotify.odd(), Thread 1 "");
    Thread t2 = new Thread(() -> waitNotify.even(), Thread 2 ""); t1.start(); t2.start(); }}Copy the code

join

package threadCommunication;

public class JoinTest extends Thread {
    @Override
    public void run(a) {
        try {
            int sleepTime = (int) (Math.random() * 1000);
            System.out.println(sleepTime);
            Thread.sleep(sleepTime);
            System.out.println("JoinTest end");
        } catch(InterruptedException e) { e.printStackTrace(); }}public static void main(String[] args) throws InterruptedException {
        JoinTest j = new JoinTest();
        j.start();
        j.join();// The current thread main waits for the thread object (j) to be destroyed
        System.out.println("main end");
    }

Copy the code

threadLocal

package sync; 
public class SequenceNumber { 
 // Define anonymous subclasses to create variables for ThreadLocal
 private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() { 
 // override the initialization method
 public Integer initialValue() { 
 		return 0; }};// Next serial number
 public int getNextNum(a) { 
     seqNum.set(seqNum.get() + 1); 
     return seqNum.get(); 
 } 
 private static class TestClient extends Thread { 
     private SequenceNumber sn; 
     public TestClient(SequenceNumber sn) { 
     this.sn = sn; 
 } 
 // The thread generates the serial number
 public void run(a) { 
     for (int i = 0; i < 3; i++) { 
         System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + 			sn.getNextNum() + "]"); }}}/** * @param args */ 
 public static void main(String[] args) { 
     SequenceNumber sn = new SequenceNumber(); 
     // Three threads generate serial numbers
     TestClient t1 = new TestClient(sn); 
     TestClient t2 = new TestClient(sn); 
     TestClient t3 = newTestClient(sn); t1.start(); t2.start(); t3.start(); }}Copy the code
thread[Thread- 1] sn[1] 
thread[Thread- 1] sn[2] 
thread[Thread- 1] sn[3] 
thread[Thread2 -] sn[1] 
thread[Thread2 -] sn[2] 
thread[Thread2 -] sn[3] 
thread[Thread0] sn[1]
thread[Thread0] sn[2] 
thread[Thread0] sn[3]

Copy the code

**CountDownLatch **CountDownLatch can replace the use of wait/notify and eliminate synchronized

import java.util.concurrent.CountDownLatch;

public class CountDown {
  private static Integer i = 0;
  final static CountDownLatch countDown = new CountDownLatch(1);

  public void odd(a) {
    while (i < 10) {
      if (i % 2= =1) {
        System.out.println(Thread.currentThread().getName() + "-" + i);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        i++;
        countDown.countDown();
      } else {
        try {
          countDown.await();
        } catch(InterruptedException e) { e.printStackTrace(); }}}}public void even(a) {
    while (i < 10) {
      if (i % 2= =0) {
        System.out.println(Thread.currentThread().getName() + "-" + i);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        i++;
        countDown.countDown();
      } else {
        try {
          countDown.await();
        } catch(InterruptedException e) { e.printStackTrace(); }}}}public static void main(String[] args) {

    CountDown countDown = new CountDown();

    Thread t1 = new Thread(() -> countDown.odd(), Thread 1 "");
    Thread t2 = new Thread(() -> countDown.even(), Thread 2 ""); t1.start(); t2.start(); }}Copy the code

CyclicBarrier

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
  public static void main(String[] args) {
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("All started!");
    }, Thread 1 "").start();

    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("All started!");
    }, Thread 2 "").start();

    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("All started!");
    }, "Thread 3").start(); }}Copy the code
thread3: ready to... thread2: ready to... thread1: ready to... All started! All started! All started!Copy the code

The thread pool

Extremely heavy resources that are frequently created and destroyed, such as threads in concurrent situations, have a significant impact on performance. Create several threads in advance, put them into the thread pool, get them directly when they are used, and put them back into the pool when they are used. It can avoid frequent creation and destruction and realize reuse.

The ExecutorService and Executors

  1. ExecutorService: ** A real thread pool interface. Common subclasses ThreadPoolExecutor void execute(Runnable command) : Executes a task/command without returning a value. It is used to execute Runnable

  2. Future Submit (Callable Task) : Executes the task, returns a value, and typically executes the Callable

  3. Void shutdown() : shuts down the connection pool

**Executors: ** Factory class for creating and returning different types of thread pools

13. Note

Java annotations, also known as Java annotations, are an Annotation mechanism introduced in JDK5.0.

role

Not the program itself, but the program itself.(This is no different from comments.)

Can be read by other programs (e.g. compilers, etc.).

They can be appended to package, class, Method, field, etc., adding additional auxiliary information to them

We can access this metadata through reflection

format

Annotations exist in the code as “@ comment name”

You can also add some parameter values, such as @suppressWarnings (value=”unchecked”)

Built-in annotations

Java defines a set of 10 annotations, three in java.lang before Java7, four in java.lang.annotation, and three more later

The annotation (java.lang) applied to the code is @override - checks if the method is an Override method. If the method is not found in the parent class or in the referenced interface, a compilation error is reported. @deprecated - Marks obsolete methods. If you use this method, a compile warning is reported. @SuppressWarnings - Instructs the compiler to ignore warnings declared in annotations. The annotation (or meta-annotation) that applies to other annotations is the (java.lang.annotation) annotation @Retention - identifies how the annotation is stored, whether it is only in the code or marshaledclassFile, or can be accessed by reflection at run time. @Documented- Marks whether these annotations are included in the user document. @Target- Mark what kind of annotation this should beJavaMembers. @Inherited- Marks which annotation class this annotation inherits from (default annotation does not inherit from any subclasses)java7The annotation at sign was added laterSafeVarargs - JavaStart to support, ignoring any warnings generated by method or constructor calls that take arguments as generic variables. @FunctionalInterface - Java8 start support, identifying an anonymous function or functional interface. @Repeatable - JavaSupport to indicate that an annotation can be used more than once on the same declaration.Copy the code
package com.annotation;
// Test the built-in annotations
import java.util.ArrayList;
import java.util.List;
// All classes inherit the Object class by default
public class Test1 extends Object {
    // @override means method Override
    //--> Check the JDK help documentation
    < span style = "max-width: 100%; clear: both; min-height: 1em
    @Override
    public String toString(a) {
    	return super.toString();
    }
     // The method is out of date and is not recommended to be used.
    //--> Check the JDK help documentation
    @Deprecated
    public static void stop(a){
    	System.out.println("Test @ Deprecated");
    }
    // @suppresswarnings SuppressWarnings. Parameters can be passed
    //--> Check the JDK help documentation
    // Find the parameter type and parameter name, not the method!
    @SuppressWarnings("all")
    public void sw(a){
   	 List list = new ArrayList();
    }
    public static void main(String[] args) { stop(); }}Copy the code

Yuan notes

package com.annotation;
import java.lang.annotation.*;
// Test meta annotations
public class Test2 {
@MyAnnotation
public void test(a){}}// Define an annotation
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface MyAnnotation{
}

Copy the code

Custom annotations

  1. When using the @ interface custom annotations, automatic inherited Java. Lang. The annotation. The annotation interface @ interface is used to declare an annotation, format: public @ interface annotation name} {define content

  2. Each of these methods actually declares a configuration parameter. The name of the method is the name of the parameter.

  3. The return value type is the type of the parameter (the return value can only be the basic type,Class, String, enum). You can declare default values for parameters with default

  4. If there is only one parameter member, the general parameter name is value

  5. An annotation element must have a value, and when we define an annotation element, we often use an empty string,0, as the default.

Annotation parameters can support data types: 1. All basic data types (int, float, Boolean, byte, double, char, long, short) 2. The type String (3) 4 Class type enum type 5. 6 the Annotation type. All of the above types of arrays

package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

* @author peida ** /
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value(a) default "";
}
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** ** Fruit color notes * @author peida ** /
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /** ** color enumeration * @author peida ** /
    public enum Color{ BULE,RED,GREEN};

    /** * Color attribute * @return */
    Color fruitColor(a) default Color.GREEN;

}
package annotation;

import annotation.FruitColor.Color;

public class Apple {

    @FruitName("Apple")
    private String appleName;

    @FruitColor(fruitColor=Color.RED)
    private String appleColor;

    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor(a) {
        return appleColor;
    }

    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName(a) {
        return appleName;
    }

    public void displayName(a){
        System.out.println("The name of the fruit is: apple"); }}// Set the default value
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** ** ** ** ** /
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    /** * Supplier number * @return */
    public int id(a) default- 1;

    /** * Vendor name * @return */
    public String name(a) default "";

    /** * Supplier address * @return */
    public String address(a) default "";
}

Copy the code

14. The reflection

Reflection mechanism

Java’s reflection mechanism relies on four classes: Class, Constructor, Field, and Method; Where class represents the time class object, Constructor- the Constructor object of the class, Field- the property object of the class, Method- the Method object of the class. Through these four objects we can see roughly the constituent parts of a class.

Method to get the class

// Invoke the.class property of the runtime class itself
Class clazz = String.class;

// From the object of the runtime class
Person p = new Person();

Class clazz = p.getClass();

// Static method through Class: reflect the dynamic of reflectionMons String className = "java.util.com"; Class clazz = Class.forName(className);// Through the class loaderMons String className = "java.util.com"; ClassLoader classLoader =this.getClass().getClassLoader();

Class clazz = classLoader.loadClass(className);

Copy the code

Method to get the constructor

Constructor getConstructor(Class[] params)Get a public Constructor that uses a particular parameter type, Constructor[]getConstructors(a)Get all the public constructors of the classgetDeclaredConstructor(Class[] params)Gets a constructor that takes a specific parameter type(Regardless of access level) 

Constructor[] getDeclaredConstructors(a)Get all the constructors of the class(Regardless of access level)

Copy the code

For field

Field getField(String name)Get the named public Field[]getFields(a)Get all the public fields of the classgetDeclaredField(String name)[] get the named Field of the class declarationgetDeclaredFields(a)Get all fields declared by the classCopy the code

Get method information

Method getMethod(String name, Class[] params)Get the named public Method using the specified parameter type []getMethods(a)Get all public methods of the classgetDeclaredMethod(String name, Class[] params)Method[] -- Use close-up parameter type to get the named Method of class declaration []getDeclaredMethods(a)Get all the methods of the class declarationCopy the code