Personal blog welcome to visit

Dunk is a search program on wechat. Follow the dunk account to get the source of the blog, notes on data structures and algorithms, and interview pens

The serial number content
1 Java basic interview questions
2 The JVM interview questions
3 Java concurrent programming interview
4 Computer network knowledge summary
5 MySQL interview questions
6 Mybatis source code analysis + interview
7 Spring interview questions
8 For SpringMVC interview questions
9 SpringBoot interview questions
10 SpringCloud interview questions
11 Redis interview questions
12 Elasticsearch interview questions
13 Docker learning
14 The message queue
15 Continuously updated…

object-oriented

The difference between object-oriented and procedural

  • Process-oriented: specific, process-oriented, to solve a problem, you need to step by step analysis, step by step implementation

    • Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, the overhead is relatively large, more consumption of resources; For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor
    • Disadvantages: No object-oriented easy maintenance, easy reuse, easy to expand
  • Object-oriented: Modeled, you just pull out a class, it’s a closed box where you have the data and the solution to the problem. What functions are needed can be used directly, do not have to go step by step implementation, as for this function is how to achieve

    • Advantages: Easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain
    • Disadvantages: Lower performance than process-oriented

The three major characteristics

Abstract: Abstract is the process of constructing a class by summarizing the common characteristics of a class of objects, including data abstraction and behavior abstraction. Abstract only focuses on the attributes and behaviors of objects, not the details of these behaviors

encapsulation

It is the expression form of object function cohesion, which determines whether information is disclosed and the level of disclosure on the basis of abstraction, and which information is exposed in what way. The main task is to hide attributes, data, and sensitive behaviors. The access and modification of attributes must be realized through public interfaces. Encapsulation simplifies object relationships, reduces code coupling, and facilitates maintenance

The Demeter principle is the requirement of encapsulation, that is, module A uses an interface behavior of module B, and should know as little as possible about other information except this behavior in module B. Getter /setter methods are used instead of reading and modifying public properties directly because they assume permission control, logging, and so on when modifying properties, which cannot be done with direct access to properties. If you change the properties and behavior of public to private, the dependency module will report an error. Therefore, if you do not know which permission to use private should be preferred

inheritance

It is used to extend a class, subclass can inherit part of the attributes and behavior of the parent class to make the module have the ability to take, inheritance is “IS-A” relationship, can use the Richter substitution principle to determine is enough to meet the “IS-A” relationship, that is, any place where the parent class can appear subclass can appear. If the parent class reference is replaced directly with a subclass reference and is correctly compiled and executed, and the output is as expected in the subclass scenario, then both classes comply with the Richter substitution principle

polymorphism

On the basis of encapsulation and inheritance, make with to run-time objects based on the actual type has different forms, polymorphism refers to the compilation method body could not determine the final call, at run time by the JVM dynamic binding, suitable for the suitable method to rewrite, belongs to static binding due to overloading, essentially override results are completely different approach, thus polymorphism generally specifically to rewrite

Overloading and rewriting

overloading

Overloading refers to the same method name, but different number of parameter types, is the horizontal implementation of different behavior. To the compiler, the method name and argument list form a unique key, called the method signature, through which the JVM decides which overloaded methods to call. Regardless of the complexity of inheritance, an overload knows at compile time by rule which target method to call, and therefore is statically bound. Right

The order in which the JVM selects the appropriate method among overloaded methods: ② Basic data types are automatically converted to a larger range of representations. Automatic unpacking and packing. (4) Subclass upward transformation. ⑤ Variable parameters

rewrite

Overrides refer to the implementation of interfaces or parent classes that keep the method signature exactly the same, implement different method bodies, and implement different behavior vertically

The meta space has a method table that holds method information, and if a subclass overrides a method of its parent class, method references in the method table point to the subclass implementation. A superclass reference executing a subclass method cannot call a method that does not have a parent class but does not have a subclass.

Override method access cannot be smaller, return types and exception types cannot be larger, and @override must be added

Relationships between classes

Class relationships describe Strong power side For example,
inheritance Relationships between parent and child classes: IS-A The parent class Dogs inherit from animals
implementation Relationship between interface and implementation class: can-do interface The dog realized the barking interface
combination Stronger relationship than aggregation: contains-a As a whole The head is part of the body
The aggregation Relationship of temporary assembly: HAS-A Assemble the The dog and the rope are a temporary bond
Rely on One class uses the other: depends-a By relying party People raise dogs, people depend on dogs
associated Equal use relationship: links-a equality People use card consumption, the card can extract information

Access control character

Access control character This class Inside the package Package subclass Any place
public Square root Square root Square root Square root
protected Square root Square root Square root x
There is no Square root Square root x x
private Square root x x x

Language features

Advantages of the Java language

  • Platform independent, get rid of hardware shackles, write once, export to run
  • Relatively safe memory management and access mechanism, avoid most memory leaks and pointer out of bounds
  • Hot code detection and runtime compilation and optimization to achieve higher performance over time
  • Perfect application program interface, support third party class library

How does Java achieve platform independence?

JVM: The Java compiler generates computer architecture-independent bytecode instructions that can be easily interpreted and executed on any machine and dynamically translated into native machine code by the JVM, which is platform-specific and does not discriminate between operating systems

Language specifications: Basic data types are clearly defined. For example, ints are always 32 bits, whereas in C/C++ they can be 16 bits, 32 bits, or any other size specified by the compiler developer. In Java, numeric types have a fixed number of bytes, are stored and transmitted in binary format, and strings are stored in standard Unicode format

The difference between JDK and JRE

JDK: Java Development Kit It provides various tools for compiling and running Java programs, including compiler (javac.exe), JRE and packaging tool (jar.exe), which is the core of Java

JRE: Java Runtime Environment, which is required for running Java programs, including the JVM, core class libraries, and core configuration tools

Does Java call by value or by reference

  • Pass by value: Accepts a value provided by the caller
  • Call by reference: means that a method accepts the address of a variable provided by the caller

Java is always called by value, a copy of all the arguments a method gets, and when you pass an object the method actually receives a copy of the object reference. Method cannot modify the arguments of the base datatype. If an int value is passed, changing the value does not affect the argument because you are changing a copy of the value

If you pass an int array, changing the contents of the array affects the argument, and changing the reference to the argument does not cause the argument to reference the new array object

