Java learning record

Posted by Leveecius on Mon, 07 Mar 2022 12:00:57 +0100

Java quick start

Java Basics

  • The biggest feature of Java is cross platform

  • Javase (Personal Edition), JavaEE (Enterprise Edition), javame (Micro Edition, for consumer electronics development)

  • Java is similar to Windows

Java running mechanism

  • Running process: source file (. Java) - [javac compiler] --- > bytecode (. Class) - [JVM virtual machine] --- > executable program

  • Relationship between JDK and JRE JVMs

    JDK(Java Development Kit)

    Debugger, compiler (javac)

    ​ JRE(Java Runtime Environment)

    Library function

    ​ JVM(Java Virtual Mechine)

Java Procedure

Overloading of methods

Definition: same name, different parameters (similar functions are required)

int add(){...}; int add(int a){...}

object-oriented

  • Object is similar to a table and consists of attributes and methods
  • Object oriented is a kind of designer thinking, assembly

Memory mechanism

  • Stack: responsible for function operation, and main starts
  • Heap: the part responsible for storing objects
  • Method area: responsible for storing the invariant parts of the class (methods, constants)

Garbage collection mechanism

Principle:

  • Java's memory management is mostly the release of objects in the heap
  • The heap is divided into three parts: young generation (Eden District + Survivor1 District + Survivor2 District), old generation and permanent generation (metadata space)
  • There are three kinds of recyclers: Mini GC (responsible for the younger generation), major GC (responsible for the older generation) and full GC (all can be responsible)
  • System.gc() can advise the system to perform garbage collection

Algorithm:

  • Reference counting method
  • Citation reachability method

Static and normal

Common attributes and methods have this pointer (implicit parameter), which distinguishes the same common attributes as local variables, such as this A=a, which is displayed in the constructor when it calls the overloaded constructor, such as

Test(int a, int b){
    this.Test(a);
    ...
}

Static attributes and static methods do not have this pointer, but have static construction methods, which are used for the initialization of static attributes, i.e

static{
    ...
}

package and import

The function of package is to classify and store classes, make them organized, and solve the problem of class homonymy to a certain extent.

There are two types of import

  • Import class
import java.lang.Math; //Import Java Lang. math class
import java.lang.*; //Import Java All classes under Lang package
  • Import static variables or static methods
import java.lang.Math.PI; //Import PI static variables
import java.lang.Math.random; //Import random() static method
import java.lang.Math.*; //Import all static variables and methods under Math class

Override

requirement:

  • ==: the method name and formal parameter list are the same
  • < =: return value type, declaration exception type, subclass less than or equal to parent class
  • >=: access permission. The subclass is greater than or equal to the parent class

combination

Object holds another object

encapsulation

objective

  • High cohesion and low coupling: high cohesion refers to the completion of the internal data operation details of the class, and external interference is not allowed; Low coupling means that only a small number of methods are exposed for external use to facilitate external calls as much as possible. For example: the mobile phone is highly cohesive. All the internship details are encapsulated in the mobile phone shell and run independently. The mobile phone is also low coupling. There are only screens, charging ports, switches and volume adjustment buttons for the outside.

realization

  • private: class friendly

  • (default): in package friendly

  • protected: in bag friendly, father son friendly

  • public: Global friendly

get set method

The general method of encapsulation is to set all properties to private, and then access them externally through the set get function.

polymorphic

For the same method, different objects call different methods

Object type conversion

  • Convert up (subclass to parent): automatic conversion
  • Convert down (parent to child): force conversion of (subclass type) objects

abstract class

Abstract method: only the method name is not implemented, preceded by abstract.

A class containing abstract methods is an abstract class. An abstract class cannot produce objects, and subclasses must implement the abstract methods of the abstract parent class.

Interface

Basic format:

Control character interface Interface name [extends Interface 1, Interface 2, ...]{
    //constant
    /*public abstract final*/Data type variable name = value;
    //Abstract method
    /*public abstract*/Return type method name(parameter list );
    //Default method
    default Return type method name(parameter list ){...}
}

An interface is a rule that needs to be implemented by a class

Inner class

Internal class is born for encapsulation and is a concept only available for compilation

There are four internal classes:

  • Member inner class

    • Non static inner class

    • Static inner class

  • Anonymous Inner Class

Use it only once, so you don't need a name

  • Local inner class

Define classes in methods

array

Array creation

Initialization of array

  • initiate static
  • dynamic initialization
  • Default initialization

Common operations of array

Array traversal

  • for(int i=0; i < array.length; ++i)
    
  • for(int i:array)
    

Array copy

Printing, sorting, searching and filling of arrays

