Java language programming - Final Review

Posted by zizzy80 on Wed, 09 Feb 2022 04:31:56 +0100

Chapter 1 first contact with Java

1. Understand the differences and relationships among JRE, JDK and JVM

JVM: the English name (Java Virtual Machine) is the familiar Java Virtual Machine. It only knows XXX Class this type of file, which can recognize the bytecode instructions in the class file and call the up API of the operating system to complete the action. Therefore, JVM is the core of Java's ability to cross platform, which will be described in detail below.

JRE: English name (Java Runtime Environment), we call it: Java Runtime Environment. It mainly includes two parts, the standard implementation of jvm and some basic class libraries of Java. Compared with the jvm, it has more Java class libraries.

JDK: English name (Java Development Kit), Java Development Kit. JDK is the core of the whole Java development. It integrates jre and some useful gadgets. For example: javac exe,java.exe,jar.exe, etc.

Obviously, the relationship between the three is: a layer of nested relationship. JDK>JRE>JVM.

2. Why can Java be written at one time and run in multiple places across platforms?

  the core of Java's ability to run across platforms lies in the JVM. Not Java can cross platform, but its JVM can cross platform. We know that the upward APIs of different operating systems must be different. If we want to write a piece of code to call the sound device of the system, we need to write different codes for the APIs of different systems to complete the action.

  Java introduces the concept of bytecode. The jvm can only recognize bytecode and interpret them into the API calls of the system. There are different jvm implementations for different systems, including Linux version and Windows version, but the bytecode of the same code after compilation is the same. Citing the above example, at the Java API level, the code we call the system sound device is unique, independent of the system, and the bytecode generated by compilation is also unique. However, the same bytecode will be mapped to API calls of different systems on different jvm implementations, so that the code can run across platforms without modification.

Chapter 2 fundamentals of Java language

1. Data type

(1) Basic types (8)

Integer type: byte(8 bits), short(16 bits), int(32 bits), long(64 bits)

Floating point type: float(32-bit), double(64 bit)

Character type: char(16 bits)

boolean type: boolean

(2) Composite type

Class
Interface
array

2. Type conversion
3. Logical expression (Boolean value, not int, etc.)
4. The new version type of expression in switch (expression) is OK
5.break lab; Jump out of multiple loops

Chapter 4 object oriented (Part I)

1. Objects send messages to each other

(1) The reference must refer to a specific object, otherwise a NullPointerException exception will be thrown at runtime
(2) The object must have corresponding properties or methods defined, otherwise the compilation will not pass
(3) The accessed property or method has accessible permissions

2. Distinguish between object and object reference

(1) Create object:
new IntClass();
Objects are allocated on the heap.

(2) Declare an object reference:
IntClass ic;
Object references are allocated on the stack.

(3) Initialize object reference:
ic = new IntClass();

Example 1:
Object memory space distribution:
IntClass ic = new IntClass();
   the essence is to assign the address of the created IntClass object to the object reference ic, from which the ic is associated with the object, and the object can be manipulated through the ic.

Example 2:
Characteristics of object as parameter:
   ordinary data types are passed by value as parameters, while objects are passed by reference.

public class Test{
	private static int a;
	public static void main(String [] args){
		modify(a);
		System.out.println(a);
	}
	public static void modify(int a){
		a++;
	}
}

   the output of this program is 0, because a + + increases the formal parameters, not the class attribute a.

3 cases:
Example of reference passing of object:
   an object is passed by reference. When an object is passed as a parameter, the address of the object is passed.

class IntClass{
	int value;
}
public class test {
	private static int a;
	public static void main(String [] args){
		IntClass a = new IntClass();
		modify(a,8);
		System.out.println(a.value);
	}
	public static void modify(IntClass s, int val){
		s.value = val;
	}
}

Output: 8

3. Distinguish between Java and C++

Java: only when you use the new operator can you really apply for a space in memory, create a new object, and bind the object to the variable name you define. In other cases, either bind the existing object to a variable name, or the defined variable name is an empty reference without binding any object.
    that is, defining a variable name only creates a new identifier, which has nothing to do with creating an object. Creating an object must be completed through new, and memory space will be applied only when creating an object.