Difference between shallow copy and deep copy

  • Shallow copy: Copies only the underlying data type of the current object, the reference variable, without copying the actual object to which the reference variable points. Modifying a cloned object may affect the original object, which is unsafe
  • Deep copy: Copies all basic data types and application data types securely

serialization

Java objects are destroyed when the JVM exits, and if objects and their state need to be persisted, they need to be serialized, storing in-memory objects in a binary stream that can then be deserialized as needed. Object serialization holds the state of the object, so static variables that are class attributes are not serialized

Common serialization methods

Java native serialization

Implementation of Serializabale tag interface, Java serialization retains object class metadata (such as classes, member variables, inherited class information) and object data, best compatibility, but does not support cross-language, performance is average. Serialization and deserialization must be consistent with the serialization ID. The private Static Final Long serialVersionUID is generally used to define the serialization ID. If not set, the compiler automatically generates this value based on the internal implementation of the class. The serialization ID should not be changed if it is a compatible upgrade to prevent errors, or it should be changed if it is an incompatible upgrade

Hessian serialization

Hessian serialization is a cross-language, object-based network protocol that supports dynamic typing. Binary streams of Java object serialization can be deserialized by other languages. Hessian protocol features: ① Self-description serialized type, independent of external description file, with a byte to represent the common base type, greatly shorten the binary stream. ② Language independent, support scripting language. The protocol is simple and more efficient than Java native serialization. Hessian serializes all properties of a complex object in a Map. If a parent class and a subclass have a member variable of the same name, the subclass is serialized first and then the parent class. Therefore, the subclass value is overwritten by the parent class

JSON serialization

JSON serialization converts a data object into a JSON string. The type information is discarded during the serialization process, so deserialization can only be performed accurately if the type information is provided. Compared with the previous two methods, it is more readable and convenient for debugging

Serialization usually uses network transmission objects, which often have sensitive data and are vulnerable to attack. Deserialization vulnerability has occurred in Jackson and Fastjson, so the transient keyword should be added when transferring sensitive attributes that do not need to be serialized. The purpose of transient is to limit the lifetime of a variable to memory and not write it to disk for persistence. The variable will be set to zero value of the corresponding data type

Often ask about methods and classes

What methods does the Object class have?

**equals: ** Checks whether objects are equal. By default, the equals method is used to compare object references. You can override the equals method to customize the comparison rule. Equals method specification: reflexivity, symmetry, transitivity, consistency, for any non-empty reference x, x.equals(null) returns false

**hashCode: **hashCode is an integer exported from an object. Each object has a default hashCode, which is derived from the object’s storage address. The string hash code is derived from the content and may have the same value. In order to use it correctly in a collection, you generally need to override both equals and hashCode, requiring that equals be the same, hashCode must be the same, hashCode is not necessarily the same as equals, so hashCode is a necessary and insufficient condition for objects to be equal

ToString: The default method for printing an object, if not overridden, to print a string representing the object’s value

Clone: The clone method is protected. A class can only clone its own objects using this method. It must be made public if it wants other classes to call this method. If an object’s class does not implement the Cloneable interface, the clone party is called to raise a CloneNotSupport exception. The default clone method is a shallow-copy. Overwriting the Clone method requires implementing the Cloneable interface and specifying the access modifier public

** Finalize: ** To determine the death of an object, it must be marked at least twice. If the object is found to have no reference chain connected with GC Roots after the reachabability analysis, it will be marked for the first time, and then it will be filtered once, and the condition is whether it is necessary for the object to execute the Finalize method. If the object has not overridden the method or if the method has been called by the virtual machine, it is considered unnecessary to execute. If necessary, the object is placed in an F-queue and executed by a low-priority Finalizer thread. The virtual machine fires this method, but it is not guaranteed to end. This is to prevent the Finalize method of an object from executing slowly or an infinite loop. As long as the object is re-associated with the object on the reference chain in the Finalize method, it will be removed from the collection on the second markup. Methods are marked as obsolete in JDK 9 and not suitable for releasing resources because they are expensive to run and cannot be called in a guaranteed order

**getClass: ** Returns the class object that contains the object information.

** Wait/notify/notifyAll: ** Blocks or wakes up the thread holding the lock

The equals and hashCode

How does a HashSet check for duplication? If two objects have the same hashCode(), equals() must also be true

HashCode () is introduced

Does hashCode() get a hash, also known as a hashCode; It actually returns an int integer, and the purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is defined in the JDK’s Object class, which means that any class in Java contains a hashCode() function

Hash table stores key-value pairs. It can quickly retrieve the corresponding value according to the key. That’s where the hash code comes in! (Can quickly find the desired object)

Why hashCode()

Let’s use “how a HashSet checks for duplicates” as an example of why hashCode is needed:

When you add an object to a HashSet, the HashSet evaluates the object’s hashCode value to determine where the object was added. It also compares the object’s hashCode value to the hashCode value of other objects that have already been added. If there is no matching hashCode, the HashSet assumes that the object is not repeated. But if objects with the same hashCode value are found, the equals() method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed. If it is different, it will be rehashed to another location

HashCode () and equals()

If two objects are equal, hashCode must be equal

Two objects are equal. Calling equals on both objects returns true

Two objects have the same hashCode value, but they are not necessarily equal

Therefore, if equals() is overridden, the hashCode() value must also be overridden

The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, then two objects in this class will never be equal anyway (even if they point to the same data).

What is the difference between the equality of objects and the equality of references to them?

Object equality compares whether the contents in memory are equal while reference equality compares whether the memory address they point to is equal

= = and equals?

  • == : This is used to determine whether the addresses of two objects are equal, that is, whether two objects are the same object (base datatype ** compares values, reference datatype ** compares memory addresses).

  • Equals () : Also checks whether two objects are equal. But it can be used in two ways

    • Class does not override equals(), so comparing two objects of the class via equals() equals the equivalent of comparing them via **==**
    • This class overrides the equals() method. In general, we override the equals()** method to determine whether two objects are equal. If they are equal, it returns true

Note: The equals method on String is overridden, because the equals method on Object compares the memory addresses of objects, whereas the equals method on String compares the values of objects

When creating a String object, the virtual machine looks in the constant pool to see if there is an existing object with the same value as the value to be created. If there is an existing object, it assigns it to the current reference. If there is no existing object, it creates a String object in the constant pool

