title: Notes on Java learning in primary school
date: 2021-06-28 23:41:10
tags:
- Java learning notes
categories: - programing language
tips: - The notes are only for the writer and are not suitable for learning
CNBLOGS @ Liqiu pig Github @Maverick618
JAVA primary school
HelloWorld
public class HelloWorld{ // The main class must be public and the class name must be the same as the file name public static void main(String args[]){ // public static void String is indispensable // System.lang.String has been import ed by default System.out.println("HelloWorld!"); // If ln, wrap automatically } } // It is customary to add after the class name / function name{ import java.util.* // Call in all classes of util package import java.util.Scanner // Call Scanner in package util
Data types and from C + + to Java
data type
-
boolean and integer cannot be converted to each other
-
boolean cannot perform numerical operations, only logical operations
-
Basic types: integer (byte, short, int, long), floating point, Boolean and char(unicode, 0~65535) are put on the stack
Other types (arrays, too) are put into the heap (implicit new), which is called reference data type
0.0 is double by default, and 0.0F is float
float = 0.0 will report an error
-
Default values for data types
Member variables have default values, but local variables have no default values.
data type Default value byte 0 short 0 int 0 long 0L char '\u0000' float 0.0F double 0.0D boolean false reference type null -
Char can be directly converted to int, but converting int to char requires forced type conversion (char)
-
Declare constants with the keyword final
-
String type: it is a class that can call methods (overloaded addition operator: String splicing), and char is the basic data type
-
Remainder operation: (- 3)% 5
-
Top level parent class: Object
tips: break with label, continue
A: for(;;) for(;;) for(;;) break A; // Directly jump out of the three-tier cycle if(a = 5){...} //An error will be reported because implicit type conversion from int to Boolean is not supported
From C + + to Java
reference type
- No copy constructs
- Classname objectname2 = objectname1 will not generate a new object
- objectname3 = objectname1 is not a data assignment between objects, but a reference address copy. They actually point to the same object
- objectname1 == objectname2 is actually the storage address of the comparison object, that is, whether the references are equal, not whether the object data are equal
- One solution: write the equals function for the class that needs to be compared
- Parameters are always passed by value
- Value copy for base type
- The assignment of address of reference type is essentially the transfer of reference
- That is, there is no '&' in void fun (classname & objectname) in Java
Single inheritance and multiple interfaces
- There is only one inheritance method, which is equivalent to the public inheritance of C + +
- There can only be one parent class
- A class can implement multiple interfaces
Default virtual function
- In Java, methods are virtual by default. You can use the final keyword to declare them as non virtual methods (as opposed to C + +).
Templates, generics, reflection, and multithreading
- java does not support templates, but supports generics, reflection and multithreading
Output notes and specifications
- println automatically wraps lines and print does not
- \t: Tab escape character
- \n: Change to the first character of the next line
- notes:
- Single line://
- Multiline: / **/
- Document comments: / * **/
task
/** * Q1:Write a JAVA program to receive the positive integer input by the user and output the factorial of the number * Requirements: limit the input data to 1-10, prompt invalid data, and end the program * The output result is as follows: 4! = 1 * 2 * 3 * 4 = 24 */ import java.util.Scanner; public class hw2{ public static void main(String args[]){ Scanner input = new Scanner(System.in); int inputNum = input.nextInt(); while(inputNum < 0 || inputNum > 11){ System.out.println("Input Invalid!"); input.nextInt(); } int answer = 1; System.out.print(inputNum + "!="); for(int i = 1; i <= inputNum; i++){ System.out.print(i); answer *= i; if(i < inputNum) System.out.print("*"); } System.out.println("=" + answer); } }
/** * Q2:Write a JAVA program to output all numbers between 1-100 that cannot be divided by 7, and sum them * Requirement: display every 4 data output lines */ public class hw1{ public static void main(String[] args){ int count = 1; int sum = 0; for (int i = 1; i < 101 ; i++){ if(i % 7 != 0){ System.out.print(i + " "); sum += i; if( count++ % 4 == 0) System.out.println(); } } System.out.println("\nSum = " + sum); } }
array
-
Declaration array: int arr[] = new int[length]; or int []arr = new int[length];
-
arr.length is the array length (function)
-
import java.util.Arrays Toolkit
-
Arrays.sort(arr) sorts (ascending) arr
-
Two dimensional array: int [] arr [] = New Int [a] [b]; or int arr[][] = new int[a] [];
-
Illegal: ··· = new int[][a];
-
Static initialization:
int [][]arr = {{1,2,3},{4},{5,6}};
-
Dynamic initialization:
int [][]arr = new int[3][]; arr[0] = new int[4]; arr[1] = new int[3]; arr[2] = new int[2]; //assignment
-
-
Address assignment
int big[][] = new int[7][7]; int small[][] = new int[2][2]; small = big; //Executable
-
Object array:
Employee []E = new Employee[3]; // After declaring an object array in C + +, you can use an object instance (the object constructed by calling the parameterless constructor is an instance) E[0].setname("zhang san"); // √
Employee []E = new Employee[3]; // Object instances cannot be used immediately after an object array is declared in Java E[0].setname("zhang san");// × // You need to the new object again for(int i = 0; i < 3 ; i++) E[i] = new Employee(); // Then you can use it
String
-
Object. Tostring() = "+ object" changes the class to a string
-
'equals' & '=='
String a = "Hello"; String b = "Hello"; //Both are placed in the static area, and the reference address is actually the same String c = new String("Hello"); String d = new String("Hell0");//In the newly applied space in the dynamic area, the two addresses are different // a == b True // b == c false // c == d false
-
Invariance of String
String str = new String("Hello"); str.concat(" World"); // Returns a String with the value "Hello World" str.replace('e','a'); str.toUpper(); System.out.print(str); //The print result is still "Hello"
-
StringBuffer: temporarily understood as a variable length string
class
Basic knowledge
-
Object oriented programming (OOP)
- encapsulation
- inherit
- polymorphic
-
Constructor
- It is generally Public, but it can also be private (singleton class)
- Cannot have return value
-
this reference
- A reference that represents the object itself.
- Resolve local and member variable naming conflicts.
- Call another constructor in a constructor, but can only be called in the first row of the constructor.
- Returns a reference to the current object.
-
Encapsulation: set and get methods can be used to set the access permission of member variables to private, and control statements can be carried out in the set function.
-
Function overload:
- Function names must be the same
- Parameters (type or number) must be different
-
There is no way to set default values for function parameters in Java
-
static:
- static type variable name;
- static member variables belong to a class, not a specific object, that is, memory space is allocated only once. All objects in the class use the data in this memory. When an object modifies its value, it will also affect other objects.
- static member variables do not occupy the memory of objects, but open up memory outside all objects, which can be accessed even without creating objects.
- Static variables can only be declared as member variables or variables in static member functions
- static member function
- The declaration of the function is similar to that of an ordinary member function, just preceded by a static modifier
- The out of class definition of function is the same as that of ordinary member function
- The fundamental difference between static member functions and ordinary member functions is that ordinary member functions have this pointer and can access any member in the class; while static member functions have no this pointer and can only access static members (including static member variables and static member functions).
abstract class
- Abstract: indicates that the class is abstract
- Abstract classes cannot
- Methods in abstract classes must be overridden
Class inheritance
- Extensions: single inheritance, with only one parent class, avoiding diamond structure.
- The subclass inherits all the properties and methods of the parent class, but does not inherit the constructor (so the constructor will not be overridden).
- A parent class can have multiple subclasses.
- super: parent keyword, representing the parent object. super(); call the default constructor of the parent class, and call it by default without writing.
- Calling the parent class constructor through super must be written on the first line of the child class constructor.
- Method override:
- The method access permission overridden by the subclass cannot be less than that of the overridden method of the parent class.
- The return value must be the same or its subclass (if the return value is a class?).
- final: the method cannot be overridden or the class cannot be inherited
polymorphic
-
Two elements
- Use parent type (inheritance)
- Method rewrite
-
instanceof operator: judge the class to which the reference object belongs
pet instanceof Dog determines whether the current pet is a dog. If yes, it returns true, otherwise false
Interface
- Keyword interface, implements
Differences between interfaces and classes
-
The interface cannot be instantiated
-
The implementation class must implement all methods of the interface
-
Implementation classes can implement multiple interfaces
-
Variables in the interface must be public and static (or final)
-
Interfaces can inherit more than one
public interface *** extends ***, ***, ***, ...
-
No constructor
characteristic
- The methods in the interface will be implicitly specified as public abstract
- The variables in the interface will be implicitly specified as public static final variables
- The methods in the interface are public
- Interfaces cannot contain static code blocks and static methods, but abstract classes can.
interface
Define interface
public interface ***{ public static *** ***; Static member variable public *** ***; Member function }
- Possible ambiguous error: duplicate static constant name of interface
- Access to static constants: interface name
implements
Interface implementation
class *** implements ***{ //@override the function in interface *** }
Tag interface
- An interface without any methods is called a tag interface.
- effect
- Create a public parent interface
- Add a data type (instanceof?) to a class
- Function of tag interface: in a simple image, it is to mark (stamp) an object so that the object has some or some privileges.
Collection, generic
- generic paradigm The essence of is parameterized type, that is, the data type operated is specified as a parameter.
- Collection framework
$$
ArrayList \in List, \quad LinkedList \in List
\ HashSet \in Set, \quad TreeSet \in Set
\ List \in Collection,\quad Set \in Collection
\HashMap \in Map, \quad TreeMap \in Map
$$
- When any type is placed in the collection interface, it will implicitly force upward transformation into Object. Generally, the method returns Object, so it may be necessary to force downward transformation.
- Because of the above characteristics, variables of different types are allowed in the collection.
- Tag element type: arrarylist < * * * >
Iterators and enhanced for
- Similar to c + +
Job / instance
/** * Realize an address book management, which can group Friends: family, friends and classmates. You can find the phone number according to the name (the name is repeated), * You can find the name according to the phone number, and you can find the name according to the group (for example, find Wang Wu in the classmate). Please use the generic collection. */ package JAVAHOMEWORK; import java.util.HashMap; //*******Object oriented programming is not used******* public class addressBook { public static void main(String[] args) { // initial HashMap<String,String> teleName = new HashMap<String, String>(); HashMap<String,String> nameGroup = new HashMap<String, String>(); teleName.put("15000000000","Zhang San"); nameGroup.put("Zhang San","classmate"); teleName.put("18700000000","Li Si"); nameGroup.put("Li Si","friend"); teleName.put("18777770000","Li Si"); teleName.put("18234560000","Wang Wu"); nameGroup.put("Wang Wu","classmate"); teleName.put("18712345678","Dog"); nameGroup.put("Dog","family"); teleName.put("19500000000","daddy"); nameGroup.put("daddy","family"); System.out.println("Tongxu you:"); for(String name: nameGroup.keySet()){ if(nameGroup.get(name).equals("classmate")) System.out.println(name); } System.out.println("The phone number is 1500000000" + teleName.get("15000000000")); System.out.println("Li Si's phone number is:"); for(String tele: teleName.keySet()){ if(teleName.get(tele).equals("Li Si")) System.out.println(tele); } } }
abnormal
- Hierarchy of Exception class
-
Cause classification
- The user entered illegal data.
- The file to open does not exist.
- The connection is interrupted during network communication, or the JVM memory overflows.
-
Anomaly classification
- Checking exception: unforeseen exception
- Runtime exceptions: exceptions that are usually avoidable and can be found at compile time.
- Error: the error is not an exception. It is out of the control of the programmer and difficult to find.
-
throw and throws
If a method does not catch a checking exception, it must be declared with the throws keyword, which is placed after the method signature
public void ***(***) throws ******
try{ //*** }catch(abnormal a){ //todo }catch(abnormal b){ //If a ⊆ b, the general exception a is placed before b. if it is placed after b, a will never be caught //todo }catch(Exception e){ //A large number of unknown exceptions will be captured and generally written to the end e.printStackTrace(); }finally{ }
Job / instance
/** * Array out of bounds exception test */ package JAVAHOMEWORK; public class exceptionHW { public static void main(String[] args) { int[] arr = new int[3]; try{ arr[1] = arr[4]; }catch (ArrayIndexOutOfBoundsException e){ System.out.println("Array out of bounds exception, illegal array access exception."); e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); }finally { System.out.println("OVER"); } } }
I/O
Classification of Java streams
-
Classification by flow direction:
- Output stream: OutputStream (bytes) and writer (characters) as base classes
- Input stream: InputStream (bytes) and reader (characters) as base classes
- I / O is for computer memory.
-
Classification by reading unit:
- Byte stream: OutputStream/InputStream
- Character stream: Writer/Reader
IO exception
- To close a nested I/O flow, you only need to close the outermost flow, that is, by calling the close method of the outermost layer, the flow will be closed layer by layer, which also becomes the decorator mode.
task
/** * 1 Read the text in "readme.txt" and output the total number of sentences in English. * And create a new file "readme2.txt" and write the line numbered article into the new text. */ package JAVAHOMEWORK; import java.io.*; import java.util.ArrayList; public class FileOp { public static void main(String[] args) throws IOException { //input file File file = new File("D:\\Program Code\\WorkPlace\\Java\\readme.txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); //output file File readme2 = new File("D:\\Program Code\\WorkPlace\\Java\\readme2.txt"); if(!readme2.exists()) readme2.createNewFile(); //create a file FileWriter fw = new FileWriter(readme2); BufferedWriter bw = new BufferedWriter(fw); String str = null; int count = 1; while((str = br.readLine()) != null){ bw.write(count + ": " + str); bw.newLine(); // Line feed operation count++; } //Be sure to close the file, otherwise the written things may not be saved br.close(); bw.close(); System.out.println("There are(is) " + --count + " line(s) in the readme.txt file."); } }
Multithreading
Tree class
-
java.lang.Tread
-
Implementation method:
- Inherit the tree class
- Override the run() method
- Call the start() function to start the thread after creating the object.
- Implement Runnable interface
- Override the run() method
- Call the start() function to start the thread after creating the object.
- Inherit the tree class
Synchronized synchronization
- Modification method
- Decorated code block
- wait and notify
- wait is equivalent to p operation
- notify is equivalent to a v operation
task
/** * Producer and consumer problem is a classic problem in thread model: producers and consumers share the same storage space in the same time period, * If producers store data in space and consumers access data, the following situations may occur if they are not coordinated: * The storage space is full, and the producer occupies it. Consumers wait for the producer to make room to remove products, and producers wait for consumers to consume products, so as to add products to the space. * Wait for each other, so as to lock life and death. * Please complete the following procedure to solve the producer / consumer problem through thread synchronization. Realize the effect of producing one and consuming one. */ package JAVAHOMEWORK; public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole();//Space for storing data Producer p1 = new Producer(c, 1);//producer Consumer c1 = new Consumer(c, 1);//consumer p1.start(); c1.start(); } } class Producer extends Thread { private CubbyHole cubbyhole; private int number;//Producer number public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("producer #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number;//consumer number public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("consumer #" + this.number+ " got: " + value); } } } //Modify the CubbyHole code so that it can generate one and consume one class CubbyHole { private int contents; private boolean available = false; //If the data is false, it means that it is not executable get() public synchronized int get() { //Synchronization method while(!available){ try { wait(); //Wait when empty }catch (InterruptedException e){ e.printStackTrace(); } } available = false; notify(); //Consumer consumption completion notice return contents; } public synchronized void put(int value) { //Synchronization method while (available){ try { wait(); //Wait when full }catch (InterruptedException e){ e.printStackTrace(); } } contents = value; notify(); //Producer generates completion notification available = true; } }
JDBC
-
API: import java.sql or javax.sql
- DriverManager
- Connection
- Statement
- ResultSet
-
Step: process from top to bottom
-
Field labels start with 1
Reflection
DAO (Data Access Object) mode
Business code and data access code coupling:
- Poor readability
- It is not conducive to later modification and maintenance
- It is not conducive to code reuse
Loose coupling:
- Extract all operations on entity classes into interfaces
- The interface is implemented by different database implementation classes
Supplement
-
Three layer architecture of software system
-
Presentation layer UI
-
Business logic layer BI
-
Data access layer DAO
User request → UI → BI → DAO → BI → UI → data
-