summary
Test site:
- Java development history -- general understanding
- It is divided into J2ME, J2SE and J2EE
- Characteristics of Java language (open, simple, robust, secure, network oriented, full OOP, cross platform)
- Comparison between Java and C + +:
- Analyze the differences and relations among JVM, JRE and JDK
- java programs (. java files) are first compiled into bytecode (. class) by the compiler and interpreted and executed by the interpreter.
- A Java file can contain multiple class definitions, but there can only be one public class. The file name must have the same name as the public class (case must be consistent).
- Java compiler: javac, interpreter: Java
- The role, meaning and configuration of two environment variables (PATH,CLASSPATH) - focus on understanding
- package definition and import
Summary of knowledge points:
1, Java development history -- general understanding
- Oak language
- On May 23, 1995, Oak changed its name to the first version of Java
- In December 2000, they successively withdrew from the three platforms of J2ME, J2SE and J2EE
- The official version of Java 8 was released on March 18, 2014
- Java 13 was officially released in September 2019
2, J2ME,J2SE,J2EE
Current application areas:
- J2ME: mini version of Java
- Embedded system development, mobile phone, PDA and other wireless devices (replaced by IOS and Android)
- J2SE: Standard Edition of Java
- Java language foundation, mainly used for desktop application software programming
- J2EE: Enterprise Edition of Java
- Enterprise class server-side computing (JSP, Java, web programming) is used for B/S structure applications, based on browser and server
3, Characteristics of Java language
The main features: platform independence, completely object-oriented, multithreading
-
Simplicity
- The system is compact, and the demand for hardware environment is not very high
- It is easy to start, similar to C + + syntax
-
Object oriented technology
- Java is a completely object-oriented language, which realizes modularization and information hiding
- Realize code reuse, so that many class libraries can be created
- Realize dynamic binding.
-
Distribution
- It can easily handle TCP/IP protocol and access other objects on the network
-
Robustness
- Java is a strongly typed language, which is strictly checked at compile and run time
-
Security
- Strictly regulate the access to data
- Network applications are not allowed to modify local data
- Pointers cannot be used to protect the security of private members
- Execute with the help of the interpreter to prevent direct access to memory
-
Architecture neutral
- The interpreter generates an architecture independent bytecode structure file format.
-
Portability
- Java class library portable
- The compiler is implemented in Java and the runner is implemented in C
-
Interpretation execution
- The interpreter executes Java bytecode interpretation directly
-
High performance
- Java's interpretation executes very fast, and bytecode is converted into machine code very quickly
- Automatic register allocation and compiler optimization of bytecode make it possible to generate high-quality code
-
Multithreading
- It allows the concurrent execution of multiple instruction streams in the program, which are independent of each other
- Concurrency is logical, not physical
- Because the code of each thread is out of order, it will bring the problem of thread scheduling
-
Platform independence
4, Comparison between Java and C + +
type | JAVA | C++ |
---|---|---|
compile | The Java source code will be compiled once to become the intermediate code, and then the intermediate code will be interpreted into machine code by the interpreter. For Java, the intermediate code is byte code (. class), and the interpreter is built in the JVM | C + + source code is compiled at one time, which is directly linked in the compilation process to form machine code. |
Execution speed | Java can leverage JVM s across platforms. | C + + executes faster than Java |
Object oriented properties | Java is a pure object-oriented language. All code (including functions and variables) must be defined in classes | There are also process oriented things in C + +, such as global variables and global functions. |
Pointer | Not in Java, but there are references. | There are pointers in C + + |
inherit | Classes in Java are single inheritance. At the same time, the interface in Java is multi inheritance, and the implementation of class to interface is also multi implementation. | C + + supports multiple inheritance |
Operator overloading | may not | sure |
Forced automatic transformation | I won't support it | support |
Goto Statement | Java does not support Goto statements in C and C + +. Instead, Goto statements in C and C + + are replaced by exception handling statements try, catch, finally, etc. to handle the jump in case of errors, making the program more readable and structured | support |
memory management | Java manages this automatically and does garbage collection | In C + +, the operators new and delete are used to allocate and free memory |
Data type support | In Java, fixed length bits are always allocated for these data types. For example, for int type, it always occupies 32 bits, which ensures the platform independence of Java. | In C and C + +, for different platforms, the compiler allocates bytes of different lengths for simple data types, such as int and float. Resulting in code non portability |
Header file | Java does not support header files. The types and access permissions of class members are encapsulated in one class. The runtime system controls access to prevent operations on private data members. | C + + uses header files to declare class prototypes, global variables, library functions, etc |
Structure and union | Java does not contain structures and unions, and all content is encapsulated in classes. | All members of the structure and union in C + + are public, which brings security problems |
Pretreatment | Java does not support macros. It declares a constant through the keyword final to implement the constant definition widely used in macro definitions. | C. The code implemented by macro definition in C + + brings difficulties to the readability and security of the program |
5, Analyze the differences and relationships among JVM, JRE and JDK
-
JVM: the English name (Java Virtual Machine) is the familiar Java Virtual Machine. It only knows xxx.class files. It 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.
6, java programs (. java files) are first compiled into bytecode (. class) by the compiler and interpreted and executed by the interpreter.
The interpretation process of Java is to read the Java bytecode file (. java) through the Java virtual machine, then convert it into local instructions (. class) related to the system hardware, and finally execute it on the CPU.
The interpreter executes bytecode files in three steps:
- Loading of code
- Code verification
- Code execution
- Compile the Java source program into a bytecode file (. class) using javac instructions
- Use java instructions to let the computer execute. class files
- be careful:
- The. java file name should be the same as the public class name
- When using javac, you need to bring. java
- You don't need to bring. class when using java
7, The role, meaning and configuration of two environment variables (PATH,CLASSPATH) - focus on understanding
-
PATH
The SDK platform provides java compiler (javac.exe) and Java interpreter (Java.exe), which are located in the bin folder of the Java installation package directory. In order to use the compiler and interpreter in any directory.
-
CLASSPATH
The jre folder of the SDK installation directory contains the Java class libraries required by the Java runtime program. These class libraries are contained in the compressed file rt.jar in the jre/lib directory
8, package definition and import
Java program structure
▪ | package
▪ |---- file
▪ |---------- class
▪ |--------------- Member (member variable, method)
▪ |----------------------- sentence
▪ |--------------------------------- expression
The Java package is similar to the C + + namespace
package a; public class A{ public void out(){ System.out.println("This is A!"); } }
package b; import a.A; public class B{ public static void main(String[] args){ A a = new A(); a.out(); } }
Java syntax
Test site:
- Java data types: (1) simple: 8 types, parameters pass values; (2) Complex: classes, interfaces, enumerations and arrays. The parameter passing adopts the reference model, that is, address passing;
- char in Java is encoded in 2-byte unicode
- Java uses 8 data type classes to encapsulate 8 basic data types
- String class in Java, string, StringBuffer. Typical method of string: equals(), indexOf()
- Type conversion in Java: automatic conversion and cast. int age = 1.5;// Is wrong in Java
- Definition of array in Java, using. The length property of the array. Class array initialization is divided into two steps - how to understand
- Meaning of labeled break and continue statements in Java
- Examples of generating random number groups -- Digest
Knowledge points:
1, Designation of identifiers:
- Cannot be a reserved word of java;
- Cannot start with a number;
- Only '' and '$' are allowed for symbols
- It can be unicode characters such as Chinese characters;
2, Java data types
- Simple data types (8), parameters pass values.
- byte,short,int,long,char,boolean,float,double
- When representing an integer, starting with "0" is octal and starting with "0x" is hexadecimal
- Digit length: (byte, short, char) – int – long – float – double
- During mixed operation, it will be automatically converted from low number of bytes to high number of bytes
- e1+=e2 is equivalent to e1 = (T1)(e1+e2)
- When forcing type conversion, converting a floating-point type to an integer type will throw away the decimal point
- Composite data types: classes, interfaces, enumerations, arrays, and parameters are passed using the reference model, that is, address passing.
3, Reserved word
- true, false and null are all lowercase
- There is no sizeof, const, goto, vitual, etc. there is final
4, String class in Java, string, StringBuffer. Typical method of string: equals(), indexOf()
StringBuffer: thread safe variable character sequence, similar to String buffer.
String is a sequence of characters, which is divided into constants and variables
String s1; // statement s1 = new String(); // initialization String s1 = new String();// Combined use
Common methods:
length() //Find string length charAt(int index) //Returns the index character indexOf(int ch) //Returns the position where the character ch first appears. If not found, - 1 is returned indexOf(String str,int index) //At the beginning of the index, the position where the substring appears for the first time. If it is not found, it returns - 1 subString(int index1,int index2) //Returns the string from index1 to index2 equals(Object object) // Compares the string content with the specified object content equalsIgnoreCase(String s) // Compare string contents, ignoring case
==And equals()
- If there are two basic numeric types
- ==Compare values
- If String, Integer, etc. override equals
- ==The comparison is that both reference the same object, and the comparison is the address
- equals compares the two values
- Other data types
- ==Consistent with equals
5, Array
-
Represents a set of ordered data of the same type
-
Must be defined before use
-
dynamic initialization
int[] a = new int[5]; int a[] = new int[5];
-
Composite type array
String sArray[] = new String[3]; //Step 1: declare the array and specify the array name and the data type of the element sArray[0] = new String("how"); //Step 2: initialize assignment sArray[1] = new String("are"); sArray[2] = new String("you");
-
The length attribute is the only data member variable of the array class. new automatically assigns a value to length when creating an array
- During traversal, I < a.length can be used to facilitate traversal
- An exception will be thrown when crossing the boundary
-
2D array initialization
//Method 1 int a[][]; a = new int[3][4]; //Method 2 int a[][] = new int[3][4]; //Method 3 int a[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}} //Method 4 int b[][] = new int[4][]; b[0] = new int[2]; b[1] = new int[4]; b[2] = new int[6]; b[3] = new int[8];
-
Deep and shallow copies
- Shallow copy, direct copy reference, pointing to the same address
- Deep copy, traversal assignment, pointing to different addresses
6, Labeled break and continue
requirement
- The label statement must immediately follow the head of the loop. Label statements cannot be used before acyclic statements.
- Labeled break: jump out of the loop specified by the label. Any outer loop can be used in multi-layer loop.
- Represents a good continue: terminate the current cycle, skip the following cycle body, and continue the next cycle of the layer corresponding to the label.
public static void main(String[] args) { search: for (int i = 0; i < 3; i++) { for (int j = 0; j < 50; j++) { if (j == 3) break search; System.out.println(i+" "+j); } } } // Output is: // 0 0 // 0 1 // 0 2
public static void main(String[] args) { search: for (int i = 0; i < 3; i++) { for (int j = 0; j < 50; j++) { if (j == 3) continue search; System.out.println(i+" "+j); } } } // Output is: // 0 0 // 0 1 // 0 2 // 1 0 // 1 1 // 1 2 // 2 0 // 2 1 // 2 2
7, Generate random number array
import java.lang.Math; public static void main(String[] args) { Person[] pArray = new Person[5]; //Create a person array with a length of 5 to hold its subclass objects for (int i = 0;i < 5;i++){ int num = (int)(Math.random()*3); //Randomly generate integers of 1-3 to create object types relative to switch (num){ case 1:pArray[i] = new Student();break; case 2:pArray[i] = new Faculty();break; case 3:pArray[i] = new Staff();break; } System.out.println(pArray[i].toString()); } } //Method 1: new Random() java.util.Random public static void main(String[] args) { Random r = new Random(1); for(int i=0 ; i<5 ; i++) { int ran1 = r.nextInt(100); System.out.println(ran1); } } //Method 2: Math.random() java.lang.Math public static void main(String[] args) { int ran2 = (int) (Math.random()*100); System.out.println(ran2); }
OOP
Test site:
- OOP has three characteristics: encapsulation, inheritance and polymorphism
- The syntax of class definition, class member variable and member method definition must be mastered
- How to understand static variables and static methods
- The difference between method overloading and method overriding.
- Polymorphism: runtime polymorphism, compile time polymorphism
- Two premises of runtime polymorphism: (1) backtracking modeling; (2) Method override (override)
- What does the final keyword mean when it modifies variables, methods, and classes?
- Knowledge points of abstract classes and interfaces -- key points
- Inner class
- System class
Knowledge points:
1, Three characteristics of object oriented
-
encapsulation
- Objective: to separate users and designers of objects
- Set the permission to access the member variables and methods of the object in the definition of the class
- Provides a uniform method for reference by other classes
- Other objects cannot directly modify the properties and methods owned by this object
-
inherit
- Objective: to improve the reusability of code and strengthen the relationship between classes. Subclasses follow the characteristics of parent classes and have their own characteristics at the same time
- Inheritance of attributes
- Method inheritance
- Java only supports single inheritance
-
polymorphic
-
heavy load
Same function name, different parameters and Implementation
-
Overwrite (overwrite)
Same function name and parameters, different implementations
-
2, Syntax of class definition, class member variable and member method definition
-
Class definition
[Modifier ] class [Class name] [extends Parent class name][implements Interface name]{ Class body part } Modifier: public,final,abstract,void,static extends: Inherit from a parent class by default Object class implements: Implement some interfaces
-
Class member variable definition
- [modifier] variable type variable name
- Access modifier
- default is only visible in the package
- private is only visible in the same class
- public is visible
- protected only non subclasses in different classes are not visible
-
Member method definition
- [modifier] return value type method name (parameter list) [throws exception list]
- Static: static method, which can be called directly by class
- final: cannot be overridden
- Abstract: abstract method
3, Understand static variables and methods (static)
- Static variable: an object or instance that belongs to a class, not to a class. Static variables are shared by all instances of the class. Usually, static variables are also used with the keyword final as a resource or constant shared by all objects. If a static variable is not private, it can be accessed through ClassName.variableName
- Static method: static method belongs to class, not instance. Static methods can only access static variables of a class or call static methods of a class. Usually, static methods are used by other classes as tool methods without creating an instance of the class
4, Construction method
- Same name as class;
- No return value
- Called by new;
- Can be overloaded;
- Java provides parameterless constructors for classes that do not define constructors
5, The difference between method overloading and method overriding.
- Overload:
- The method name is the same, but the parameters are different
- Overwrite (overwrite):
- Subclasses override methods that already exist in the parent class
- The method name and parameter types are the same, and the return value type is the return value type of the parent class or its subclass.
- The access modifier is more restricted than the parent class
- You cannot throw an exception larger than the parent class
6, Polymorphism
- Compile time polymorphism: overloading
- Runtime polymorphism: determine what form of method to call according to the specific type of object (override)
- The reference of the parent class points to the address of the child class
7, final keyword
- Modifier variables: constants
- Decoration method: cannot be overridden
- Modifier class: cannot be inherited
8, Abstract classes and interfaces
-
abstract class
- Modified with abstract, it can only be used as a parent class
- Cannot instantiate object
- The methods contained in an abstract class are not necessarily abstract methods, but can have function bodies.
- What contains abstract methods must be abstract classes
- Non Abstract subclasses inherit abstract classes and must override all abstract methods of the parent class.
-
Abstract method
- Abstract methods are modified with abstract
- Abstract methods must not have method bodies
-
Interface, similar to (pure virtual class)
[Access control character] interface Interface name{ Abstract method declaration Member variable declaration }
- Interface cannot be instantiated
- All methods are abstract methods
- The variables in the interface are static and final in nature
- Interfaces cannot inherit from other classes. They can inherit from other interfaces. A class can have multiple interfaces
- Interfaces cannot be decorated with private and protected
- Interface reference variables can point to instance objects
- A non Abstract subclass implements an interface and must override all abstract methods in it
9, Inner class
- Member inner classes cannot have static properties and static methods
- Inner classes can be static
- The inner class of a member can have unobstructed access to any member of the outer class
- Advantages: internal classes can inherit interfaces independently without affecting external classes, which makes the solution of multiple inheritance more perfect
10, Object instantiation process
- Memory allocation:
- Initialization sequence
- static first
- Parent class before child class
- Variables before methods
11, System class
Common methods of Object
-
equals
- If it is not String, these classes that have overridden this method will compare whether they are the same reference
-
getClass
- Returns the Class of the Class runtime
-
toString
-
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
-
-
Class class implements the reflection feature of Java
Class c = Class.forName("MyClass"); MyClass mc = (MyClass)c.newInstance();
Conversion of basic data type and String
s = num + ""; s = Integer.toString(num); s = String.valueOf(num); num = Integer.parseInt(s); Integer.valueOf(s).intValue();
Use of dynamic array Vector and ArrayList
-
Similarities and differences
- Both are implemented internally through arrays, and the storage space is continuous
- Vector supports thread synchronization, so it avoids inconsistency caused by multithreading, but reduces the access rate
- Both have initial sizes. If the element exceeds the initial size, the Vector capacity will double and the ArrayList will increase by 50%
-
Vector usage
import java.util.*; public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(); v.add(1); v.add(3); System.out.println("First element: " + (Integer)v.firstElement()); System.out.println("Last element: " + (Integer)v.lastElement()); if(v.contains(3) System.out.println("Vector contains 3."); System.out.println("Current capacity: " + v.capacity()); Enumeration vEnum = v.elements(); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); }
-
ArrayList usage
import java.util.ArrayList; public class RunoobTest { public static void main(String[] args) { ArrayList<String> sites = new ArrayList<String>(); sites.add("Google"); sites.add("Runoob"); sites.set(0,'Run'); //Change the first element to Run sites.remove(1); //Delete the second element System.out.println(sites); } } // [Run]
exception handling
Test site:
- Basic concepts of exception handling in Java
- Understand the corresponding relationship between the running errors in the JVM and the exception classes in Java (the JVM helps us correspond);
- Master the diagram about exceptions in PPT (flow chart of exception generation, transmission and handling)
- Classification of exception classes in Java: runtime exceptions, non runtime exceptions, classification criteria, and purpose of classification?
- Two methods to deal with exceptions: (1) try catch; (2) Declare in function header
- Custom exceptions - learn the difference between throw and throws
Knowledge points:
1, Basic concepts of exception handling
-
Definition of exception
It refers to abnormal phenomena during program operation, such as user input error, divisor is zero, the file to be processed does not exist, array subscript is out of bounds, etc.
-
Advantages:
Separate the program code that completes the normal function from the program code that performs exception handling.
-
There are two ways for Java to handle exceptions:
- Handle directly where exceptions occur
- Throw the exception to the caller and let the caller handle it
-
Classification of exceptions -- exception and error
- Exception the exception generated by the program itself and the environment
- Error handling internal system errors
2, Correspondence between JVM run errors and Java exception classes
- If an exception occurs during program execution, the system will detect and automatically generate a corresponding exception class object, and then give it to the runtime system
- At runtime, the system automatically looks for the corresponding exception handling code to handle this exception. If no code is found to handle the exception, the program terminates
3, Process of exception handling
4, Classification of exception classes
-
Runtime exception
Runtime exceptions are RuntimeException class and its subclasses, such as NullPointerException, IndexOutOfBoundsException, etc. these exceptions are not checked, and the program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions as much as possible from a logical point of view.
-
Non runtime exception
Non runtime exceptions are exceptions other than RuntimeException, which belong to Exception class and its subclasses. Such as IOException, SQLException, and user-defined Exception. For such exceptions, the JAVA compiler forces us to catch and handle these exceptions, otherwise the program cannot be compiled. Therefore, in the face of such exceptions, whether we like it or not, we can only write a lot of catch blocks to deal with possible exceptions.
-
Common functions of exception class (output basic information of exception)
- toString()
- getMessage()
- printStackTrace() / / abnormal transfer track
5, Exception handling method
-
Direct capture
public class CatchDemo{ public static void main(String[] a){ method(1); method(2); } static void method(int i){ try{ if(i == 1){ int b = 3/0 //Throw exception ArithmeticException }else if(i == 2){ int c[] = new int[3]; c[5] = 3; //Throw exception ArrayIndexOutOfBoundsException } }catch(ArithmeticException e){ System.out.println(e); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(e); } } }
-
Function header throw
public class CatchDemo{ public static void main(String[] a){ try{ method(1); method(2); }catch(ArithmeticException e){ System.out.println(e); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(e); } } static void method(int i) throws ArithmeticException,ArrayIndexOutOfBoundsException{ if(i == 1){ int b = 3/0 //Throw exception ArithmeticException }else if(i == 2){ int c[] = new int[3]; c[5] = 3; //Throw exception ArrayIndexOutOfBoundsException } } }
6, Custom exception
- Purpose: find out custom business logic errors
- How
- Define exception class
- Objects that create and throw exception classes
class MyException extends Exception{ MyException(String s){ super(s); } } if(age < 0){ throw new MyException("User age cannot be less than 0"); }
- The difference between throws and throw
- throws is used in the method header to represent the declaration of exception, throw is used in the method body, and the exception object is thrown
- throws can throw multiple exceptions, and throw can only throw one
- Throws throws throws an exception. Its caller must declare that an exception is caught, otherwise an error will be reported. throw can not be declared.
Input / output stream
Test site:
- Input and output streams are divided into four categories. What are the four abstract classes and what are their meanings?
- Can use byte stream and character stream to write file copying program
- Master the usage of File
- Master byte stream to character stream Converters: InputStreamReader, OutputStreamWriter
- Can use BufferedReader and bufferedwriter
Knowledge points:
1, Four categories of input and output streams
- Input byte stream
- InputStream
- Input character stream
- Reader
- Output byte stream
- OutputStream
- Output character stream
- Writer
2, Can use byte stream and character stream to represent the copy program of pinch file
-
File read / write class
- FileInputStream
- FileOutputStream
- FileReader
- FileWriter
-
File class
-
Construction method:
File(String pathOrName); File(String path,String name); File(File dir,String name);
-
Member method:
String getName() getPath() getParent() getAbsolutePath() boolean renameTo(File newName) boolean exists() canWrite() canRead() long length()
-
-
Use FileInputStream and FileOutPutStream to copy files
void copy(String srcFile,String dstFile) throws Exception{ InputSteam input = new FileInputStream(srcFile); OutputStream output = new FileOutputStream(dstFile); byte[] buf = new byte[256]; int length = 0; while((length = input.read(buf)) != -1){ output.write(buf,0,length); } output.flush(); input.close(); output.close(); }
-
FileReader and FileWriter finish copying files
void copy(String srcFile,String dstFile) throws Exception{ FileReader reader = new FileReader(new File(srcFile)); FileWriter writer = new FileWriter(new File(dstFile)); char[] buf = new char[256]; int length = 0; while((length = reader.read(buf)) != -1){ writer.write(buf,0,length); } writer.flush; reader.close(); writer.close(); }
-
Convert byte stream to character stream (this can customize the character set of the file)
void copy(String srcFile,String dstFile) throws Exception{ InputSteam input = new FileInputStream(srcFile); OutputStream output = new FileOutputStream(dstFile); Reader reader = new InputStreamReader(input,"GBK"); Writer writer = new OutputStreamWriter(outpu t,"GBK"); char[] buf = new char[256]; int length = 0; while((length = reader.read(buf) != -1)){ writer.write(buf,0,length); } writer.flush; reader.close(); writer.close(); }
3, Buffer stream
-
FilterInputStream,FilterOutputStream
-
Buffered character stream: BufferedReader/BufferedWriter
-
advantage
- It provides buffering function and higher reading and writing efficiency
- Provide more convenient API functions to read and write characters: String readLine() can directly read a line of the file and return
-
import java.io.*; InputStream is = new FileInputStream("..."); //Get file byte stream Reader r = new InputStreamReader(is,"GBK"); //Encapsulate into character stream BufferedReader br = new BufferedReader(r); //Encapsulated into a character filter stream //Three in one BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("in.txt"))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("out.txt"))); String line = ''; while((line = br.readLine()) != null){ bw.write(line + "\n"); } bw.flush(); br.close(); bw.close();
Multithreading
Test site:
- Thread and Runnable are the most important classes and interfaces in Java multithreaded programming
- Four state diagrams of multithreading;
- Two ways to write multithreaded programs -- be able to write code. Understand the differences, advantages and disadvantages of the two methods
- To understand the synchronization of critical resources in Java, use the synchronized keyword
- Thread. Sleep() of thread. Currentthread() gets the thread currently running
Knowledge points:
1, Thread class, Runnable interface
2, Four state diagrams of threads
-
Create status
Thread t = new Thread() //Thread objects in creation status can only be used to start and terminate threads (start(), stop()).
-
Operational status
Thread t = new Thread(); t.start(); t.yield(); //Give in and give up the current CPU use right, but compete for the new CPU immediately //The start() method generates the system resources required by the thread to run, and submits the thread to the Java thread scheduler for execution.
-
Inoperable state
Thread t = new Thread(); t.sleep(300) //Sleep for 300ms and start automatically after time t.wait(); //Pending, need notify to wake up t.notify() //Wake up thread
-
Death state
Thread t = new Thread(); t.run(); //After the run method ends, normal death occurs t.stop(); //Abnormal death
3, Two ways to create threads
Method 1: inherit Thread class
public class MyThread extends Thread{ @Override public void run(){ //Override run method for(int i = 0;i < 10;i++){ System.out.println(i); } } public static void main(String[] args){ //Create thread instance MyThread myThread = new MyThread(); myThread.start(); //The start method calls the run() method } }
- The program is simple to write, but it can no longer inherit other classes.
Method 2: implement Runnable interface
public class MyThread implements Runnable{ @Override public void run(){ //Override run method for(int i = 0;i < 10;i++){ System.out.println(i); } } public static void main(String[] args){ Thread td = new Thread(new MyThread()); td.start(); } }
- You can separate Thread objects, code, and classes that implement the Runnable interface
- Multiple interfaces can be implemented
4, Synchronized critical resources
- When synchronized is called, the object is locked
- When the synchronized method is executed or an exception occurs, the lock is automatically released
- Data protected by synchronized should be private
class Cbank { private static int s=1000; //bank deposit //Use synchronized to ensure resource synchronization public synchronized static void sub(int m){ int temp = s; temp = temp - m; //Money after withdrawal try{ Thread.sleep((int)(1000*Math.random())); }catch(InterruptedException e){ } s= temp; System.out.println("s = "+s); } } class Customer extends Thread { public void run(){ for(int i=1; i<=5; i++) Cbank.sub(100); //Withdraw 100 yuan } } //main class class Thread { public static void main(String args[]){ Customer c1 = new Customer(); Customer c2 = new Customer(); c1.start(); c2.start(); } }
Network Communications
Test site:
- For the use of URL class, InputStream openStream() will use byte stream and URL class to download online file resources - programming
- Key points: understand the model and principle of Socket communication; Master the usage of ServerSocket and Socket classes; Programming of network communication program based on Socket (combined with experiment 3)
Summary of knowledge points:
1, Use of URL class
URL is one of the most advanced network functions provided by Java. You can directly read and write data on the network through URL
-
Composition of URL: http://61.135.169.125:80/img/baidu_sylogo1.gif
- Resource type: http
- Host domain name: 61.135.169.125 (www.baidu.com)
- Port: 80
- Resource file name: / img/baidu_sylogo1.gif
-
HTTP default port 80, FTP default port 21, HTTPS default port 43
-
Construction method of URL class
Construction method of URL class Function description public URL(String str) Create a URL object using a URL string public URL(String protocol,String host,String file) Create a URL object by specifying the protocol name, host name, file name, and port using the default value public URL(String protocol,String host,String port,String file) Create a URL object by specifying a protocol name, host name, file name, and port number public URL(URL content,String str) Create a URL object by adding details to a known URL path -
Method of URL class
URL class Function description int getPort() Get the port number. If the port is not set, return - 1 String getProtocol() Get the protocol name. If the protocol is not set, return null String getHost() Get the host name. If the host is not set, return null String getFile() Get the file name. If the file is not set, return null Boolean equals(Object obj) Compare with the specified URL object obj. If it is the same, return true; otherwise, return false Final OpenStream() Obtain an input stream. If the acquisition fails, a java.io.Exception will be thrown String toString() Convert this URL object to a string -
Use the URL class to read web page data
-
URL data - > inputstreamreader object - > BufferedReader object
import java.net.*; import java.io.*; public class Network_1{ public static void main(String[] args) throws Exception{ URL hfut = new URL("http://www.baidu.com"); BufferedReader in = new BufferedReader(new InputStreamReader( hfut.openStream() ) ); String inputLine; //Printout HTML while ( (inputLine = in.readLine() ) != null ) System.out.println(inputLine); //Close buffer in.close(); } }
-
URL object - > urlconnection object - > inputstreamreader - > BufferedReader
import java.net.*; import java.io.*; public class Network_2 { public static void main(String[] args) throws Exception { URL hfut = new URL("http://www.baidu.com"); URLConnection uc = hfut.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
-
2, Socket communication model and principle
-
definition:
-
The last endpoint of a two-way communication link between programs running on the network.
-
Socket derived from the combination of IP and port.
-
-
Model and process:
-
Principle:
-
Server side: Server
- ServerSocket: listen to the local port
- Socket: connect to the client
- PrintWriter: transfers data to the client
- BufferedReader: reads the data passed in by the client
-
Client: client
- Socket: connect to the server
- BufferedReader: read in local user command line input
- PrintWriter: transfers data to the server
-
Socket and ServerSocket usage:
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { // Create a server-side instance and set port 80 try { ServerSocket server = new ServerSocket(80); } catch (IOException e) { System.exit(1); } try { //Automatically create a Socket instance through the ServerSocket method accept Socket client = server.accept(); //Send information to the client through the PrintWriter instance PrintWriter out = new PrintWriter(client.getOutputStream(), true); //Receive client information through BufferedReader BufferedReader in = new BufferedReader(new InputStreamReader (client.getInputStream())); } catch (IOException e) { System.exit(1); } while (true) { String line = in.readLine(); String len = line.length(); // Calculate the length of information sent by the client //Tell the client how long the message is out.println("received string's length is: "+ strlen); if(line.equalsIgnoreCase("Bye")) break; } out.close(); in.close(); client.close(); server.close(); } }
//client import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { try { //Instantiate the client, set port 80, and local IP Socket client = new Socket("127.0.0.1", 80); //Send the information to the server through the PrintWriter instance PrintWriter out = new PrintWriter(client.getOutputStream(), true); //Receive the server information through the BufferedReader instance BufferedReader in = new BufferedReader(new InputStreamReader (client.getInputStream())); } catch (Exception e) { System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); while (true){ String line = stdIn.readLine();// Read the information entered on the command line out.println(line);// Send the command line content to the server if(line.equalsIgnoreCase("Bye")) break; } out.close(); in.close(); stdIn.close(); } }
GUI
Test site:
- Master the use of common containers Frame and Panel, and know four kinds of containers:
- Window, Frame - default layout BorderLayout
- Panel, Applet - default layout FlowLayout
- The most common method of container
- add()
- setLayout()
- setSize()
- setVisible()
- Master the use of basic GUI components:
- Label
- Button
- TextField
- TextArea
- Choice
- ...
- AWT event monitoring model, PPT diagram and table should be mastered.
- Take ActionEvent as an example, write the message response code of a button yourself (Experiment 3 contains all).
Summary of knowledge points:
1, Master the use of common containers Frame and Panel, and know four kinds of containers
-
Definition: a container is where components are placed. It can be regarded as a special component, but it can accommodate other components or containers.
-
Four relationships: generally use frame (form) and Panel
-
Layout mode (you can use serLayout to modify the layout mode):
- Flowlayout (default for pannel and Applet)
- From left to right, wrap when full
- Center lines
- BorderLayout(Window, Frame default)
- It is divided into five parts in the East, West, north, South and middle
- East,West,South,North
- CardLayout
- Similar to a carousel chart
- GridLayout
- Divide the form into several grids
- Flowlayout (default for pannel and Applet)
2, The most common method of container
- Add() -- > Add component to container
- Setlayout() -- > sets the layout mode
- Setsize() -- > set size
- Setvisible() -- > sets whether it is visible
- Setbackground -- > sets the background color of the component.
- Setdefaultcloseoperation() -- > sets the default window processing method (unique to swing)
- Settitle() -- > sets the text of the title bar in the window
- Setresizable() -- > sets whether the user can change the frame size
- Setpreferredsize() -- > sets the size of the component
3, Master the use of basic GUI components
-
Label – text
Label titleLabel = new Label("server setting"); titleLabel.setPreferredSize(new Dimension(380,30));
-
Button – button
Button sayButton = new Button("Say");
-
TextField – input field
TextField portText = new TextField(); //Input box startButton.addActionListener((e)->{ server = new Server(Integer.parseInt(portText.getText()),textArea); });
-
TextArea – text box
TextArea textArea = new TextArea(); textArea.setPreferredSize(new Dimension(380,100));
-
Choice – drop down box
//Drop down selection box Choice choice1 = new Choice(); choice1.add("Drop down box 1"); choice1.add("Drop down box 2");
4, AWT event listening model
- Event source: describes the source of time in human-computer interaction, usually the component of Java graphics package
- Event: interactive content generated by the event source, such as "mouse down", class in java.awt.event
- Event listener: receive events and process them. The programmer writes and processes the events generated by the monitored event source
- Listener interface: write the "provisions" - abstract methods of "event listener". These methods must be implemented in the listener class to complete event processing
class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ // The specific work performed by the button event } }
Common event classes:
Event type | Typical trigger action |
---|---|
ActionEvent | Button, list double click, click menu item |
KeyEvent | Keyboard input |
MouseEvent | Events of dragging, moving, clicking, pressing, releasing, or entering or exiting components with the mouse |
ComponentEvent | Events when components are hidden, moved, resized, or become invisible |
FocusEvent | Events when a component gains or loses focus |
InputEvent | Check box and list item clicks, selection of controls, and selection events for optional menu items |
TextEvent | Change of text area or value of text area |
WindowEvent | The event that a window activates, loses an active window, minimizes, minimizes, opens, closes, or exits |
Event handling interface:
Event type | Typical trigger action |
---|---|
ActionListener | Process button, double click list, click menu item |
KeyListener | Handle keyboard input |
MouseListener | Handle the events of mouse dragging, moving, clicking, pressing, releasing, or entering and exiting components |
ComponentListener | Handles events when components are hidden, moved, resized, or become invisible |
FocusListener | Handles events when a component gains or loses focus |
TextListener | Handle changes to the text area or the value of the text area |
WindowListener | Handles window activation, deactivation, minimization, minimization, opening, closing, or exiting events |
- Bind the listener to the component: through the addXXXListener method
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.event.ActionListener; public class Main { public static void main(String[] args) { myButtonFrame frm = new myButtonFrame("ActionEventTest"); frm.show(); //Display Form } } //Design window class class myButtonFrame extends Frame{ JButton btn; //Constructor myButtonFrame(String s){ super(s); this.setSize(200,120); //Create button btn = new JButton("Button"); this.add(btn); btn.addActionListener(new buttonListener()); } //Listener class class buttonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e){ System.out.println("You've pressed the button"); } } }