The data type

Java basic data types

The data type Memory size The default value Value range
byte 1B (byte)0 – 128 ~ 127
short 2B (short)0 – 215-215-1
int 4B 0 – 231-231-1
long 8B 0L – 263-263-1
float 4B 0.0 F + 3.4E+38 (effective digits 6~7)
double 8B 0.0 D + 1.7E+308 (15 effective digits)
char English 1B, Chinese UTF-8 3B, GBK 2B ‘\ u0000’ ‘\ u0000’ ~ ‘\ uFFFF
boolean Single variable 4B/ array 1B false True, false,

The JVM does not have special bytecode instructions for Boolean assignment. Boolean f = false is assigned using ICONST_0, the constant 0. Individual Boolean variables are replaced with int, and Boolean arrays are encoded as byte arrays

A wrapper class

There is a wrapper class for each primitive data type, and the wrapper classes for the primitive data types are capitalized except for int and char, which correspond to Integer and Character

  • Automatic boxing: Base types are wrapped in their corresponding reference types
  • Automatic unpacking: Converts package type to base data type

Difference between int and Integer

Java is an almost pure object-oriented programming language, but it has introduced a wrapper class for each primitive data type in order to be able to manipulate them as objects. The wrapper class for int is Integer, and since Java 5 automatic boxing/unboxing has been introduced to make them interchangeable

Java provides a wrapper type for each primitive type:

Primitive types: Boolean, char, byte, short, int, long, float, double

Wrapper types: Boolean, Character, Byte, Short, Integer, Long, Float, Double

Is Integer A = 127 the same as Integer B = 127

For object reference types: == Compares the memory address of the object. For basic data types: == compares values

If the Integer literal has a value between **-128 and 127 **, auto-boxing will not new a new Integer object, but will refer directly to an Integer object in the constant pool. Beyond the range A1 ==b1, the result is false

public static void main(String[] args) {
    Integer a = new Integer(3);
    Integer b = 3;  // Automatically box 3 into type Integer
    int c = 3;
    System.out.println(a == b); // false Two references do not refer to the same object
    System.out.println(a == c); // true a is automatically unpacked into int types and then compared with C
    System.out.println(b == c); // true

    Integer a1 = 128;
    Integer b1 = 128;
    System.out.println(a1 == b1); // false

    Integer a2 = 127;
    Integer b2 = 127;
    System.out.println(a2 == b2); // true
}
Copy the code

String

What are the ways of concatenating strings

  • Use directly+, the underlying implementation with StringBuilder. Only suitable for small quantities if used in loops+Concatenation, which is the equivalent of constantly creating new StringBuilder objects and converting them to Strings, is extremely inefficient
  • Use the concat method of String, which is used in this methodArrays.copyOfCreate a new character array buf and copy the values of the current string value array into BUf, buf length = current string length + concatenation string length. After the callgetCharsMethods usingSystem.arraycopyThe value of the concatenated String is also copied to the buF array, and a new String object is returned with buf as the construction parameter new. Slightly more efficient than direct use+
  • Use StringBuilder or StringBuffer, bothappendMethods all inherit from AbstractStringBuilder, which is used firstArrays.copyOfDetermine the new character array size, then callgetCharsMethods usingSystem.arraycopyAppends the new value to the array. StringBuilder was introduced in JDK5 and is efficient but not thread-safe. StringBuffer uses synchronized to ensure thread safety

String a = “a” + new String(” b “) how many objects are created?

Constants and constant concatenation are still constants, and the result is in the constant pool, as long as there are variables involved in the concatenation the result is a variable, in the heap

With a literal, only one constant from the constant pool is created. With new, if the value is not in the constant pool, it is created in the constant pool and an object is created in the heap referencing the constant from the constant pool. So String a = “a” + new String(“b”) creates four objects, a and B in the constant pool, B in the heap, and AB in the heap

What’s the difference between StringBuffer and StringBuilder?

variability

  • The String class uses character arrays to hold characters,private final char value[], so strings are immutable.
  • StringBuilder and StringBuffer both inherit fromAbstractStringBuilderIn class,AbstractStringBuilderIn also uses character arrays to hold strings

Thread safety

  • Objects in strings are immutable, which means they are thread safe.
  • AbstractStringBuilderStringBuffer is the common parent of StringBuilder and StringBuffer. StringBuffer locks methods or methods that are called, so it is thread-safe. StringBuilder does not lock methods synchronously-so it is not thread-safe

performance

  • Every time a String type is changed, a new String is generated and will point to the new String.
  • A StringBuffer operates on a StringBuffer every time, rather than generating new objects and changing their references. Using A StringBuilder only yields a 10% to 15% performance improvement over using a StringBuffer. But you run the risk of multithreading insecurity

conclusion

  • Use String if you operate on a small amount of data
  • Single thread manipulation of large amounts of data using StringBuilder
  • Multithreading manipulates large amounts of data using stringBuffers

Can switch work on byte, can switch work on long, and can switch work on String?

Before Java5, switch(expr), expr can only be byte, short, char, int. From Java5, Java introduced enumeration type, expr can also be enum. From Java7, expr can also be String. But Long doesn’t support it

The final keyword

  • Modify variables

Any member variable or local variable (called a local variable ina method or code block) that is declared final is called final. Final variables are often used with the static keyword as constants

When final modifies a variable of base data, the initial value must be assigned and the reference variable cannot be modified. The reference variable cannot point to another object

An error is reported when final modifies a primitive datatype variable without assigning an initial value and when the reference variable points to another object

An error is reported when a final modifier base datatype variable is changed

  • Modification methods

Final can also be declared as a method, and the final keyword means that the method cannot be overridden by a subclass method. You can also declare a method final if you think that the functionality of a method is complete enough that the subclass doesn’t need to change. Final methods are faster than non-final methods. Because it is statically bound at compile time, there is no need to bind at run time

  • decorator

Classes that use final modifiers are called final classes. Final classes are usually complete and cannot be inherited. There are many classes in Java that are final, such as String, Integer, and other wrapper classes

What is the difference between Final, Finally and Finalize?