It means that when you create a new identifier in C + +, it also means that you don't have a corresponding identifier in the stack.
    therefore, the variable name defined in C + + is not only an identifier, but also automatically associated with a memory space in the stack.
    the new operator in C + + means to apply for memory in the heap. Because the size of memory in the stack is fixed and limited at run time, it needs to be implemented with new when dynamic memory allocation is needed. This is similar to the malloc function in C, but the new operator also encapsulates other operations.

    in summary, the variable name in Java is just an identifier used to refer to the actual object in memory. If you don't associate it with an object, it will be an empty reference. Although the variable name (non pointer type) in C + + is also an identifier, it is always associated with the actual memory space. When we see a variable (non pointer type), we know that it represents an actual memory space.

4. Create an array (array is an object)

1. One dimensional array

A. Statement
(1)int

int[] test_int;

(2)String

String[] test_String;

(3) Custom class

MyClass[] test_mc;

(4) Object array

Integer[] test_Integer;

B. Initialize
a. Use the keyword new to define
Type identifier [] array name = new type identifier [array length];

(1)int
An array object of type int with 10 cells is generated, and the initial value of all cells is 0

int[] test_int = new int[10];

or

int[] test_int;
test_int = new int[10];

(2)String
Generate an array object with 10 cells of type String, and the initial values of all cells are null

String[] test_String = new String[10];

or

String[] test_String;
test_String = new String[10]; // Note: do not write as new String(10)

(3) Custom class
Generate an array object with 10 cells and type MyClass, and the initial values of all cells are null

MyClass[] test_mc = new MyClass[10];

or

MyClass[] test_mc;
test_mc = new MyClass[10];

(4) Object array
An array object of type Integer with 10 cells is generated, and the initial values of all cells are null

Integer[] test_Integer = new Integer[10];

or

Integer[] test_Integer;
test_Integer = new Integer[10];

b. Initialize directly at the time of declaration
Note: this definition method can only be in one line of code and cannot be separated.

(1)int

int[] test_int = {1,2,3};

(2)String

or

String[] test_String = {"ab","cd","ef"};

or

String[] test_String = {new String("ab"),new String("cd"),new String("ef")};

(3) Custom class

MyClass test_mc1 = new MyClass();
MyClass test_mc2 = new MyClass();
MyClass test_mc3 = new MyClass();
MyClass[] test_mc = {test_mc1,test_mc2,test_mc3};

(4) Object array

Integer[] test_Integer = {3,5};

or

Integer[] test_Integer = {new Integer(3), new Integer(5)};

c. Use the following methods to define and initialize
(1)int

(2)String
String[] test_String = new String[] {"ab","cd","ef"};
or

int[] test_int = new int[] {1,2,3};

(2)String

or

String[] test_String = new String[] {"ab","cd","ef"};

or

String[] test_String = new String[] {new String("ab"), new String("cd"), new String("ef")};

(3) Custom class

(4) Object array
Integer[] test_Integer = new Integer[] {1,2,3};
or

MyClass test_mc1 = new MyClass();
MyClass test_mc2 = new MyClass();
MyClass test_mc3 = new MyClass();
MyClass[] test_mc = new MyClass[] {test_mc1,test_mc2,test_mc3};

(4) Object array

or

Integer[] test_Integer = new Integer[] {1,2,3};

or

Integer[] test_Integer = new Integer[] {new Integer(1), new Integer(2), new Integer(3)};

C. Use the foreach statement to traverse a one-dimensional array
(1)int

public class MyClass {
public static void main(String[] args) {
	int[] test_int = new int[10];
	test_int[0] = 1;
	for(int x: test_int) {
		System.out.println(x + " ");
	}
}
}

Output: 1 0 0 0 0 0 0 0 0 0

(2)String

public class MyClass {
	public static void main(String[] args) {
		String[] test_String = {"ab","cd","ef"};
		for(String x: test_String) {
			System.out.print(x + " ");
		}
	}
}