Using methods in the Array class

  • Printing: array ToString (array object)

  • Sorting: array Sort (array object). This kind of array object needs to implement the comparable interface, and the compareTo() method in comparable needs to be implemented

  • Find: array Binarysearch (array object, find element)

  • Fill: array Fill (array object, start pos, end pos, fill element)

Two dimensional array

That is, the array of arrays

summary

  • Inclusion relationship of JDK, JRM and JVM

  • .java --javac-->. Class -- JVM -- > executable

  • Basic data classification and reference type (basic data types also have corresponding application types)

  • Classes and objects

  • pacakage Package name;
    
    import Package name.Class name(*);
    import static Package name.Class name.Static method;
    
    /*
    Class members include properties, methods, and inner classes
     Classes and members have modifiers:
       1.public protected default private
       2.static final abstract
    */
    
    public class Class name(Consistent with file name) [extends Parent class name]{
        //attribute
        //Construction method
        Modifier construction method(parameter list ){
            
        }
        //method
        
        //Static inner class
        public static class A{
            //Static member
        }  
        
        //Non static inner class
        public class B{
            
        } 
    }
    
    
  • Storage of classes and objects (JVM memory model)

    • Stack (storage method, starting from main method)
    • Heap (object)
    • Method area (method, static member, constant pool)
  • Interface

    public interface Interface name [extends Interface 1, Interface 2, ...]{
        [public static final] Type name property name = value;
        [public abstract] Return type name and method name(parameter list);
        
        //Supplementary default method
        default Return type name and method name(parameter list );
        
        //Supplementary static method
        static Return type name and method name(parameter list );
    }
    
  • encapsulation

    Scope of public protected (default) private

  • inherit

    • Class inheritance (single) interface inheritance (multiple)
    • super
    • Override @ override
  • polymorphic

Deepening and improving Java Foundation

Generics and generic classes

container

Basic structure

  • Collection interface

    • Set interface

      • HashSet class
      • LinkedHashSet class
      • TreeSet class
    • List interface

      • ArrayList class
      • LinkedList class
      • Vector class
  • Map interface

    • HashMap class
    • LinkedHashMap class
    • TreeMap class
    • Properties class
    • HashTable class

Collections interface

//View basic information
int size();
boolean isEmpty();
//Add / delete operation
boolean add(Object element);
boolean addAll(Collections c);
boolean remove(Object element);
boolean removeAll(Collections c);
boolean retainAll(Collections c); //Only elements that intersect with container c are retained
void clear();
//see
boolean contains(Object element); //Whether to include an element
boolean containsAll(Collections c);
//iterator 
Iterator iterator(); //Returns an iterator for container traversal
//conversion
Object[] toArray();  

List interface

Features: orderly + repeatable

//Add operation
boolean add(int index, Object element);
//Delete operation
boolean remove(int index);
//Modify operation
boolean set(int index, Object element);
//Find / view
Object get(int index);
int indexOf(Object element);
int lastIndexOf(Object element);

ArrayList class

characteristic:

  • It is realized through array, so the search efficiency is high and the operation efficiency of addition and deletion is low
  • Thread unsafe

IO

Basic concepts

Input / output stream

  • Input stream: program external -- > internal
  • Output stream: program internal -- > external

data source

  • Source device: the device that sends data
  • Target device: the device that receives data

Node flow, processing flow (packaging flow): like a pipe, a flow can be nested

  • Node flows: flows that directly link data sources
  • Process flow: a flow that wraps other flows

4 IO abstract classes

byte

  • InputStream

method:

int read(); //For byte reading, a decimal number of 0-255 is returned if the reading is successful, and - 1 is returned if the reading is failed
void close(); //Close flow

·Subclass:

Node flow:
FileInputStream;  //Operation file
ByteArrayInputStream; //Operation byte array
 Process flow:
ObjectInputStream; //Operation object
DataInputStream; //Operation basic data type and string type
BufferdInputStream; //Increase cache function to provide efficiency
  • OutputStream

method:

void write(int ); //Write a byte
void close(); //Close flow

Subclass:

Node flow:
FileOuputStream;
ByteArrayOuputStream;
Process flow:
ObjectOutputStream;
DataOutputStream;
BufferedOutputStream;
PrintStream;

character

  • Reader

method:

int read(); //For character reading, a decimal number of 0-65535 is returned if the reading is successful, and - 1 is returned if the reading is failed
void close(); //Close flow

Subclass:

Node flow:
FileReader;
Process flow:
BufferedReader;
  • Writer

method:

void write(int ); //Write a character
void close(); //Close flow

method:

Node flow:
FileWriter;
Process flow:
BufferedWriter;