Final can modify classes, variables, and methods. A modifier class means that the class cannot be inherited, a modifier method means that the method cannot be overridden, and a modifier variable means that the variable is a constant and cannot be reassigned. Finally is usually used ina try-catch block. When handling an exception, the method finally is always executed, indicating that the block will be executed regardless of whether an exception occurs. It is used to store code that closes a resource. Finalize is a method that belongs to the Object class, which is the parent of all classes. Java allows you to use Finalize () to do the necessary cleanup before the garbage collector purifies objects from memory.

annotations

The concept of annotations

Annotations are a method provided by Java to set the associated information and MetaData of an element in a program. It is an interface that a program can use to obtain an Annotation object of a specified element in a program through reflection, and then obtain the MetaData information in the Annotation through this Annotation object

What are annotations? What is a meta-annotation?

  • Annotation: an identifier that allows a class or excuse to attach additional information to help the compiler and JVM perform a particular function. For example, @Override identifies a method as an Override method.

  • Meta-annotations: meta-annotations are annotations of custom annotations:

    • @ Target: The values are ElementType enumerated constants, including METHOD methods, VARIABLE variables, TYPE classes/interfaces, PARAMETER METHOD parameters, CONSTRUCTORS, and LOACL_VARIABLE local variables

    • @Retention: Constraint life cycle

      • SOURCE: valid in the SOURCE file, that is, retained in the SOURCE file
      • CLASS: valid in the CLASS file, that is, retained in the CLASS file
      • RUNTIME: valid at RUNTIME, i.e. reserved at RUNTIME
    • Documented: Indicates that this annotation should be Documented by a Javadoc tool and therefore Documented by a Javadoc class tool

    • @Inherited: This is an Annotation that indicates that an annotated type is Inherited. If an Annotation using the @Inherited Annotation is applied to a Class, it will be applied to the Class

Annotation processor

Annotations are used to describe metadata information, with the emphasis on the definition of annotation processor. JavaSE5 extends the API of reflection mechanism to help programmers quickly construct custom annotation processor. The use of annotations generally includes the definition and use of annotation interface, and we generally use annotations by encapsulating unified annotation tools

Custom annotation

/ * * *@author: zsy *@date: Created 2021/6/12 14:48 *@description: * /
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    // Supplier number
    public  int id(a) default- 1;
    // Vendor name
    public String name(a) default "";
    // Supplier address
    public  String address(a) default "";
}
Copy the code

Using the Annotation interface

Define an Apple class and annotate a property

/ * * *@author: zsy *@date: Created 2021/6/12 14:51 *@description: apple * /
@Setter
@Getter
public class Apple {
    @fruitProvider (id = 1, name = "Shangluo ", address =" Xi 'an ")
    private String appleProvider;
}
Copy the code

Defining annotation handlers

Get annotation data by reflecting information

/ * * *@author: zsy *@date: Created 2021/6/12 14:53 *@description: Annotation processor */
public class FruitInfoUtil {

    public static void getFruitInfo(Class
        clazz) {
        System.out.println("Supplier Information");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            FruitProvider annotation = declaredField.getAnnotation(FruitProvider.class);
            System.out.println(Supplier No. : + annotation.id());
            System.out.println(Name of Supplier: + annotation.name());
            System.out.println("Supplier address:"+ annotation.address()); System.out.println(annotation); }}}Copy the code

test

/ * * *@author: zsy *@date: Created 2021/6/12 14:54 *@description: * /
public class Test {
    public static void main(String[] args) { FruitInfoUtil.getFruitInfo(Apple.class); Supplier Information Supplier No. :1Supplier name: Shangluo, Shaanxi Supplier address: Xi 'an, Shaanxi @ Note. FruitProvider(Name = Shangluo, Address = Xi 'an, ID =1)
Copy the code

class

The inner class

Classes defined inside a class are called inner classes. Inner classes can be divided into static inner classes, member inner classes, local inner classes and anonymous inner classes according to different definitions

Static inner class

A static class defined inside a class is a static inner class

A static inner class can access static variables and methods of an external class. In a static inner class, you can define static variables, static methods, construct inverse functions, etc. The static inner class passes the outer class. Static inner class

A static inner class can access all the static variables of the outer class, but not the non-static variables of the outer class. Static inner class creation, new outer class. Static inner class (), as follows

/ * * *@author: zsy *@date: Created 2021/6/12 15:07 *@description: static inner class */
public class OuterClass {
    private static String className = "StaticInnerClass";

    public static class StaticInnerClass {
        public void getClassName(a) {
            System.out.println("The className."+ className); }}// Call the static inner class
    public static void main(String[] args) {
        StaticInnerClass staticInnerClass = newStaticInnerClass(); staticInnerClass.getClassName(); }}Copy the code

The Java collection class HashMap maintains an array of static inner class Nodes to hold elements. Node elements are transparent to users. Static inner classes can be used if they are closely related to external classes and do not depend on external class instances

Member inner class

A non-static class defined inside a class at a member location is an intra-member class.

Member inner classes cannot define static methods and variables (with the exception of final modifications) because member inner classes are non-static, whereas static methods and variables cannot be defined in Java’s non-static code blocks

Member inner classes can access all variables and methods of the external class, including static and non-static, private and public. A member inner class depends on an instance of an external class and is created in the same way as an instance of an external class. new Inner class ()

/ * * *@author: zsy *@date: Created 2021/6/12 15:16 *@description: Member inner class */
public class OutClass {
    private static int a = 12;
    private int b = 2;

    public class MemberInnerClass {
        public void print(a) { System.out.println(a); System.out.println(b); }}public static void main(String[] args) {
        OutClass outClass = new OutClass();
        MemberInnerClass memberInnerClass = outClass.new MemberInnerClass(a); memberInnerClass.print(); }}Copy the code

Local inner class

An inner class defined in a method is a local inner class

When a class only needs to use a specific class in a method, it can be done elegantly with a local inner class

Local inner class is created in the corresponding method, new inner class ()

/ * * *@author: zsy *@date: Created 2021/6/12 15:26 *@description: local inner class */
public class OutClass {
    private  static int a;
    private int b;

    public void printClassTest(final int c) {
        final int d = 1;
        class PastClass {
            public void print(a) {
                System.out.println(c);
            }
        }
        PastClass pastClass = new PastClass();
        pastClass.print();
    }