EF CD: AB output

(3) Custom class

public class MyClass {
	public int value = 1;
	public static void main(String[] args) {
		MyClass test_mc1 = new MyClass();
		MyClass test_mc2 = new MyClass();
		MyClass test_mc3 = new MyClass();
		MyClass[] test_mc = {test_mc1,test_mc2,test_mc3};
		for(MyClass x: test_mc) {
			System.out.print(x.value + " ");
		}
		System.out.println();
		for(MyClass x: test_mc) {
			System.out.print(x + " ");
		}
	}
}

Output: 1
test . MyClass@15db9742 test. MyClass@6d06d69c test . MyClass@7852e922

(4) Object array

public class MyClass {
	public int value = 1;
	public static void main(String[] args) {
		Integer[] test_Integer = {new Integer(3), new Integer(5)};
		for(Integer x: test_Integer) {
			System.out.print(x + " ");
		}
	}
}

Output: 3 5

2. Two dimensional array

A. Statement
(1)int

int[][] test_int;

(2)String

String[][] test_String;

(3) Custom class

MyClass[][] test_mc;

(4) Object array

Integer[][] test_Integer;

B. Initialize
Array name = new type specifier [array length] [];

Array name = new type specifier [array length] [array length];

For dimensions that are not initialized, the value is null:

int arr[][];
arr = new int[3][4];

It is equivalent to the following four statements:

arr = new int[3][]; // Create an array with 3 elements, and each element is also an array
arr[0] = new int[4]; // Create an array of arr[0] elements, which has 4 elements
arr[1] = new int[4]; // Create an array of arr[1] elements, which has four elements
arr[2] = new int[4]; // Create an array of arr[2] elements, which has four elements

It is equivalent to:

arr = new int[3]\[];
for(int i=0;i<3;++i) arr[i] = new int[4];

For two-dimensional arrays, when only one-dimensional arrays are defined, the dimensions of the other dimension can be different, that is, it is not necessarily a regular matrix form. For example:

int[][] arr;
arr = new int[3][];
arr[0] = new int[3];
arr[1] = new int[2];
arr[2] = new int[1];

C. Use the foreach statement to traverse a two-dimensional array

for(int[] arr1: arr){
for(int x: arr1){
	System.out.print(x + " ");
}
System.out.println();
}

5. Create object initialization sequence

(1) The system initializes data members by default
(2) Execute initialization statement at data member definition
(3) Call the constructor to specify the initial value for the data member

class IntClass {
	int value; // Automatic initialization, the default value is 0
	// int value = 5; //  Specify initialization statement when defining

	public IntClass() {}

	// Define a constructor to initialize the attribute value
	public IntClass(int val) {
		value = val;
	}
}
public class IntClassConstructor {
	public static IntClass getInstance() {
		// Call the constructor to omit the s, value code
		IntClass s = new IntClass(8);
		// s.value = 8;
		return s;
	}

	public static void main(String args[]) {
		IntClass a = new IntClass();
		System.out.println(a.value);
		a = getInstance();
		System.out.println(a.value);
	}
}

Output:
0
8

6. Garbage collection mechanism
7. Data members are also called fields
8.final modifier constant
9. package organization

Chapter 5 object oriented (middle)

1. Three characteristics of objects: encapsulation, inheritance and polymorphism

1, Encapsulation

1. Concept
   encapsulation is to bind data and data-based operations by using abstract data types (classes). The data is stored in the abstract data type, and the system can access the data only through authorized operation methods.

  encapsulation is the core idea of object-oriented programming

characteristic:
(1) Data and data-based operator a Fei form a unity
(2) The implementation details of the operation method of the class are hidden and only called through the name of the operation interface. Changes within the operation will not affect the use of the interface

2. Advantages
  data can only be accessed through specified methods
  hide class implementation details
  easy to modify and realize
  easy to add control statements

3. Application
   modify the visibility of attributes: public, protected, private, "default" (without any modifiers)
  create a public method for reading and writing attributes
   add a control statement to the attribute reading and writing method to judge the legitimacy of the attribute value