File class

The File class is a wrapper class that handles disk files or directories

method:

//initialization
File(String path); //Relative path acquisition method: system Property("user.dir");
//Create file / directory
boolean createNewFile();
boolean mkdir();
boolean mkdirs();
//Delete file
boolean delete();
//operation
String getPath();
...

Multithreading

Basic concepts

  • Program: executable file (static), which is usually placed on disk and run in memory when needed;

  • Process: a process is a run of a program in memory, which monopolizes a piece of memory space and is composed of several threads (at least one), code and data;

  • Thread: a thread is a linear execution unit running in a process. Data is shared between threads in the same process (sharing and mutual exclusion problem occurs)

  • Main thread: the thread that starts with the main method

  • Sub thread: a new thread created by the main method

Threads in java

Thread

Runnable

Thread control

  • Thread end
  • Thread pause
    • sleep(long s); Enter the blocking state and return to the ready state after a certain time
    • yeild(); Enter the ready state and give cpu resources to other threads of the same priority

Thread Union

join function. The added thread can run only after the added thread runs

thread priority

t.setPriority(5);
t.start();
System.out.println(t.getPriority());

Daemon thread

Threads are divided into user threads and guard threads. Guard threads are used to serve user threads, such as garbage collection. If the user thread dies, the guard thread also dies.

Thread synchronization

Basic knowledge of thread synchronization
java implementation of thread synchronization
  • Member variable
synchronized(Member variable object name){
    //Code blocks that need to be synchronized
}
  • this
synchronized(this){
    //Code blocks that need to be synchronized
}

synchronized public void func(){
    
}
  • Class name class
synchronized(Class name.class){
    //Code blocks that need to be synchronized
}

synchronized public static void func(){
    //Code blocks that need to be synchronized
}

Concurrent collaboration of threads

Model: Producer (thread) - > [buffer] -- > consumer (thread)

effect

  • Logically realize the separation of survivor thread and consumer thread, and release the coupling between them
  • The speed between producer thread and consumer thread is coordinated to improve efficiency

Communication between threads

  • wait
  • notify
  • notifyAll

Communication + syn mechanism can realize the producer consumer model

Network programming

Basic concepts

computer network

A system that links computers in different places through communication lines and realizes computer resource sharing and information communication under the management and coordination of network operating system, network management software and network communication protocol

Network communication protocol

  • Agreement: standards and rules. Similarly, the communication between humans needs a common language, and the information exchange between computers also needs the same set of rules.
  • Computer communication is too complex, so it is layered, including IOS model (Theory) and TCP/IP model (industry). Each layer has a corresponding protocol.
  • Under the guidance of the model, the communication between computers is a process of layer by layer packaging (sender) and then layer by layer splitting (receiver).

Encapsulation (splitting) and unpacking (merging) of data

why: the amount of data is too large to be transmitted at one time. It needs to be sent in order after segmentation;

what: the sender splits and encapsulates the data layer by layer until the physical media is transmitted, and the receiver splits the received data

how: because each layer of encapsulation and unpacking is a principle, we only discuss one layer here. The function of layer i is to transmit the data provided by layer i+1. The sender first splits the data PUD from the upper layer and then packages it, transmits it by using the service established at the lower layer, and then merges it after the receiver receives the data.

IP address and port number

  • IP: identify computer
  • Port number: identifies the service

URL

Composition: HTTPS (Protocol) 😕/ www.baidu. Com (domain name) [port number] / index HTML (file)

Role: identify computer resources (directories, files, references to complex objects)

Socket

Function: it creates a bridge between the application layer and the transport layer. It is the programming interface provided by the transport layer, so that the application can communicate with the network

TCP UDP

TCP

Located in the transport layer, reliable transmission mode, establish virtual link, disconnect virtual link, similar to making a phone call

3 handshakes and 4 waves

UDP

It is located in the transmission layer and is not reliable

Common classes in Java network programming

Socket programming sequence

  • The server creates a ServerSocket object and sets the listening interface;

  • The ServerSocket object calls the accept() method and keeps it in a blocking state, waiting for the link from the client;

  • The client creates a Socket object and sets the IP and Port to connect to the server;

  • The client sends a request, and the client establishes a link with the server;

  • Obtain the built InputStream and OutStream stream objects of the client and server through the Socket object;

  • Streaming data between client and server;

  • Close stream close Socket object

  • Information: the posts are limited and will disappear too late. Therefore, we should grasp the time. The two opportunities should be faster. It is expected to be cast before March 20

  • Is there any danger of interview or interview failure? No, it's beneficial. It's good to exercise your courage and learn interview experience! So don't be afraid and interview boldly