    public static void main(String[] args) {
        OutClass outClass = new OutClass();
        outClass.printClassTest(10); }}Copy the code

Anonymous inner class

Anonymous inner classes are inner classes that do not have a name and are often used in daily development.

Anonymous inner classes are classes defined and used directly by inheriting a parent class or implementing an interface. Anonymous inner classes do not have the class keyword, which should be used to generate an object reference directly with new

/ * * *@author: zsy *@date: Created 2021/6/12 15:38 *@description: anonymous inner class */
public class Worker {
    public void work(a) {
        / / lambda ((Service) () - > System. Out. The println (" workers working..." )).doSome();
        new Service() {
            @Override
            public void doSome(a) {
                System.out.println("The workers are working....");
            }
        }.doSome();
    }

    public static void main(String[] args) {
        Worker worker = newWorker(); worker.work(); }}interface Service {
    void doSome(a);
}
Copy the code

Characteristics of anonymous inner classes

  • An anonymous inner class must inherit an abstract class or implement an interface
  • Anonymous inner classes cannot define any static members or methods
  • When the parameter of the method needs to be used by an anonymous inner class, it must be declared final
  • An anonymous inner class cannot be abstract; it must implement an inherited class or interfaceAll abstract methods

conclusion

Advantages of inner classes

  • An inner class object can access the contents of the external object that created it, including private data
  • Inner classes are not seen by other classes in the same package and have good encapsulation
  • Inner classes effectively implement multiple inheritance, optimizing the shortcomings of Java single inheritance
  • Anonymous inner classes make it easy to define callbacks

Application scenarios

  1. Some multi-algorithm scenarios
  2. Resolves some non-object-oriented blocks of statements
  3. The proper use of inner classes makes your code more flexible and extensible
  4. When a class has an external class,Is no longer used by another class

When a local inner class or an anonymous inner class accesses a local variable, why must the variable be final?

Because the lifecycle is different, local variables are stored directly on the stack, and non-final local variables are destroyed when the method execution ends. The local inner class reference to the local variable still exists, if the local inner class to call the local variable will be wrong, add final, can ensure that the variables used by the local inner class and the outer local variable are separated, solve this problem

/ * * *@author: zsy *@date: Created 2021/6/12 15:50 *@description: Tests final */
public class OuterClass {
    private int age = 12;

    class Inner {
        private int age = 13;

        public void print(a) {
            int age = 14;
            System.out.println("Local variable:" + age);
            System.out.println("Inner class variable:" + this.age);
            System.out.println("External class variable:" + OuterClass.this.age); }}public static void main(String[] args) {
        OuterClass outerClass = new OuterClass();
        outerClass.new Inner(a).print(a); }}Copy the code

What’s the difference between abstract classes and interfaces?

Interfaces and abstract classes abstract entity classes at a higher level, defining only common behaviors and characteristics

Grammar dimension An abstract class interface
Member variables No special requirements Default public static final constant
A constructor There are constructors and cannot be instantiated There is no constructor and cannot be instantiated
methods An abstract class may not have abstract methods, but an abstract class must have abstract methods Public abstract by default, JDK8 supports default/static methods, and JDK9 supports private methods
inheritance Single inheritance Multiple inheritance

How to choose abstract classes and interfaces?

  • Abstract classes represent is-A relationships, and interfaces represent Can-do relationships. In contrast to interfaces, abstract classes are relatively concrete abstractions of the same kind of transaction
  • Abstract class is template design, including a group of specific features, such as a car, chassis, control circuit and so on are common features abstracted out, but the interior, display screen, seat material can be different according to different levels of configuration
  • The interface is designed by contract and is open. It defines method names, parameters, return values, and the types of exceptions thrown. Anyone can implement it, but they must follow the conventions of the interface. For example, all vehicles must apply brakes
  • Interface is a top class, abstract class is on the second floor of the interface, the interface combination, and then implements the part of the interface, when entangled with defined interfaces and abstract classes, recommended defined as interface, follow the interface segregation principle, according to the dimensions into multiple interfaces, reuse abstract classes to implement these, facilitate subsequent extension and reconstruction

The generic

What are generics and what do they do?

The nature of generics is to parameterize types and solve the problem of not knowing the exact type of an object. Generics by definition only have the ability to execute Object methods

Benefits of generics:

  • Type safe, whatever comes out, no ClassCastException, okay
  • To improve readability, the coding phase displays object types that know how generic collections, generic methods, and so on are handled
  • Code reuse, combining the same type of processing code

Generic markup and generic qualification

A generic

The generic tag instructions
E-Element Used in a collection to represent the elements held in the collection
T-Type Represents Java classes, both the base class and the classes we define
K-Key Represents a key, such as a Map key
V-Value Said value
N-Number Presentation data type
? Indicates an indeterminate type

Generic limit

  • Limits on generic limits<? extends T>: indicates that the type represented by the wildcard is a subclass of type T or several subinterfaces of type T
  • Lower limit on renovation<? super T>: indicates that the type represented by the wildcard is the parent class or parent interface of type T

What is generic erasure?

Generics are used at compile time. The compiled bytecode file does not contain generic type information. Because the virtual machine does not have generic type objects, type parameters are removed at compile time by the compiler, a process called type erasure

For example, if a Listor List

is defined while coding, it will become a List when compiled. The additional type information of generics is not visible to the JVM

The process of type erasing begins by looking for the concrete class (usually Object) to replace type arguments, and if an upper bound is specified, the upper bound is used as the concrete class for the substitution, and then replacing all type arguments in the code with concrete types

For example,

replaces T with type A

If there are more than one qualified type it is replaced with the first qualified type

For example,

replaces T with type A

Java collection containers

Common collection classes

Subclasses of the Collection interface include Set, Queue, and List