public class People{
 public String name; // public
 protected int age; // under protection
 char sex; // default
 private int money; // private

 public int getMoney() { // Public methods are used to read properties
 	if(money<0) return 0; // Judge the legitimacy of attribute value
     return money;
 }

 public void setMoney(int money) { // Public methods are used to write attributes
 	if(money<0) this.money = 0; // Judge the legitimacy of attribute value
     this.money = money;
 }
}

4.This keyword
   this calls the class attribute, that is, the domain variable / class field / class data member of the class
  this calls other methods in this class
   this calls other construction methods in this class. When calling, it should be placed in the first line of the construction method

public class test {
 public int money; // Member properties / class fields

 public test(){ // Construction method 1
     this(233);  // this keyword calls other constructors in the class
 }

 public test(int a){ // Construction method 2
     this.fun(); // this keyword calls other methods in the class
     System.out.println(a);
 }

 public void fun(){
     this.money = 666; // Use the this keyword to assign values to member properties
     System.out.println(this.money); // Use this keyword to call the class field
 }

 public static void main(String[] args) {
     test myMoney = new test();
 }     
}

2, Inherit

1. Concept
  inheritance is a cornerstone of Java object-oriented programming technology because it allows the creation of hierarchical classes.

   inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the class inherits the method from the parent class, so that the subclass has the same behavior as the parent class.

2. Features
  inheritance encourages class reuse
  inheritance can be multi-level
  a class can only inherit one parent class (single inheritance)
  private modified in the parent class cannot be inherited
  constructor cannot be inherited
  inherited keyword extends

3. Application
(1) Parent class

public class Father {
	/*Member properties*/
    public String name; // public
    public int age; // public
    public char sex; // public
    
	/*Construction method*/
	public Father(){
        System.out.println("Father Nonparametric construction method");
    }
    public Father(String name){
        this.name = name;
        System.out.println("Father Parametric construction method, Father Your name is:"+this.name);
    }
	
	/*Member method*/
    public void say() { // public
        System.out.println("Father Can speak");
    }
    public void eat(){ // public
        System.out.println("Father Can eat");
    }    
}

(2) Subclasses access parent class member properties
Access parent class attribute: super name; (can be used in other methods and construction methods)

public class Son extends Father {
    public Son(String name){
        super.name = name; // Assign a value to the parent class member property
        System.out.println(super.name); // Access parent class member properties
    }
    
    public void fun(){
        System.out.println(super.name);
    }
    
    public static void main(String[] args) {
        Son son = new Son("xx");
        son.fun(); // Call the subclass fun function
    }
}

(3) Subclass access parent class constructor
To access the parent class constructor:

Construction method of parent class without parameters: super();
Construction method of parent class with parameters: super(name);
Note: the constructor that accesses the parent class can only be accessed in the constructor of the subclass, and must be the first line of the subclass constructor

public class Son extends Father {
    public Son(){
        super("**"); 
    }
    
    public static void main(String[] args) {
        Son son = new Son();
    }
}

(4) Subclass access parent method
Access parent class method: super Method name ();

public class Son extends Father {
    public Son(String name){
        super.eat(); // Access the eat method of the parent class    
    }
    
    public void fun(){
        super.say(); // Access the say method of the parent class
    }
    
    public static void main(String[] args) {
        Son son = new Son("xx");
        son.fun(); // Call the subclass fun function
    }
}

Summary super keyword:

   super can only appear in subclass methods and construction methods
   when super calls the constructor, it can only be the first sentence
  super cannot access private members of the parent class

4. Restrictions on Succession

  parent class members that cannot be inherited:
  private member
   the subclass is not in the same package as the parent class, and the members with default access rights are used
  construction method

5. Multiple inheritance initialization sequence
  parent field / attribute
  parent class construction method
  subclass fields / attributes
   subclass construction method

Rewriting method
  in subclasses, you can override the methods inherited from the parent class as needed
   the overridden method and the overridden method must have the same method name, parameter list and return type
   overridden methods cannot use overridden methods

