Note reference source: Crazy God said Java video https://www.bilibili.com/video/BV12J41137hu
This note is a little long. It can be located according to the directory. It is recommended to cooperate with video learning.
Preparatory course
What is a computer
- Name: Computer, full name: electronic Computer, commonly known as Computer.
- Definition: a modern intelligent electronic device that can run according to the program and process massive data automatically and at high speed.
- Composition: composed of hardware and software.
- Form: common displays include desktop computer, notebook computer, mainframe computer, etc.
- Applications: scientific computing, data processing, automatic control, computer aided design, artificial intelligence, network and other fields.
Hardware and von Neumann structure
computer hardware
Composition: CPU, motherboard, memory, power supply, mainframe, hard disk, graphics card, keyboard, mouse and display.
Von Neumann Architecture
Software and software development
Computer software
Windows common shortcuts
Alt+f4 close window Shift+Delete permanently delete ctrl+w auto save
Crash: Task Manager ends the process
Basic Dos commands
How to open CMD
- Start + system + command prompt
- win + R + enter cmd (recommended)
- Under any folder, hold down Shift + right-click to open the command line window
- Add "cmd" before the path in the Explorer address bar
- Administrator operation mode: right click the command prompt to run as an administrator (with the highest permission)
Common Dos commands
# Drive letter switching E: # View all files in the current directory dir # Switch directory cd /d E:\idea # Return to the previous directory cd # Enter the next level directory CD TMP under the same level directory (file name under this directory) # Clear screen cls (clear screen) # Exit terminal exit # View the current IP address of the computer ipconfig # Open calculator calc # Open drawing mspaint # New notepad # Create a new folder MD test (folder name) in the current directory # New file CD > a.txt (file name) # Delete the file del a.txt (file name) # Delete directory Rd test (directory name) # ping command (copy the link to Dos and directly click the right mouse button to paste) ping www.baidu.com
History of computer language
- First generation language: machine language
- Second generation language: assembly language
- Third generation language: high level language
high-level language
C,C++,Java,C#,Python,PHP,JavaScript ...
Generally, it can be divided into two categories: process oriented and object-oriented
- C language is a typical process oriented language, C + + and Java are typical object-oriented languages
Getting started with Java
The birth of the Java Empire
Java features and advantages
- Simplicity
- Face object
- Portability
- High performance
- Distributed
- Polymorphism
- Multithreading
- Security
- Robustness
Three versions of Java
-
Write Once,Run Anywhere
-
JavaSE: Standard Edition (desktop program, console development...)
-
JavaME: embedded development (mobile phones, small appliances...) is cold
-
Java EE: e enterprise level development (Web side, server side development...), based on Java se
JDK JRE JVM
- JDK: Java Development Kit (Java developer tools, including JRE and JVM)
- JRE: Java runtime environment
- JVM: Java Virtual Machine (Java virtual machine, cross platform core)
Install development environment
Uninstall JDk
- Delete Java installation directory
- Delete environment variable JAVA_HOME
- Delete the JAVA directory under path
- Java -version
Install JDK
- Baidu search JDK8 and find the download address
- Agree to the agreement and download the corresponding version of the computer, such as jdk-8u281-windows-x64.exe for 64 bit operating system
- Double click Install JDK
- Remember the installation path
- Configure environment variables
- My computer - properties - system advanced settings - environment variables
- System variable new – > java_ Home enter the corresponding jdk installation path
- path variable – >% Java_ HOME%\bin
- Test success cmd – > java - version
Java Foundation
notes
- Single line note//
- Multiline comment / **/
- Document comments / * **/
Identifiers and keywords
- All components of Java need names. Class names, variable names, and method names are all called identifiers
keyword
Identifier considerations
- All identifiers should be in letters, $(dollar sign)_ (underline) start
- The first letter can be followed by the letter, $_ Number or any combination of characters
- Keywords cannot be used as variable or method names
- Identifier case sensitive
- It can be named in Chinese, but it is not recommended to use it, that is, using pinyin is also Low
data type
-
Strongly typed language
- It is required that the use of variables should strictly comply with the regulations, and all variables must be defined before they can be used
-
Weakly typed languages: JavaScript, Python
-
Java data types fall into two categories
- There are 8 basic types, all of which are reference types
- reference type
//integer int num1 = 10; //Most commonly used, as long as it does not exceed 2.1 billion (2 ^ 31-1) byte num2 = 20; //-128~127 short num3 = 30; long num4 = 30L; //long type numbers should be followed by an l (try to use uppercase, lowercase l is easy to confuse with 1)
//Decimals: floating point numbers float num5 = 50.1F; //The number of float type should be followed by an F double num6 = 3.141592653589793238;
//Decimals: floating point numbers float num5 = 50.1F; //The number of float type should be followed by an F double num6 = 3.141592653589793238;
//Boolean: Yes No boolean flag = true
Type conversion
- Because Java is a strongly typed language, type conversion is required for some operations.
- High capacity – > low:
- In the operation, different types of data are converted to the same type before operation.
- Cast, (type) variable name, capacity from high to low
- Automatic conversion, capacity from low to high
//Cast (type) variable name high -- low //Automatic conversion low high int i = 128; byte b = (byte)i; //Cast memory overflow - 128 ~ 127 double d =i; //Automatic conversion System.out.println(i); //128 System.out.println(b); //-128 System.out.println(d); //128.0 /* Note: 1.Boolean values cannot be converted 2.Cannot convert an object type to an unrelated type 3.Force conversion when converting a high container to a low capacity 4.There may be a memory overflow or a precision problem * */ System.out.println((int)23.7); //23 lost accuracy char c = 'a'; int n = c+1; System.out.println(n); //98 System.out.println((char)n); //b
//When the operands are large, pay attention to the overflow problem //JDK7 new feature, numbers can be separated by underscores int money = 10_0000_0000; //1 billion, the underline will not be printed System.out.println(money); //1000000000 int years = 20; int total = money*years; //Large data, overflow System.out.println(total); //-1474836480 long total2 = money*years; //The default is int, and there is an overflow problem before conversion System.out.println(total2); //-1474836480 long total3 = money*(long)years; //First turn a number to Long System.out.println(total3); //20000000000
Variable, constant, scope
-
What is a variable: it is a variable
-
Java is a strongly typed language, and every variable must declare its type
-
Java variable is the most basic storage unit in a program. The elements include variable name, variable type and scope
//Data type variable name = value; type varName [=value][{,varName[=value]}]; //You can use commas to separate variables of the same type, but it is not recommended to define multiple variables on one line
Variable scope
- Class variable (static)
- Instance variable
- local variable
public class Variable{ static int allClicks = 0; //Class variable String str = "hello world"// Instance variable public void method() {int i = 0; / / local variable}}
constant
-
Constant: a value that cannot be changed after initialization. It is a value that will not change.
-
It can be understood as a special variable. After its value is set, it is not allowed to be changed during program operation.
//Constants generally use uppercase characters. Final constant name = value; final double PI=3.14;
//There is no order of modifiers. static can be written after final. static final double pi = 3.14// Class variable, the global scope under this class
Naming conventions for variables
- All variables, methods and class names: see the meaning of the name
- Class member variable: initial lowercase + hump principle: lastName
- Local variable: initial lowercase + hump principle
- Constants: uppercase letters and underscores: MAX_VALUE
- Class name: initial capital + hump principle: Man, GoodMan
- Method name: initial lowercase + hump principle: run(), fastRun()
operator
int a=10;int b=20;System.out.println(a/b); //0System.out.println((double)a/b); //0.5long c=12300000000;System.out.println(a+b); //intSystem.out.println(a+c); //long automatically converts the data type with large capacity in the formula
Self increasing and self decreasing operator
// ++Self increasing -- self decreasing unary operator int a = 3;int b = a++; //b=a,a=a+1 is assigned first, that is, B = 3, a = 4int, C = + A// A = a + 1, C = a increases automatically first, i.e. a = 5, C = 5system.out.println (a)// 5System.out.println(b); // 3System.out.println(c); // five
//Power operation 2^3 2*2*2=8double pow = Math.pow(2,3)// (base, index) double type system. Out. Println (POW)// eight
//Extension: written test question I = 5 S = (I + + + + + + + I) + (I -- + (- I) s =? int i=5; int s=(i++)+(++i)+(i--)+(--i); System.out.println(s); // twenty-four
Logical operator
- &&Logic and operation: both variables are true and the result is true
- ||Logic and operation: one of the two variables is true and the result is true
- ! Take the opposite, true becomes false, false becomes true
// And (snd) or (or) not (negative) boolean a = true; boolean b = false; System.out.println(a&&b); // false System.out.println(a||b); // true System.out.println(!(a&&b)); // true int c=5; boolean d = (c<5)&&(c++<5); //The first value is false, and no judgment will be made later System.out.println(d); //false System.out.println(c); //5 c + + not executed
Bit operation
/* A = 0011 1100 B = 0000 1101 A&B 0000 1101 Bitwise AND A|B 0011 1101 Bitwise OR A^B 0011 0001 XOR ~B 1111 0010 wrong Interview question: how is 2 * 8 the fastest? 2<<3 <<Shift left * 2, high efficiency!! >>Shift right / 2 */ System.out.println(2<<3); // 16
Ternary operator
int a = 10;int b = 20;a+=b; // a = a+ba-=b; // a = a-bSystem.out.println(a); //10 / / String connector +, convert to String type, and then splice. Note!! System.out.println(""+a+b); //1020System.out.println(a+b+""); //30 first perform the operation, and then convert to String splicing system.out.println (a + B + "STR")// 30str
// x ? Y: Z / / if x is true, the result is y; otherwise, it is Z / / if (x) y; else z; int score = 80; String type = score<60? "Pass": "fail"; System.out.println(type); // pass
Package mechanism
- In order to better organize classes, Java provides a package mechanism due to the namespace of class names
- Syntax format of package:
package pkg1[.pkg2[.pkg3...]];
- Generally, the company domain name is inverted as the package name; com.kuangstudy.www
- In order to be able to use the members of a package, you need to import the package in your Java program
import package1[.package2...].(className|*); //Wildcard * import all classes under the package
- Reference: Alibaba Java development manual
JavaDoc generated document
-
The javadoc command is used to generate its own API documents
-
parameter information
- @Author author name
- @Version version number
- @since indicates the earliest jdk version used
- @param parameter name
- @Return return value
- @throws exception thrown
-
API documentation: https://docs.oracle.com/javase/8/docs/api/
/** * @author Kuangshen * @version 1.0 * @since 1.8 */ public class Demo05 { String name; /** * @author kuangshen * @param name * @return * @throws Exception */ public String test(String name) throws Exception{ return name; } }
- Open the cmd command line under the folder where a class is located
- Input: Javadoc - encoding UTF-8 - charset UTF-8 doc (class name). java
- API documents related to this class will be generated automatically. Some more files are found in the folder
- Open index.html (home page) to view the document comments
Java process control
User interaction Scanner
Scanner object
-
The basic syntax we learned before did not realize the interaction between programs and people. Java provides us with a tool class that can obtain the user's input. java.util.Scanner is a new feature of Java 5. We obtain the user's input through the Scanner class.
-
Basic grammar
Scanner s = new Scanner(System.in);
-
Obtain the user's string through the next() and nextLine() methods of the Scanner class. Before reading, generally use hasNext() and hasNextLine() to judge whether there is still input data.
//Create a scanner object Scanner scanner = new Scanner(System.in); System.out.println("use next Mode reception"); //Judge whether the user has entered a string if(scanner.hasNext()){ //Using hasNextLie() will receive a line of "hello word" //Receive in next mode String str = scanner.next(); System.out.println("The input content is:"+str); //input: hello word //The input content is: hello } //All classes belonging to IO streams will always occupy resources if they are not closed scanner.close();
next():
- Be sure to end the input after reading valid characters
- The next () method will automatically remove the whitespace encountered before entering valid characters
- Only after a valid character is entered can the space entered later be used as a separator or terminator
- next() cannot get a string with spaces
Scanner scanner=new Scanner(System.in); System.out.println("You entered:"); String str=scanner.nextLine(); System.out.println("Output:"+str); scanner.close();
nextLine():
- Take enter as the terminator, that is, the nextLine() method returns all characters before the input carriage return
- Can get blank
Scanner advanced
Determine whether the scanner input is correct
Scanner scanner=new Scanner(System.in); int i=0; System.out.println("please enter an integer:"); if (scanner.hasNextInt()){ i = scanner.nextInt(); System.out.println("You typed it right:" + i); }else{ System.out.println("please enter an integer"); } Scanner sanner=new Scanner(System.in); float a=0.0f; System.out.println("Please enter decimal:"); if (scanner.hasNextFloat()){ a = scanner.nextFloat(); System.out.println("You entered a decimal. That's right:" + a); }else{ System.out.println("Please enter decimal"); } scanner.claose();
Example: we can input multiple numbers and find their sum and average. Press enter to confirm each number. Input non numbers to end the input and output the execution result
Scanner scanner=new Scanner(System.in); float f=0.0f; float sum=0.0f; float avg=0.0f; System.out.println("Please enter multiple numbers:"); while (scanner.hasNextFloat()){ f=scanner.nextFloat(); sum=sum+f; avg++; System.out.println("You entered the number"+avg+"number"); } System.out.println("Altogether"+avg+"A number,"+"Hewei"+sum+",The average is:"+sum/avg); scanner.close();
switch selection structure
Another implementation of the multiple selection structure is the switch case statement
The variable types in the switch statement can be:
- byte, short, int or char
- Start with Java SE7
- switch supports String type
- At the same time, the case tag must be a string constant or literal
char grade='C'; switch (grade){ case 'A': System.out.println("excellent"); break; case 'B': System.out.println("good"); break; case 'C': System.out.println("pass"); break; case 'D': System.out.println("make persistent efforts"); break; default: System.out.println("Unknown level"); }
switch can support strings
String str="world"; switch (str){ case "hello": System.out.println("Hello"); break; case "world": System.out.println("world"); break; default: System.out.println("java"); break; }
Cyclic structure
- while Loop
//Calculate 1 + 2 + 3 +... + 100 int i=0; int sum=0; while(i<100){ i++; sum+=i; } System.out.println(sum); //5050
- do... while loop
//Execute first and then judge, at least once do{ i++; sum+=i; }while(i<100) //Same effect as above
- for loop
//(initialization; condition judgment; iteration) for(int i=0;i<100;i++){ i++; sum+=i; } for(; ; ){...} //Dead cycle
- multiplication table
for (int i=1;i<=9;i++){ for (int j=1;j<=i;j++){ System.out.print(i+"*"+j+"="+(i*j)+"\t"); } System.out.println(); }
- Output 1-1000 numbers that can be divided by 5, and output 3 for each line
//Exercise: output 1-1000 numbers that can be divided by 5, and output 3 for (int i = 1; I < = 1000; I + +) {if (I% 5 = = 0) {system. Out. Print (I + "\ T"); / / output no line break} if (I% (3 * 5) = = 0) {system. Out. Println();}}
- Dead cycle
//(initialization; condition judgment; iteration) for (int i = 0; I < 100; I + +) {I + +; sum + = I;} for (;;) {...} / / loop
- break & continue
-
break can be used in the body of any loop. It can also be used in switch statements because of forced exit from the loop.
-
continue is used in loop statements to terminate a loop process, skip the remaining statements, and judge the conditions of the next loop.
-
Label: identifier followed by a colon label:
- Enhanced for loop
int []num={10,12,45,31,2,12}; for (int i=0;i<6;i++){ System.out.println(num[i]); } System.out.println("==================="); for (int x: num){ System.out.println(x); }
The enhanced for loop can be abbreviated. A simple method: if you want to loop 5 times, you can use "5.for" in idea
- Print triangles
for (int i = 0; i < 6; i++) { for (int j=5;j>i;j--){ System.out.print(" "); } for (int j=1;j<=i;j++){ System.out.print("*"); } for (int j=1;j<i;j++){ System.out.print("*"); } System.out.println(); }
Detailed explanation of Java methods
Java methods are collections of statements that together perform a function.
- Method is an orderly combination of steps to solve a class of problems
- Method is contained in a class or object
- Methods are created in the program and referenced elsewhere
Principle of design method: the original intention of method is code block, which is the statement block to realize a function. When we design a method, we'd better keep the atomic lines of the method, that is, a method only completes one function, which is conducive to our later expansion.
Definition of method
Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. In a class, defining a method includes the following syntax:
-
Method contains a method header and a method body. Here are all parts of a method
-
Modifier: modifier, which is optional, tells the compiler how to call the method and defines the query type of the method
-
Return value type: a method may return a value. returnValueType is the data type of the return value. Some methods perform the required operations but do not return a value. In this case, returnValueType is the keyword void
-
Method name: the actual name, method name and parameters of the method together constitute the method signature
-
The parameter type parameter is like a placeholder. When a method is called, it passes a value to the parameter. This value is called an argument or variable. The parameter list refers to the parameter type, order and number of parameters of the method. The parameters are optional. The method can not contain any parameters
//main method public static void main(String[] args) { //Actual parameters: the parameters passed to him by the actual call int sum=add(5,5); System.out.println(sum); } //addition //Formal parameter, used to define the function public static int add(int a,int b){ return a+b; }
-
Method body: the method body contains specific statements that define the function of the method
Modifier return value type( void Method name (parameter type parameter name) is not returned{ ··· Method body ··· return Return value; }
Java is value passing
-
Method overload
-
Overloads are functions in a class that have the same function name but different formal parameters
-
Rules for overloading methods
- Method names must be the same
- The parameter list must be different (different number, different type, different parameter arrangement order, etc.)
- The return types of methods can be the same or different
- Just different return types are not enough to overload methods
-
Implementation theory:
If the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method. The corresponding method has been selected. If the matching fails, the compiler will report an error
Command line parameters
- Sometimes you want to pass a message to a program when it runs. This is achieved by passing command line arguments to the main () function
public static void main(String[] args) { //args.length array length for (int i = 0; I < args. Length; I + +) {system.out.println ("args [" + I + "]:" + args [i]);}}
Find the folder of the current class and open cmd
Variable parameters
- Starting with Jdk1.5, Java supports passing variable parameters of the same type to a method.
- In the method declaration, add an ellipsis (...) after specifying the parameter type.
- Only one variable parameter can be specified in a method. It must be the last parameter of the method.
public static void main(String[] args) { //Calling methods with variable parameters printmax(34,45,456,4,6545,44,54,4,54); printmax(new double[]{1,2,3}); } public static void printmax(double ...numbers){ if (numbers.length==0){ System.out.println("No argument passed"); return; } double result=numbers[0]; //Find maximum value for (int i=1;i<numbers.length;i++){ if (numbers[i]>result){ result=numbers[i]; } } System.out.println("The max value is "+result); }
Implementation of calculator
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Please enter the first value:"); while (scanner.hasNextDouble()){ double a=scanner.nextDouble(); System.out.println("Please enter an operator"); String str=scanner.next(); System.out.println("Please enter the second value:"); double b=scanner.nextDouble(); switch (str){ case "+": add(a,b); break; case "-": mius(a,b); break; case "*": multiply(a,b); break; case "/": except(a,b); break; default: System.out.println("Wrong operator entered"); break; } } } public static void add(double num1,double num2){ System.out.println(num1+num2); } public static void mius(double num1,double num2){ System.out.println(num1-num2); } public static void multiply(double num1,double num2){ System.out.println(num1*num2); } public static void except(double num1,double num2){ if (num2==0){ System.out.println("Denominator cannot be 0"); }else{ System.out.println(num1/num2); } }
Arrays in Java
Simple implementation of array
-
Array variables must be declared before arrays can be used in programs. The following is the syntax for declaring array variables:
datatype [] arrayRefVar;int [] num1;
-
The Java language uses the new operator to create arrays. The syntax is as follows:
datatype [] arrayRevVar=new dataType[arraySize];
-
The elements of the array are accessed through the index. The array index starts from 0
-
Get array length: array.length
//Type of variable name of variable = value of variable// Array type public static void main (string [] args) {int [] nums; / / 1. Declare an array nums=new int[10];//2. Create an array int [] nums2=new int[10]; / / declaration and creation can be put together / / 3. Assign values to array elements nums [0] = 1; nums [1] = 2; nums [2] = 3; nums [3] = 4; nums [4] = 5; nums [5] = 6; num [6] = 7; num [7] = 8; num [8] = 9; num [9] = 10; / / calculate the sum of all elements, int sum = 0; for (int i = 0; I < num.length; I + +) {sum + = num [i];} system.out.println (sum);}
Initialization of array
//Static initialization: create + assign int [] a={4,1,2,3,5,4,6,4};System.out.println(a[0]); / / dynamic initialization int [] b=new int[10]; b[0]=10; System.out.println(b[0]);
Four basic characteristics of arrays
- Once an array is created, its size cannot be changed
- Its elements must be of the same type, and mixed types are not allowed
- The elements in the array can be any data type, including basic and reference types
- Array variables refer to types, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object. The array itself is an object, and the object in Java is in the heap. Therefore, the array object itself is in the heap regardless of the original type or other object types.
- ArrayIndexOutOfBoundsException: array index out of bounds exception
Array usage
- Normal for loop
int [] arrays={1,2,3,45,5}; int sum=0; for (int i=0;i< arrays.length;i++){ sum+=arrays[i]; System.out.println(arrays[i]); }
- For - Each loop (enhanced for loop)
int [] arrays={1,2,3,45,5}; for (int ayyays:arrays){ System.out.println(ayyays); }
- Array as method input parameter (void as method input parameter, can have no return value)
int [] arrays={1,2,3,45,5};printArray(arrays); //Print array element public static void printarray (int [] arrays) {for (int i = 0; I < arrays. Length; I + +) {system.out.print (arrays [i] + "");}}
-
Array as return value (invert array)
int [] arrays={1,2,3,45,5};int [] reverse= reverse(arrays);for (int i=0;i< reverse.length;i++){ System.out.println(reverse[i]); }//Reverse array public static int [] reverse (int [] arrays) {int [] result = New Int [arrays. Length]; / / reverse operation for (int i = 0, j = result. Length-1; I < arrays. Length; I + +, J --) {result [J] = arrays [i];} return result;}
Two dimensional array
-
Traversal of two-dimensional array
int [] [] array={{3,4},{5,6},{6,7}};// System.out.println(array[1][1]); / / traverse the length of two-dimensional array for (int i = 0; I < array. Length; I + +) {for (int j = 0; J < array [i]. Length; j + +) {system. Out. Println (array [i] [J]);}}
Arrays class
- The tool classes of arrays are Java. Utill and arrays
- Because the data object itself has no method for us to use, but the API provides a tool class Arrays for us to use
- The methods in the Array class are static methods decorated with static. When using them, they can be called directly with the class name, and can be called without objects
- Common functions
- Assign value to array: fill method
- Sorting: sort method, ascending
- Compare arrays: the equals method compares whether the element values in the array are equal
- Find array elements: binarySearch performs binary search on the array of sorting numbers
int [] array={3,5,4,6,3,1,2,0,5,9,8,7}; //Fill the array Arrays.fill(array,2,4,0); / / print the array System.out.println(Arrays.toString(array)); / / sort the array arrays arrays.sort (array); System.out.println(Arrays.toString(array)); / / binary search returns the subscript System.out.println(Arrays.binarySearch(array,0));
Fake sort
- Bubble sort is the most famous sort algorithm of the eight sorts.
- Code: two-layer cycle, the number of bubble wheels in the outer layer and the inner layer are compared in turn.
- When we see nested loops, we should immediately conclude that the time complexity of this algorithm is O(n2).
public static void main(String[] args) { int [] a={4,5,6,5,45,54,5,64,54,7}; int [] sort=sort(a); System.out.println(Arrays.toString(sort)); } public static int [] sort(int []array){ int temp=0; for (int i=0;i< array.length-1;i++){// boolean flag=true; for (int j=0;j< array.length-i-1;j++){ if (array[j+1]<array[j]){ temp= array[j]; array[j]= array[j+1]; array[j+1]=temp;// flag=true; } }// if (flag==false){// break;// } } return array; }
Add "/ /" as the optimization part
Sparse array
//Create a two-dimensional array 11 * 11 0: no wife 1: sunspots 2: white words public static void main(String[] args) { int[][] array = new int[11][11]; array[1][2] = 1; array[2][3] = 2; System.out.println("Output original array"); for (int[] ints : array) { for (int anInt : ints) { System.out.print(anInt + "\t"); } System.out.println(); } //Convert to sparse array save //1. Number of valid values obtained int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if (array[i][j] != 0) { sum++; } } } System.out.println("================="); System.out.println("Number of valid values " + sum); //2. Create an array of sparse arrays int[][] array2 = new int[sum + 1][3]; array2[0][0] = 11; array2[0][1] = 11; array2[0][2] = sum; //3. Traverse the two-dimensional array and store non-zero values in the sparse array int count = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] != 0) { count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array[i][j]; } } } //4. Output sparse array System.out.println("Sparse array"); for (int i = 0; i < array2.length; i++) { System.out.println(array2[i][0] + "\t" + array2[i][1] + "\t" + array2[i][2] + "\t"); } System.out.println("=============="); System.out.println("reduction"); //1. Read sparse array int [][]array3=new int[array2[0][0]][array2[0][1]]; //2. Restore its value to the element in it for (int i=1;i< array2.length;i++){//Note that starting from 1, 0 is the header information array3[array2[i][0]][array2[i][1]]=array2[i][2]; } //3. Printing System.out.println("Output restored array"); for (int [] ints:array3){ for (int anInt:ints){ System.out.print(anInt+"\t"); } System.out.println(); } }
Object oriented programming (OOP)
Initial object oriented
-
Attribute + method = class
-
For describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it.
-
The essence of the dawn of surface phenomenon object ratio is to organize code in the form of classes and organize (encapsulate) data in the form of objects.
-
From the perspective of epistemology, there are classes after the existing objects.
Review the definition and invocation of methods
definition
- main method
//Mainmethodpublic static void main (string [] args) {} / * modifier return value type method name (...) {/ / method body return return value;} * / public string sayhello() {return "Hello world";} public void print() {return;} public int max (int a, int b) {return a > b? A: B;}
- Method call
Students students=new Students();students.say();
-
Pay attention to value passing and parameter passing
public static void main(String[] args) { Person person= new Person(); System.out.println(person.name); Demo05.change(person); System.out.println(person.name); } public static void change(Person person){ person.name="Zhang San"; } }class Person{ String name;//null
- When a basic type is passed as a parameter, it is a copy of the passed value. No matter how you change the copy, the original value will not change
- When an object is passed as a parameter, a copy of the address of the object in memory is given to the parameter
Relationship between classes and objects
- Class is an aggressive data type. It is an overall description / definition of a certain type of transaction, but it cannot represent a specific thing
- Objects are concrete instances of abstract concepts
Create and initialize objects
- When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be used
//Instantiate the object students Xiaoming = new students(); Xiaoming. Name = "Xiao Ming"; xiaoming.age=3; System.out.println(xiaoming.name); System.out.println(xiaoming.age);
//Class public class Students {/ / student class string name; / / null int age; / / 0 / / method public void study() {system. Out. Println (this. Name + "learning");}}
- Even if a class writes nothing, it will have a method
- Constructor:
- Same as class name
- no return value
- Core role:
- Using the new keyword is essentially calling the constructor
- Constructor to initialize values
- In a parameterless constructor, a parameterless constructor can instantiate an initial value
//Parameterless constructor public Person() {} / / in the main method, Person person=new Person();
Note:
- Parameterized constructor: once a parameterized construct is defined, the definition must be displayed if there is no parameter
- Alt+Insert
Memory analysis
//Class: abstract, instantiated / / class instantiation will return an object of its own / / the student object is a concrete instance of the students class. Students Xiaoming = new students(); Xiaoming. Name = "Xiao Ming"; xiaoming.age=3; xiaoming.study(); xiaoming.play(); System.out.println(xiaoming.name); System.out.println(xiaoming.age); Students xiaohong=new Students(); xiaohong.name = "Xiaohong"; xiaohong.age=15; xiaohong.study(); System.out.println(xiaohong.name); System.out.println(xiaohong.age);
//Student class string name// null int age;// 0 / / method public void study() {system.out.println (this. Name + "learning");} public void play() {system.out.println (this. Name + "in the game, King glory");}
- Object operates by reference type: stack -- > heap
Summary classes and objects
- Classes and objects
- A class is a template: an abstract object is a concrete instance
- method
- Definition, general!
- Corresponding reference
- Reference type: basic type (8)
- Objects are operated by reference: stack → heap
- Properties: Field member variables
- Default initialization:
- Number: 0.0
- char u0000
- boolean: false
- Reference: null
- Modifier attribute type attribute name = attribute value!
- Default initialization:
- Object creation and use
- You must use the new keyword to create an object. The constructor Person xiaohong=new Person();
- Object's property xiaohong.name
- Object's method xiaohong.sleep()
- class
- Static properties
- Dynamic behavior method
encapsulation
- The dew that should be exposed, the hide that should be hidden
- Our programming should pursue "high cohesion and low coupling". High cohesion means that the internal data details of a class are completed by itself, and external interference is not allowed; Low coupling: only a small number of methods are exposed for external use.
- Encapsulation (data hiding)
- Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding.
- Property private, get/set
//name private String name; //Student number private int id; //Gender private char sex; //Age private int age; public int getAge() { if (age>120 || age<0){ this.age=3; }else{ this.age=age; } return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; }
Students s1=new Students(); s1.setAge(1200); System.out.println(s1.getAge());
- effect
- Improve program security and protect data
- Implementation details of hidden code
- Unified interface
- System maintainability has increased
inherit
-
The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the world
-
Extensions means "extension". A subclass is an extension of a parent class and is represented by extensions
-
There is only single inheritance in Java, not multiple inheritance! A class can inherit a parent class
-
Inheritance is a relationship between classes, in addition to dependency, composition, aggregation and so on
-
Two classes of inheritance relationship, one is the subclass (derived class) and the other is the subclass of the parent class (base class), which inherits the parent class
-
If a subclass inherits from the parent class, it will have all the methods of the parent class, while private private properties and methods cannot be inherited.
-
In Java, all classes inherit the Object class directly or indirectly by default (Ctrl+H can view the class relationship)
-
A class modified by final cannot be inherited.
super&this
super note:
- super calls the constructor of the parent class, which must be called in the first (default) of the constructor
- super must only appear in subclass methods or constructor methods
- super and this cannot call constructor at the same time
VS this
-
The objects represented are different:
- this: the object itself is the caller
- super: represents the application of the parent object
-
premise
- this: can be used without inheritance
- super: can only be used under inheritance conditions
-
Construction method
- This (): the construction of this class
- super (): Construction of parent class
-
The difference between super and this: Super represents the reference of the parent object and can only be used under inheritance conditions; This calls its own object and can be used without inheritance.
super(); //Hidden code. The parameterless construction of the parent class is called by default. To write, only the first line can be written
Method override
- Override: the method of the subclass must be consistent with that of the parent class, and the method body must be different.
- The parameter list must be the same
- Modifiers can expand but not shrink
- public>protected>default>private
- Exception thrown: the range can be narrowed, but not expanded: ClassNotFoundException – > exception (large)
- Rewriting is the rewriting of methods, independent of properties
- Rewriting methods are only related to non static methods, not static methods (static methods cannot be overridden)
- Methods modified by * * static (class, not instance), final (constant method) and private (private) * * cannot be overridden
public class B { public static void test(){ //Static method System.out.println("B==>test()"); } }
public class A extends B{ //inherit public static void test(){ System.out.println("A==>test()"); } }
public class Application { public static void main(String[] args) { //Method is related to the type defined on the left A a = new A(); a.test(); //Print a = = > Test () //The reference of the parent class points to the child class, but the static method is not overridden B b = new A(); b.test(); //Print B = = > Test () } }
Modify A.Java, B.java
public class B { public void test(){ //Non static method system. Out. Println ("B = = > test()");}} Public class a extends B {@ override / / overrides the method of B public void test() {system. Out. Println ("a = = > test()");}}
//The reference of the parent class points to the child class B b = new A()// The subclass overrides the method of the parent class and executes the subclass method b.test()// Printing becomes a = = > test() / * static methods are methods of classes. Non static methods are methods of objects. When there is static, B calls methods of class B, because B is defined by class B. when there is no static, B calls methods of objects, while B is objects from class a new, calling methods of class A*/
Override: the method of the subclass must be consistent with the parent class: the method body is different
Methods modified by * * static (class, not instance), final (constant method) and private (private) * * cannot be overridden
Why rewrite:
- The functions of the parent class and the child class are not necessarily required or satisfied
polymorphic
- That is, the same method can adopt different behavior modes according to different sending objects
- The actual type of an object is determined, but there can be many references to the object
- Polymorphic conditions
- There is an inheritance relationship
- Subclass overrides parent method
- A parent class reference points to a child class object
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-e0qkj1og-163357313035) (C: \ users \ jameslzhang \ appdata \ roaming \ typora \ user images \ image-20211003093902789. PNG)]
Note:
- Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
- Parent and child classes, associated type conversion exception: ClassCastException
- Existence conditions: inheritance relationship, method needs to be overridden, and parent class reference points to child class object!
instanceof and type conversion
-
instanceof reference type comparison to determine the type of an object
Object object = new Student(); System.out.println(object instanceof Student); System.out.println(object instanceof Person); System.out.println(object instanceof Object); System.out.println(object instanceof Teacher); System.out.println(object instanceof String); System.out.println("======================"); Person person = new Student(); System.out.println(person instanceof Student); System.out.println(person instanceof Person); System.out.println(person instanceof Object); System.out.println(person instanceof Teacher);// System.out.println(person instanceof String); System.out.println("======================="); Student student = new Student(); System.out.println(student instanceof Student); System.out.println(student instanceof Person); System.out.println(student instanceof Object);// System.out.println(student instanceof Teacher);// System.out.println(student instanceof String);
-
Type conversion
- The parent class refers to an object that points to a child class
- If you convert a subclass into a parent class and make an upward transformation, you will lose some of your original methods
- The subclass method is called only after the parent class is converted into a subclass, transformed downward and forced
- Convenient method call (transformation), reduce duplicate code and be concise.
static
- Static variables can be accessed directly by class name, also known as class variables.
- Static variables (or methods) are shared by all objects (instances) of a class.
- Static variables can be called directly, but non static variables cannot be called directly
private static int age; private double score; public void run(){ } public static void go(){ } public static void main(String[] args) { Student s1=new Student(); System.out.println(Student.age);// System.out.println(Student.score); System.out.println(s1.age); System.out.println(s1.score); go();// run(); }
- The static area code is initialized when the class is loaded. It is executed at the earliest and only once (new for the first time).
public class Person { { System.out.println("Anonymous code block"); } static { System.out.println("Static code block"); } public Person(){ System.out.println("Construction method"); } public static void main(String[] args) { Person person=new Person(); System.out.println("=============="); Person person2=new Person(); System.out.println("=============="); Person person3=new Person(); }}
- Math - > Random Number:
//Static import package import static java.lang.math.random; Public class application {public static void main (string [] args) {/ / the first random number does not need to import the package System.out.println(Math.random()); //0.7562202902634543 / / the second random number statically imports the package System.out.println(random()); //0.5391606223844663}}
abstract class
-
Abstract modified classes are abstract classes, and modified methods are abstract methods.
-
Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes.
-
Abstract classes cannot use new to create objects. It is used to let subclasses inherit.
-
Abstract methods have only method declarations and no implementation. Let their subclasses implement them.
-
A subclass inherits an abstract class and must implement all methods of the abstract class, otherwise the subclass must also be declared as an abstract class.
//Abstractct abstract class public abstract class action {/ / constraint, implemented by someone for us / / abstract, abstract method, only method name, no method implementation! public abstract void dosomething();//abstract abstract abstract class can only inherit single (interfaces can inherit multiple) //Constraint ~ someone helps us implement ~ / / the abstract method only has the method name, but there is no method implementation public abstract void dosth() ; / / 1. You can't new abstract classes. You can only implement them by subclasses as a constraint / / 2. Abstract methods can only appear in abstract classes. Abstract classes can have ordinary methods / / 3. Abstract classes have constructors and can generate subclasses / / 4. The meaning of abstract classes: Constraints improve development efficiency. However, classes can only inherit alone, so there are few limitations
Interface
-
Common class: only concrete implementation
-
Abstract classes: concrete implementations and specifications (abstract methods) are available
-
Interface: only specification, no method implementation, professional constraints! Separation of constraints and Implementation: interface oriented programming~
-
An interface is a specification, which defines a set of rules, "what are you... What must be done...".
-
The essence of an interface is a constraint. Just like human laws, it is formulated and observed by everyone.
-
The interface has no constructor and cannot be instantiated
-
The implementation class must override the methods in the interface
-
Implementation classes can implement multiple interfaces
//Keywords defined by interface and interfaces are classes that need to be implemented public interface UserService { //All keywords in the interface are abstract, public abstract void run(String name); void add(String name); void delete(String name); void query(String name); } public interface TimeService { void timer(); }
public class UserServiceImplement implements UserService,TimeService{ @Override public void run(String name) { } @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void query(String name) { } @Override public void timer() { } }
Inner class
- Internal class is to define another class inside a class. For example, if class B is defined in class A, then B is the internal class of a, and a is the external class relative to B
- Member inner class: private properties and methods of external classes can be manipulated
- Static internal class: static decoration. Private properties of external classes cannot be accessed
- Local inner class: the class defined in the method of the outer class
- Anonymous inner class: class initialized without name
public class Outer { private int id=10; public void outer(){ System.out.println("This is the method of an external class"); } public class Inner{ public void in(){ System.out.println("This is the method of the inner class"); } public void getID(){ System.out.println(id); } //Local inner class public void method(){ class Inner2{ public void in(){ } } } } }
public static void main(String[] args) { Outer outer=new Outer(); Outer.Inner inner=outer.new Inner(); inner.getID(); // outer.outer(); }
abnormal
- During the operation of software programs, we may often encounter abnormal problems. Exception means exception. These exceptions require us to write programs to deal with them reasonably without crashing the programs.
- Exceptions refer to unexpected conditions during program operation: file missing, network connection error, illegal parameters, etc.
- The exception occurs during the running of the program, which affects the normal execution process.
Simple classification
- Check type exception: the most representative exception is the exception caused by user error or problem, which is unforeseen by programmers. For example, exceptions thrown when a user wants to open a file that does not exist. These exceptions cannot be simply ignored at compile time.
- Runtime exception: it is an exception that may be avoided by programmers. Contrary to checking exceptions, runtime exceptions can be ignored at compile time.
- Error: the error is not an exception, but a problem out of the control of the programmer. Errors are often ignored in code. For example, when the stack overflows, an exception occurs, and they cannot be checked during compilation.
Exception handling mechanism
- Throw exception
- Catch exception
- Exception handling Keywords: try, catch, finally, throw, throws
- Note that when handling exceptions, follow the rule from small to large. throwable includes error and exception
public static void main(String[] args) { int a=1; int b=0; try{ System.out.println(a/b); }catch (Error e){ System.out.println("Error"); }catch(Exception e){ System.out.println("Exception"); }catch (Throwable t){ System.out.println("Throwable"); }finally { System.out.println("finally"); } } public void a(){b();} public void b(){a();}
- throws is used to declare all the exception information that may be thrown by a method. throws is to declare the exception but not handle it. Instead, it uploads the exception to the user who calls it. throw refers to a specific exception type thrown
//If this method cannot handle this exception, an exception will be thrown on the method public void test(int a,int b) throws ArithmeticException{ if (b==0){ throw new ArithmeticException();//Actively throw exceptions, which are generally used in methods } System.out.println(a/b); }
Custom exception
//Custom exception class public class MyExpectation extends Exception { private int detail; public MyExpectation(int a) { this.detail = a; } //Exception handling information //tostring @Override public String toString() { return "MyExpectation{" + "detail=" + detail + '}'; } }
public class Appcication { //There may be abnormal methods static void test(int a) throws MyExpectation{ System.out.println("The parameters passed are:"+a); if (a>10){ throw new MyExpectation(a);//Throw } System.out.println("ok"); } public static void main(String[] args) { try { test(11); }catch (MyExpectation e){ System.out.println("MyException=>"+e); } } }
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-iimdp4kz-163357313040) (C: \ users \ jameslzhang \ appdata \ roaming \ typora \ user images \ image-20211006162125312. PNG)]
- When customizing some exceptions, you mainly inherit exceptions
Some resources are reproduced in: fllow_wind (before entering Scanner, the following ones are all by hand)
Production is not easy: if this article is helpful to you, you might as well point a praise before you go!