  • The main implementation classes of the Set interface (unordered: elements may be stored and retrieved in different order) are: HashSet, TreeSet, LinkedHashSet
  • The Queue interface contains the Deque and BlockingQueue
  • Implementation classes for the List interface (ordered: elements are stored in the same order as they are retrieved) : ArrayList, LinkedList, Stack, and Vector

Map interface: a collection of key-value pairs that stores mappings between keys and values. Key unordered, unique; Value does not require order and allows repetition

Implementation classes: HashMap, TreeMap, HashTable, ConcurrentHashMap, and Properties

The List interface

Talk about the ArrayList

An ArrayList is a non-thread-safe list with variable capacity, implemented using arrays. When a collection is expanded, a larger array is created, and the original array is copied into the new array. Supports fast random access to elements, but inserts and deletes are slow. ArrayList implements the RandomAcess tag interface, which, if implemented by a class, proves to be faster to traverse using indexes than iterators

Object[]elementData is a transient Object that overrides the writeObject() method. When serialized, writeObject() is called to stream. Call readObject() when deserializing to reassign to elementData of the new object

writeObject()

The defaultWriteObject() method is called to serialize the non-transient elements in the ArrayList, and then elementData is iterated to serialize only the stored elements, which both speeds up the serialization and reduces the size of the serialized file

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();
    // Write out size as capacity for behavioural compatibility with clone()
    s.writeInt(size);
    // Write out all elements in the proper order.
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }
    if(modCount ! = expectedModCount) {throw newConcurrentModificationException(); }}Copy the code

Size is the actual size, elementData size is equal to size

**modCount ** records the number of structural changes to an ArrayList, derived from AbstractList. All methods that involve structural changes increase this value. ExpectedModCount is the modCount value recorded when the iterator is initialized. Each time a new element is accessed, the expectedModCount and The expectedModCount are checked to see if they are equal. If they are not, an exception is thrown. This mechanism is called fail-fast, and all collection classes have it

Initial capacity

The initial capacity is 10

In JDK1.7, equivalent to handedness, the first time a no-argument constructor is created, an array of initial capacity 10 is created

In JDK1.8, equivalent to slob, the default initial capacity is allocated only when the add is fully added

capacity

The capacity expansion threshold for ArrayList is 1.5

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}
Copy the code

Capacity Expansion process:

  • Suppose you have an array of length 10, add a new element, and find that the ArrayList is full and needs to be expanded
  • Redefine an array of length 10 * 1.5
  • Copy the data from the original array into the new array
  • Points the address of the ArrayList to the new array

How to convert an array to a List

Array-to-list: Use arrays.aslist () for the conversion

List toArray: use the toArray() method that comes with List

Talk about LinkedList

AbstractList is a bidirectional LinkedList. AbstractList also implements a Deque interface, which has queue and stack properties. Its member variables are transient, similar to ArrayList

LinkedList contains three important members: Size, first, and last. Size is the number of nodes in a bidirectional list. First and last refer to the first and last nodes, respectively

The advantage of LinkedList is that fragmentary memory space can be associated with additional references to form a linear structure of link sequential search, with high memory utilization

Difference between ArrayList and LinkedList

  • Data structure implementation: ArrayList is a data structure implementation of dynamic arrays, while LinkedList is a data structure implementation of bidirectional linked lists
  • ArrayList is faster to query and access, but slower to add and delete, and LinkedList is slower to find and access elements, but faster to add and delete
  • Arraylists require a contiguous memory space, linkedLists do not require a contiguous memory space (in particular, when creating a collection of ArrayLists, the contiguous memory space must be greater than or equal to the created capacity).
  • Both are thread-unsafe

In general, ArrayList is recommended for frequent reads of elements in a collection, and LinkedList is recommended for heavy inserts and deletions

Difference between an ArrayList and a Vector

The difference between ArrayList Vector
Thread safety Non-thread-safe Thread safety
performance optimal poor
capacity ArrayList expansion 1.5 Expand Vector by 2 times

All methods of the Vector class are synchronized. It is possible for two threads to access a Vector safely, but for one thread to access a Vector, the code takes a lot of time to synchronize operations

Arraylist is not synchronous, so it is recommended when thread safety is not required

Fail fast

Fail-fast is a Java collection error detection mechanism that can be used when multiple threads make structural changes to a collection

Iterators access the contents of the collection directly during traversal and use a modCount variable during traversal. If the contents of the collection change during traversal, the value of modCount is changed. Whenever the iterator iterates over the next element using hashNext()/next(), it checks whether the modCount variable is the expectedmodCount value and returns the traversal if it is; Otherwise, an exception is thrown and the traversal is terminated

Fail-safe

A collection container with a security failure mechanism is not accessed directly on the collection contents, but copies the original collection contents first and iterates over the copied collection

Principle: as the iteration is to traverse the copies of the original collection, so in the process of traversing the changes to the original collection and cannot be detected by the iterator, so will not trigger a ConcurrentModificationException

Faults: based on the copy content has the advantage of avoiding the ConcurrentModificationException, but by the same token, the iterator can not access to the contents of the modified, namely: iterators iterate over a collection of began to traverse the moment he got copies of the original collection during traversal of modifying the iterator is don’t know

Scenario: Containers under the java.util.concurrent package are security failures and can be used and modified concurrently in multiple threads.

How do I ensure that a collection is not modified

You can use the collections.unmodifiablecollection (Collection C) method to create a read-only Collection, This change of set any operation will throw Java. Lang. UnsupportedOperationException anomalies

The iterator

Iterator

The Iterator interface provides an interface to iterate over any Collection. We can get an iterator instance from a Collection using the iterator method. Iterators replace Enumeration in the Java collection framework by allowing callers to remove elements during iteration

Iterator features: only one-way traverse, but more security, because it can guarantee that in the current traverse a collection of elements are changed, will throw ConcurrentModificationException

How do I iterate over and delete elements in a Collection