public class Son extends Father {
    public void say(){ // Subclass method override
        System.out.println("Son Can speak English");
        super.say();
    }
    
    public static void main(String[] args) {
        Son son = new Son();
        son.say();
    }
}

3, Polymorphism

1. Concept
Polymorphism refers to the coexistence of different methods with the same name in a program.
  Java provides two polymorphic mechanisms: Overloading and Overriding

2. Implementation ideas
(1) Write parent class
(2) Write a subclass that overrides the parent method
(3) At runtime, use the type of the parent class and the object of the child class

3. Three necessary conditions for realizing polymorphism
  succession
  rewrite
  parent class reference points to subclass object

public class Son extends Father {
    public void say(){ // Subclass method override
        System.out.println("Son Can speak English");
    }
    
    public static void main(String[] args) {
    	Father father = new Father();
        father.say();
        System.out.println();
        
        Father fatherson = new Son();
        fatherson.say();
        System.out.println();
        
        Son son = new Son();
        son.say();
    }
}

4. Heavy load
The method name is the same, but the parameter type or number is different.
Note: if the method names are the same, the parameters are the same, and the return types are different, the compilation will not pass.

class Parent {
	public int getScore() {
		return 3;
	}
	public int getScore() {
		return i;
	}
}

5. Coverage
   subclasses redefine the methods with the same name (the same method name, the same parameters and the same return type) of the parent class, that is, define methods with the same name but different contents in the subclass.

class Parent {
	public int getScore() { return 3; }
	public String getCountryName() { return "China"; }
}
class Son extends Parent {
	public int getScore() { 
		return 4; 
	}
	public void function() {
		System.out.println(super.getScore());
	}
	public static void main(String[] args){
		Son s = new Son();
		System.out.println(s.getScore());
		System.out.println(s.getCountryName());
		s.function();
	}
}

6. Difference between heavy load and coverage

Function nameparameterReturn valuestaticpolymorphic
withDifferentSame / differentheavy load
withwithwithheavy load
withwithwithDifferentDifferent functions
withwithDifferentCompilation failed

2. Minimum programming unit: class.
3. Combination of classes: in a class, object references of this class / another class are placed as data members
4. High cohesion and low coupling
5. Copy the meaning of the non static parent class and child class to the method instead of the parent class and child class
6.Object is similar to the common ancestor of all classes, even if extensions object is written when defining a class
7. The class modified by final is called the final class. It cannot have subclasses
8. Methods modified by final cannot be overridden in subclasses
9. The subclass method overrides the parent method, and the access modifier permission of the subclass should be equal to or greater than that of the parent
10. Static methods and non static methods with the same name cannot overlap each other
11. If there is an abstract method in an abstract class, the specific subclass must override the abstract method

Chapter 6 object oriented (Part 2)

1. There are three uses of this:
(1)this. Domain variable, this Member method
(2) This (parameter) -- refers to the overloaded construction method
(3) this refers to the current object
2.super can be used in two ways:
(1)super. Domain variable, super Member method (parameter)
(2) Super (parameter) -- inheritance call of construction method
If the domain variable name or member method name of the subclass is the same as the domain variable name or member method name of the parent class, the keyword super can be used to refer to the method with the same name of the parent class or the domain variable with the same name of the parent class.
3. Initialization sequence:
(1) Before calling any constructor, initialize the class field first
(2) Call the parent class constructor before calling the subclass constructor
4. Abstract class and abstract method [equivalent to pure virtual function in C + +]
5. interface is a collection of function method descriptions, in which all defined data members are final static (even without any modification, the effect is completely equivalent)
6. The interface has no construction method, and all member methods are abstract methods. Note that the method cannot be modified to final
7. Comparison between abstract class and interface:
(1) Common ground: both have abstract methods and cannot be instantiated. Each has its own declaration and can reference specific subclasses or implementation class objects.
(2) Different points