Iterator<Integer> it = list.iterator();
while(it.hasNext()){
   *// do something*it.remove(); } list.remove(I)Copy the code

What is the difference between Iterator and ListIterator

ListIterator iterates through sets and lists, whereas ListIterator iterates through lists in one direction, ListIterator implements the Iterator interface and then adds some additional functionality, such as adding an element, replacing an element, and getting the index position of the preceding or following element

The Set interface

Talk about HashSet

HashSet is implemented based on HashMap. The value of HashSet is stored on the key of HashMap, and the value of HashMap is presented. Basically, it is completed by directly calling the underlying hashmap-related methods

private static final Object PRESENT = new Object();
Copy the code

HashMap compares hashCode first and then equals, so keys are not duplicated

public boolean add(E e) {
	return map.put(e, PRESENT)==null;
}
Copy the code

TreeSet with TreeMap

The Map interface

Talk about a TreeMap

TreeMap is implemented based on a red-black tree. The average and worst time complexity of adding, deleting, modifying, and querying is O(LOGN). The Key is ordered

HashMap relies on hashCode and equals to cancel weights, while TreeMap relies on Comparable or Comparator. TreeMap sorted, if the comparator is not null would prefer using the comparator compare method, or use the Key to achieve Comparable compareTo method, neither meet throws an exception

The operation of red-black trees is described in HashMap

Comparable and Comparator interfaces

Comparable is an interface implemented by a class and a comparaTo method implemented within the class. Comparable is also called an internal comparator. Classes that implement the Comparable interface have one thing in common: they can be compared to themselves. How they compareTo another class that implements the Comparable interface depends on the implementation of the compareTo method

public interface Comparable<T> {
    public int compareTo(T o);
}
Copy the code

When using a Comparator, you write a class that implements the Comparator interface. Use this class as a dedicated Comparator, passing it in as an argument where it is needed. An object implemented the Comparable interface, but the developer decided that the comparison in the compareTo method was not what he wanted

public interface Comparator<T> {
    int compare(T o1, T o2);
}
Copy the code

Ascending descending notation

Here O1 represents the preceding object and O2 represents the following object

Return -1 (or negative) to indicate that 01 and 02 do not need to be swapped, o1 is placed before O2, and ASC returns 1 (or positive) to indicate that 01 and 02 need to be swapped, o1 is placed after O2, and desc

conclusion

If you implement a class that does not implement the Comparable interface and want to compare two classes (or if your class implements the Comparable interface but is not satisfied with the Comparable algorithm in compareTo), you can implement the Comparator interface, define a Comparator, and write a comparison algorithm

The Comparable interface is implemented in a slightly more coupling way than the Comparable interface. If we were to change the Comparator algorithm, we would have to change the Comparable implementation class. The Comparable implementation class is external to the comparison. From this point of view, it’s not a good idea, especially when we make the implementation class’s.class file a.jar file for developers to use. In fact, the way you implement the Comparator interface, as described later, is a typical policy pattern.

HashMap

HashMap, Hashtable, ConcurrentHashMap (1.7, 1.8) source analysis + red-black tree

Queue

Characteristics of queues

A queue is a special linear structure. It only allows delete operations at the front of the table and insert operations at the rear. The end that inserts is called the end of the queue, and the end that deletes is called the head of the queue. The element inserted first in the queue will be deleted first, and the corresponding last inserted element will be deleted last. So queues are called FIFO — first in first out (FIFO — first in first out) linear tables, as opposed to stacks (filo-first in last out)

BlockingQueue

Four groups of API

way An exception is thrown No exception is thrown. There is a return value Block and wait Timeout waiting for
add add offer put Offer (” c “, 2, TimeUnit. SECONDS)
delete remove poll take poll(2,TimeUnit.SECONDS)
Determine the first element of the pair column element peek

IO and NIO

JavaIO flow

Block vs. non-block

Blocking and non-blocking are ways of dealing with whether the data is ready when the process accesses it.

When data is not prepared

Blocking: It is often necessary to wait until the data in the buffer is ready before doing anything else, or else wait forever.

Non-blocking: When our process accesses our data buffer, if the data is not ready, it returns without waiting, and if the data is ready, it returns

Blocking IO

Non-blocking IO

Synchronous and Asynchronous

Both synchronous and asynchronous are based on how applications and operating systems handle IO time

Synchronization: The application directly participates in I/O reads and writes

Asynchronous: All I/O reads and writes are handed over to the operating system, and applications just wait for notifications.

In synchronous mode, we must block a method to wait for the I/O event to complete (block the I/O event or poll the I/O event). In asynchronous mode, all I/O reads and writes are handed over to the operating system. At this point, we can do other things without actually doing the IO operation, and when the operation completes the IO, our application will be notified.

For example,

Synchronous blocking: ordinary kettle boiling water, stand beside, take the initiative to see whether the water is boiling

Synchronous non-blocking: Go do something else, check every once in a while to see if the water is boiling, and then leave

Asynchronous blocking: Standing by and not actively checking to see if the water is boiling at regular intervals. If the water boils, the kettle notifies him automatically.

Asynchronous non-blocking: Go do something else, and the kettle notifies him automatically if the water boils. Asynchronous nonblocking

Therefore, the advantage of asynchrony compared to synchronization is that when we process IO data, we can use the resources consumed by waiting for other transactions to improve the performance of our service

Synchronous IO

Asynchronous I/o

conclusion

Synchronous and asynchronous are communication mechanisms, and blocking and non-blocking are invocation states

  • Synchronous I/O synchronization means that the user thread initiates an I/O request and waits or polls the kernel for the I/O operation to complete
  • Asynchronous I/O means that the user thread can continue to execute the I/O request. When the kernel completes the I/O operation, it notifies the user thread or invokes the callback function registered by the user thread
  • Blocking I/O indicates that the I/O operation can be returned to user space only after it is complete
  • Non-blocking I/O returns a status value immediately after an I/O operation is invoked, without waiting for the OPERATION to complete

NIO model

NIO (Non-blocking/New I/O)

NIO is a synchronous non-blocking IO model introduced in Java 1.4, corresponding to the java.nio package, which provides abstractions such as channels, selectors, and buffers. N in NIO can be interpreted as non-blocking, not just New. It supports buffer-oriented, channel-based approaches to I/O operations. NIO provides two different Socket channel implementations, SocketChannel and ServerSocketChannel, that correspond to Socket and ServerSocket in the traditional BIO model. Both channels support both blocking and non-blocking modes. For high-load, high-concurrency (network) applications, NIO’s non-blocking mode should be used for development

NIO non-blocking mode, is a thread from one channel to send request to read data, but it can only get the currently available data, if there is no data is available, you can get nothing, rather than keep thread block, so until data becomes can read, this thread can continue to do other things, a non-blocking write also is so, A thread requests to write some data to a channel, but without waiting for it to write completely, the thread can do something else in the meantime. Threads typically spend idle time of non-blocking IO performing IO operations on other channels, so a single thread can now manage multiple input and output channels

The characteristics of the NIO

  • One thread can handle multiple channels, reducing the number of threads created
  • Read and write is non-blocking, saving resources. When there is no writable readable data, there will be no blocking resulting in waste of thread resources

Core components

Channel

A Channel is a bidirectional Channel. Unlike traditional IO operations that only allow one-way reads and writes, NIO channels allow read and write operations on one Channel, replacing traditional BIO streams. Instead of accessing data directly, NIO channels read data through buffers and interact with other channels

The main implementation

FileChannel, SocketChannel, ServerSocketChannel, DatagramChannel

Buffer

Buffer is a Buffer, which is actually a container, a continuous array. Channel provides a Channel to read data from a file or network. However, the read and write data must pass through Buffer

A Buffer is essentially a block of memory from which data can be written and then read. The block of memory is wrapped as a NIO Buffer object and provides a set of methods for easy access to the module’s memory. To understand how Buffer works, you need to be familiar with its three properties:

  • Position: position where data is read or written next time
  • Limit: indicates the limit position of read and write operations
  • Capacity: indicates the maximum capacity

How to use it: Write data to Buffer, call flip to switch to read mode, read data from Buffer, and call clear or Compact to clear the Buffer

  • flipSet position to 0 and limit to the current position
  • clearConvert read to write mode (for reading all data, set position to 0 and limit to Capacity)
  • compactConvert read to write mode (used when there is unread data and position points to the next unread data)

The direction of the channel is opposite to that of the Buffer. Reading data is equivalent to writing data to and reading data from the Buffer

Selector

Polling checks the state of multiple channels to determine whether the registration event occurs, that is, whether the Channel is in readable or writable state. Before applying, the Channel needs to be registered in the Selector, and a SelectionKey will be obtained after registration. Retrieves information about channels and selectionkeys

BIO model

BIO (Traditional IO)

  • BIO is a synchronous and blocking IO mode, traditionaljava.ioPackages, implemented based on the flow model, provide some of the most familiar IO features, such asFile Abstract, input and output streamsAnd so on.The interaction mode is synchronous and blocking
  • When an input stream is read or an output stream is written, the thread blocks until the reads and writes are complete, and the calls between them are in a reliably linear order
  • The server implementation pattern is one thread for each connection request, the server needs to create a thread for each client request, if the connection does nothing will cause unnecessary thread overhead. This type of I/O is called pseudo asynchronous I/O. It applies to scenarios where the number of connections is small and the number of server resources is large

Java BIO vs. NIO

IO model BIO NIO
communication Facing the flow Facing the buffer
To deal with Blocking IO Non-blocking IO
The trigger There is no The selector

AIO concept

AIO is asynchronous non-blocking IO introduced in JDK7. The server implementation mode is that each valid request corresponds to one thread. The OS of the client completes THE I/O operation first and then notifies the server application to directly use the prepared data. This mode applies to the scenario where the number of connections is large and the connection duration is long

The implementation methods include blocking callback through the Get method of the Future and implementation of the CompletionHandler interface, completed callback method for rewriting a successful request and failed callback method for rewriting a failed request

What are the types of JavaIO flows

  • According to the flow direction, the flow can be divided into input flow and output flow
  • According to the operation unit, it can be divided into byte stream and character stream
  • Flows are divided into node flows and processing flows according to their roles

Character streams are used for text files, and byte streams are used for images and other files

The character stream includes the character inputStream Reader and the character OutputStream Writer. The byte stream includes the byte inputStream inputStream and the byte OutputStream OutputStream.

Character streams and byte streams have corresponding buffer streams. Byte streams can also be divided into character streams. The buffer stream has an 8KB buffer array to improve the read and write efficiency of the stream.

In addition to buffering streams, there are FilterReader, CharArrayReader, ByteArrayInputStream, and FileInputStream

JDK8 new features

Lambda expressions

Simplifies anonymous inner class code by allowing functions to be passed as arguments to methods

  • Why Lambda expressions

    • Avoid overdefining anonymous inner classes
    • The code can look neat
  • Definition of a functional interface

    • Any interface that contains only one abstract method is a functional interface
    public interface Runnable {
        public abstract void run(a);
    }
    Copy the code
    • For a functional interface, we can create its interface object through a Lambda expression
    interface Love {
        void lambda(int a);
    }
    
    Love love = (inta) -> {... }Copy the code
  • Lambda expression simplification

    • Remove parameter types
    love = (a) -> {... }Copy the code
    • Remove the parenthesis
    love = a -> {... }Copy the code
    • Remove curly braces
    love = a -> ...
    Copy the code
    • Multiple parameter case
    love = (a, b, c) -> ...
    Copy the code

Functional interface

Enter T type to return R type

public interface Function<T.R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
Copy the code

The instance

/ * * *@author: zsy *@date: Created 2021/4/21 19:26 *@description: functional interface */
public class Demo1 {
    public static void main(String[] args) {
        Function<String, String> function = str -> {returnstr; }; System.out.println(function.apply("zhangsna")); }}Copy the code

Deterministic interface

Enter type T to return Boolean

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
Copy the code

The instance

/ * * *@author: zsy *@date: Created 2021/4/21 19:29 *@description: Indicates a qualitative interface */
public class Demo2 {
    public static void main(String[] args) {
        Predicate<String> predicate = str -> {returnstr.isEmpty(); }; predicate.test("zhangsan"); }}Copy the code

Consumer interface

As long as the input type, no return type

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
Copy the code

Supply interface

Only return type, no input type

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get(a);
}
Copy the code

The instance

/ * * *@author: zsy *@date: Created 2021/4/21 19:37 *@description: consumer interface and supply interface */
public class Demo3 {

    public static void main(String[] args) {
        Consumer<String> consumer = o -> System.out.println(o);

        Supplier<Integer> supplier = () -> 1024; }}Copy the code

Method references

You can further simplify lambda expressions by referring to methods and constructors of existing classes or objects

interface

The interface can define default methods modified by default, reducing the complexity of interface upgrades, and static methods can be defined.

annotations

Introduce repeated annotation mechanism, the same annotation can be declared multiple times in the same place. Annotations have also been extended to apply to local variables, generics, method exceptions, and so on.

Type conjecture

Strengthened type speculation mechanism, making the code more concise.

Optional class

Handle null pointer exceptions to improve code readability.

The Stream class

The introduction of functional programming style, providing a lot of functionality, make the code more concise. Methods include forEach traversal, count statistics, filter based on conditions, limit taking the first N elements, Skip skipping the first N elements, Map mapping processing, concat merging stream, etc.

The date of

Enhanced date and time apis, the new Java.time package mainly contains operations dealing with date, time, date/time, time zone, time, and clock.

JavaScript

A new JavaScript engine is provided that allows specific JavaScript applications to run on the JVM.