abstract classInterface
attributeCan have domain variablesCan't have domain variables, can only be static constants
Member methodThere can be concrete methods, and concrete methods can call abstract methodsIf there are methods, they are all abstract methods
Implementation strategyMust have subclass inheritanceThere must be an implementation class
Expansibilityweakstrong

8. Abstract class declaration can refer to all concrete subclass objects
9. The parent class declaration can refer to all specific subclass objects
10. Subclass declaration cannot refer to other class objects of parallel level, nor can it refer to parent class objects
11. The subclass object referenced by the parent class declaration can be assigned to the subclass declaration through explicit transformation (modeling cast), but the subclass object referenced by the subclass declaration does not need explicit transformation when assigned to the parent class declaration
12. For objects equals() compares references, and = = compares references
13.String uses equals() to compare values, and = = to compare reference addresses
14. The value is compared with = = value
15. Use instanceof to compare reference types:
Operator format: a instanceof A, where a is the reference of the object and a is the class.
Returns true if a is an instance of a or an instance of a subclass;
If a is an instance of a parent class, false is returned;
If the class of a object has no relationship with a, the compilation will not pass.
16. Inner class, anonymous inner class
17. External classes cannot directly access members in internal classes

Chapter 7 exceptions

1. Exception statement
2. Exception capture
3. Custom exception throw new exception class

Chapter 8 common Java class libraries and tools

1. equals of string is value comparison, which is strictly case sensitive. equalsIgnoreCase can be used to ignore case comparison
2. The characteristic of string is that once assigned, the character object it points to cannot be changed. If changed, it points to a new character object
3. Compiler automatic optimization:

String s = "Hello";
String t = "Hello"; // s and t point to the same character object

String s = "Hello";
String t = new String("Hello"); // s and t point to different character objects in memory

4.StringBuffer is a String object with the characteristics of object reference transfer (after String splicing and other operations, a new String object will not be created, but will be changed)
5.

6. The internal implementation of string is based on constant character array, and the content is immutable
7.StringBuffer (thread safe) and StringBuilder (non thread safe) are based on ordinary character arrays. The size of the array can be expanded and the content can be changed
8. Performance: StringBuilder > StringBuffer > string

Chapter 9 threads

1. There are two ways to create threads

(1) Inherit the Thread class and override its run method;

(2) Implement the Runnable interface and pass the implementation class object as a parameter to the construction method of Thread class.

2. Multithreaded access to shared resources -- > security issues -- > synchronized atomicity – > lock and deadlock

Chapter 10 collection classes

1. Two Collection frameworks: Collection and Map

2.

3.

4. Implementation classes of map: Hashtable, HashMap, TreeMap

5.Map traversal:

Set keys = map.keySet();
if(keys!=null){
	Iterator iterator = keys.iterator();
	while(iterator.hasNext()){
		Object key = iterator.next();
		Object value = map.get(key);
		...;
	}
}
Set entries = map.entrySet();
if(entries!=null){
	Iterator iterator = entries.iterator();
	while(iterator.hasNext()){
		Map.Entry entry = iterator.next();
		Object key = entry.getKey();
		Object value = entry.getValue();
		...;
	}
}

Chapter 14 I/O input / output

1. Standard input: the object is the keyboard, and the Java corresponding class is system in
Standard output: the object is the screen, and the corresponding Java class is system out
Standard error output: the object is also the screen, and the Java corresponding class is system err

2. Byte stream

(1)InputStream

int read(byte b []): reads multiple bytes into the array, returns the number of bytes read, and returns - 1 after reading
Int read (byte b [], int off, int len): read the data with length len from the input stream, write it to the position starting from index off in array b, and return the number of bytes read. If it is finished, return - 1

(2)OutputStream
write(byte b []): output the data in the byte array to the stream
Write (byte b [], int off, int len): output the data with length len of array b from the position specified by off to the stream
flush(): empty the output stream and force the data in the buffer out

3.ByteArrayInputStream construction method: public ByteArrayInputStream(byte[] buf) -- use byte array as the data source of byte stream

public class ByteArrayStream {
	public static void main(String[] args) {
		byte[] b = "hello".getBytes(); // String->byte[]
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		int n = 0;
		while((n=bais.read())!=-1) {
			System.out.print((char)n); // hello
		}
	}
}

4.ByteArrayOutputStream construction method: public ByteArrayOutputStream() -- construct a byte array output stream, which is used to write the number of bytes into the stream, and finally convert it into a byte array as a whole

public class ByteArrayStream {
	public static void main(String[] args) {
		byte[] b = "hello".getBytes(); // String->byte[]
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos.write(b,0,b.length); // Write the byte array of length in b to the output stream
		System.out.println(new String(baos.toByteArray()));
	}
}

5.FileInputStream construction method: FileInputStream(String name) -- construct a file input stream with the file path name, open a connection with the actual file, and use it to read the file byte stream from the stream
6.FileOutputStream construction method: FileOutputStream(String name) -- construct a file output stream with the file path name, and open a connection with the actual file for file writing and throttling
7.PipedInputStream and pipedinputstream: usually used to connect the output of one program to the input of another program.
The output stream is the sending end of the pipeline and the input stream is the receiving end of the pipeline.
Before use, you need to call the connect method to connect the output stream with the input stream.
Usually, one thread performs the write operation of the pipeline output stream, and another thread performs the read operation of the pipeline input stream.

public class PipedStream{
	public static void main(String[] args) throws IOEception {
		PipedInputStream in = new PipedInputStream();
		PipedOutputStream out = new PipedOutputStream();
		in.connect(out);
		new Thread(new Input(in)).start();
		new Thread(new Output(out)).start();
	}
}
class Input implements Runnable {
	private PipedInputStream in;
	public Input(PipedInputStream in) {
		this.in = in;
	}
	
	public void run() {
		byte[] buf = new byte[1024];
		int len;
		try {
			len = in.read(buf);
			String s = new String(buf, 0, len);
			System.out.println("in "+s);
			in.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}
class Output implements Runnable {
	private PipedOutputStream out;
	public Output(PipedOutputStream out) {
		this.out = out;
	}

	public void run() {
		try {
			out.write("hello".getBytes());
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}

8. Byte stream -- > character stream: InputStreamReader(InputStream in)

InputStreamReader ins = new InputStreamReader(System.in);

9. Character stream -- > byte stream: OutputStreamWriter(OutputStream out) or PrintWriter(OutputStream out)

OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream("test.txt"));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), true);
out.println("Hello"); // Output string "Hello"

10. Use of filter stream BufferedReader: it is used to cache character stream and can be read line by line (as long as it is a Reader, it can be used as a parameter of BufferedReader)

BufferedReader keyin = new BufferedReader(new InputStreamReader(System.in));

String c1;
int i = 0;
int[] e = new int[10];
while(i<10) {
	try {
		c1 = keyin.readline();
		e[i] = Integer.parseInt(c1);
		i++;
	} catch(NumberFormatException ee) {
		System.out.println("Please enter the correct number!");
	}
}

11. Filter streams DataInputStream and DataOutputStream, which can write and read Java basic data types from byte stream, independent of the specific data types of the machine, and facilitate data storage and recovery

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("test.txt")));
dos.writeInt(3); // Write integer
dos.writeDouble(3.14); // Write floating point
dos.writeUTF("hello"); // Write string
dos.close();

DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
System.out.println(dis.readInt()); // Read integer, output 3
System.out.println(dis.readDouble()); // Read floating point, output 3.14
System.out.println(dis.readUTF()); // Read the string and output hello
dis.close();

12. Object Serialization, also known as Serialization, is the expression of dynamic objects in memory into a string form that can be transmitted, while the opposite process is deserialization or deserialization.
13. Object Serialization realizes the conversion of the object of the Serialization interface into a byte sequence, and can completely restore this byte sequence to the original object in the future.
14. The purpose of object serialization is to facilitate network transmission and media storage.
15. The essence of object serialization and deserialization is to solve the problem of how to map objects between memory and physical storage, or how to map objects from the memory of one computer to the memory of another computer.

Chapter 15 Java network communication

1.OSI layer 7 protocol

layerfunction
physical layerBitstream transmission
data link layerPoint to point frame transmission between two adjacent nodes
network layerProvide communication services for different hosts in packet switching network, including routing, address resolution, etc
Transport layerProvide reliable service for process communication between two hosts
Session layerIt provides the establishment, maintenance and termination of sessions between two hosts in the network
Presentation layerProvide standard format for network transmission
application layerDirectly provide services for the user's application process

2.TCP/IP four layer protocol: application layer, transportation layer, network layer and network interface layer
3. Network application positioning:
(1) IP address: identifies the network address of network devices such as computers. It consists of four 8-bit binary numbers.
For example: 192.127.32.123
(2) Domain name: mnemonic of network address.
For example: www.baidu.com com
(3) Service type: the network service provided by the application layer.
For example: http
(4) Port number: the identification number of the network service.
For example: 80
4. Uniform Resource Locator URL: protocol://resourceName
(1) Protocol: indicates the transport protocol used to obtain resources, such as http
(2) Resource Name: indicates the full address of the resource, including domain name, port number, file name or a reference inside the file
For example: http://news.hzau.edu.cn/2015/1114/43886.shtml
5. You can read the specified WWW resources through the URL method openStream()
6. You can connect WWW network resources through URL openConnection()
7.127.0.0.1 is the default local address in TCP/IP protocol
8. There are two types of transmission protocols for network communication: TCP and UDP
9.TCP is a connection oriented protocol to ensure reliable transmission. TCP establishes the connection with three handshakes
10. General process of socket communication:
(1) Create Socket
(2) Open the input / output stream connected to the Socket
(3) Read / write the Socket according to a certain protocol: start the server first, and then the client. The client sends a string to the server, and then it is in the blocking waiting state; After receiving the string sent by the client, the server displays it and is in the state of sending characters to the client. When the string "bye" is input at either end, the program will exit and the communication will be interrupted
(4) Close the Socket (close the stream first)
11. Get the input / output stream connected to the socket

// Get the input stream from the Socket object and construct the corresponding BufferedReader object
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Get the output stream from the Socket object and construct the PrintWriter object
PrintWriter os = new PrintWriter(socket.getOutputStream());

// The BufferedReader object is constructed by the system standard input device
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));

12. Datagram is a complete and independent data entity, which carries the information that can be correctly routed from the source computer to the destination computer through the network. The communication information between different datagrams is independent of each other, and the datagrams sent before and after a datagram have no logical connection
13. Datagram socket: used to establish a communication connection between programs for transmitting datagrams
Datagram packet: used to represent a datagram

Chapter 16 JDBC

1.JDBC (Java DataBase Connectivity) is an API Specification for java object-oriented applications to access databases. Its emergence unifies the access methods of Java applications to various relational databases
Jdbc driver type:
(1) 100% pure JDBC Driver
(2) JDBC call client
(3) JDBC/ODBC Bridge
3. Using JDBC to operate the database usually includes the following steps:
(1) Load JDBC driver
(2) Get the Connection object of the database and establish a Connection between the client and the database
(3) Query or update the data according to the Statement obtained from the connection object
(4) If the query is executed, traverse the returned recordset ResultSet; If the update is performed, the database transaction operation is performed according to the return structure of success or failure
(5) After the operation, close the ResultSet, Statement and Connection in turn
4.JDBC exception handling is uniformly captured and handled by SQLException
5.Java reflection mechanism (obtain self information at runtime)
Suppose Student is a class and stu is a reference to the instance object of Student class

(1)Class c1 = Student.class();
(2)Class c2 = stu.getClass();
(3)Class c3 = Class.forName("hzau.info.Student");
(4)Student stu = c1.newInstance(); // Create instance object at runtime
(5)Method m = c1.getDeclaredMethod("Method name",Variable parameter list(Parameter type.class)); // Get class method at runtime
(6)m.invoke(object, parameter list); // Calling object methods at runtime

Topics: Java