Hello World
- Create a new folder to store the code
- Create a new java file
- The file suffix is java
- Hello.java
- [note] the system may not display the file suffix, so we need to open it manually
- Write code
public class Hello{ public static void main(String[] args){ System.out.print("Hello,World"); } }
- Compiling javac java files will generate a class file
- java class file, run class file
Possible situations:
- Pay attention to the correct case of each word. java is case sensitive
- Try to use English
- The file name and type must be consistent and capitalized
- Do not use Chinese symbols
Chapter I
notes
- Single-Line Comments
- multiline comment
- Text notes (JavaDoc)
public class Hello { public static void main(String[] args) { // Single-Line Comments // Output a Hello,World! /* I'm a multiline comment */ /** * I'm a document comment */ System.out.println("com.xie.base.Hello,World!"); } }
identifier
-
keyword
-
All components of Java need names. Class names, variable names and method names are called identifiers
Identifier considerations
- All identifiers should be in letters (A-Z or A-Z), dollar sign ($), or underscore () start
- The first character can be followed by a letter (A-Z or A-Z), a dollar sign ($), or an underscore () Or any combination of characters of numbers
- Keywords cannot be used as variable or method names
- Identifiers are case sensitive
- Examples of legal identifiers: age, $salary_ value, _ 1_value
- Examples of illegal identifiers: 123abc, - salary, #abc
- It can be named in Chinese, but it is generally not recommended to use it in this way, nor is it recommended to use pinyin
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 language
- Java data types fall into two categories
- primitive type
- reference type
public class Demo2 { public static void main(String[] args) { // Eight basic data types // integer int num1 = 10; // Most commonly used byte num2 = 20; short num3 = 30; long num4 = 40L; // Long type should be followed by an L // Decimal floating point number float num5 = 50.1F; // The float type should be followed by an F double num6 = 3.1415926; // character char name = 'country'; // Boolean Yes No boolean flag = true; } }
expand
public class Demo3 { public static void main(String[] args) { // Integer extension: binary: 0b decimal octal: 0 hex: 0x int i1 = 0b10; // Binary: 0b int i2 = 10; int i3 = 010; // Octal: 0 int i4 = 0x10; // Hex: 0x System.out.println(i1); System.out.println(i2); System.out.println(i3); System.out.println(i4); System.out.println("=============="); // Floating point extension // The business of banks generally does not apply to floating-point numbers, for reasons such as rounding, but uses BigDecimal: mathematical tools float f = 0.1f; double d = 1.0/10; System.out.println(f == d); // The theory shows that it should be true, but it shows false float f1 = 2313132313f; double d1 = f1 + 1 ; System.out.println(f1 == d1); // The theory shows that it should be false and true System.out.println("=============="); // Character expansion all characters are still numbers and encoding related Unicode char c1 = 'A'; char c2 = 'in'; char c3 = '\u0061'; System.out.println(c1); System.out.println((int)c1); // Cast type System.out.println(c2); System.out.println((int)c2); // Cast type System.out.println(c3); } } # result 2 10 8 16 ============== false true ============== A 65 in 20013 a
Type conversion
-
Because Java is a strongly typed language, type conversion is required for some operations
-
Low ---------------------------------------------------- > High
Byte, short, char - > int - > long - > float - > double (decimal must have priority over integer)
-
In the operation, different types of data are first converted to the same type, and then the operation is performed
-
Cast type
-
Automatic type conversion
public class Demo4 { public static void main(String[] args) { // Cast cast: high - > low auto cast: low - > High int i = 128; byte b = (byte)i; // out of memory double b1 = i; System.out.println(i); System.out.println(b); System.out.println(b1); /* Note: 1. Cannot convert boolean type 2. Cannot convert an object type to an unrelated type 3. When converting high capacity to low capacity, you need to cast. Automatic conversion from low capacity to high capacity 4. There may be memory overflow or accuracy problems during conversion */ System.out.println("==========================="); double d1 = 23.7; float f1 = -45.87f; System.out.println((int)d1); System.out.println((int)f1); System.out.println("==========================="); char c = 'a'; int d2 = c+1; System.out.println(d2); System.out.println((char)d2); } } # result 128 -128 128.0 =========================== 23 -45 =========================== 98 b
Pay attention to details
public class Demo5 { public static void main(String[] args) { // When operating large numbers, pay attention to the memory overflow problem // jdk7 new feature, numbers can be separated by underscores int money = 10_0000_0000; int years = 20; int total1 = money*years; // Memory overflowed during calculation long total2 = money*years; // There was a problem before the conversion long total3 = money*(long)years; // In the correct way, first convert one to long System.out.println(total1); System.out.println(total2); System.out.println(total3); } } # result -1474836480 -1474836480 20000000000
variable
- What are variables? Is the amount that can be changed
- Java is a strongly typed language, and every variable must declare its type
- Java variable is the most basic storage unit in a program. Its elements include variable name, variable type and scope
type varName [=value];
//Data type variable name = value;
- matters needing attention:
- Each variable has a type, which can be either a basic type or a reference type
- Variable name must be a legal identifier
- Variable declaration is a complete statement, so each declaration must end with a semicolon
- Variable scope
- Class variable (static variable)
- Instance variable
- local variable
public class Demo6 { // Class variable static is subordinate to class static double salary = 2500; // Instance variable: subordinate to the object. If initialization is not performed, the default value of numeric type is 0.0 // The default value for Boolean types is false // The default value of all types except the basic type is null String name; int age; public static void main(String[] args) { // Local variables: must be declared and initialized int i = 10; System.out.println(i); System.out.println("==================="); Demo6 demo6 = new Demo6(); // Need new first System.out.println(demo6.age); System.out.println(demo6.name); System.out.println("==================="); System.out.println(salary); // new is not required } } # result 10 =================== 0 null =================== 2500.0
Naming conventions for variables
- All variables, methods and class names: see the meaning of the name
- Class member variables: initial lowercase and hump naming rules: monthSalary
- Local variables: initial lowercase and hump principle
- Constants: uppercase letters and underscores: MAX_VALUE
- Class name: initial capitalization and hump principle: Man,GoodMan
- Method name: initial lowercase and hump principle: run(),runRun()
constant
- Constant: the value cannot be changed after initialization! That is, the value that will not change.
- The so-called constant can be understood as a special variable
- final type constant name = value;
- final double PI = 3.14;
- Constant names generally use uppercase characters
public class Demo7 { // Modifier, no order static final double PI = 3.14; // The following can also be used final static double PI1 = 3.14; public static void main(String[] args) { System.out.println(PI); System.out.println(PI1); } } # result 3.14 3.14
operator
The Java language supports the following operators:
- Arithmetic operators: +, -, *, /,%, + +, –
- Assignment operator:=
- Relational operators: >, <, > =, < =, = =,! =, instanceof
- Logical operators: & &, |, |,!
- Bitwise operators: &, |, ^, ~, > >, <, > > (understand)
- Conditional operator:?:
- Extended assignment operators: + =, - =, * =/_=
public class Demo1 { public static void main(String[] args) { // Binary operator int a = 10; int b = 20; System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(a/(double)b); } } # result 30 -10 200 0.5
public class Demo2 { public static void main(String[] args) { long a = 15874594213566L; int b = 123; short c = 10; byte d = 8; System.out.println(a+b+c+d); // If there is a long type, the output result is a long type System.out.println(b+c+d); // int type System.out.println(c+d); // int type } } result 15874594213707 141 18
public class Demo3 { public static void main(String[] args) { int a = 10; int b = 20; int c = 21; System.out.println(a>b); System.out.println(a<b); System.out.println(a==b); System.out.println(a!=b); // Modulo operation System.out.println(c%a); } } result false true false true 1
public class Demo4 { public static void main(String[] args) { // ++Self increasing -- self decreasing unary operator int a = 3; System.out.println("a="+a); int b = a++; // First execute b=a, and then a increases automatically System.out.println("a="+a); int c = ++a; // Self increment first, and then execute c=a System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); // Extended power operation 2 ^ 3 = 8 many operations. We will use tool classes for operations double pow = Math.pow(2, 3); System.out.println(pow); } } result a=3 a=4 a=5 b=3 c=5 8.0
public class Demo5 { public static void main(String[] args) { // Logical operation // And (and) or (or) not (negative) boolean a = true; boolean b = false; System.out.println(b&&a); System.out.println(b||a); System.out.println(!(b&&a)); System.out.println("=================="); // Short circuit operation int c = 5; boolean d = (c<4)&&(c++<4); System.out.println(d); System.out.println(c); // Because the judgment of c < 4 is wrong, c + + is not executed, so c is still equal to 5 boolean e = (c++>4)&&(c>4); System.out.println(e); System.out.println(c); // c + + is executed here, and c becomes 6 } } result false true true ================== false 5 true 6
public class Demo6 { public static void main(String[] args) { // Bit operation /* A = 0011 1100 B = 0000 1101 ------------------------ A&B = 0000 1100 //When both bits are 1, it is 1, and the rest are 0 A|B = 0011 1101 //It is 0 only when both bits are 0, and the rest are 1 A^B = 0011 0001 // If two bits are the same, it is 0, and if they are different, it is 1 ~B = 1111 0010 // And correspond to exactly the opposite Calculation 2 * 8 = 16 = > 2 * 2 * 2 * 2 << Equivalent to * 2 << Equivalent to / 2 0000 0000 0 0000 0001 1=2^0 0000 0010 2=2^1 0000 0100 4=2^2 0000 1000 8=2^3 0001 0000 16=2^4 */ System.out.println(2<<3); } } result 16
public class Demo7 { public static void main(String[] args) { int a = 10; int b = 20; a+=b; System.out.println(a); System.out.println("============="); // String connector System.out.println(""+a+b); System.out.println(a+b+""); } } result 30 ============= 3020 50
public class Demo8 { public static void main(String[] args) { // x ? y : z // If x==true, the result is y; otherwise, the result is z int score1 = 50; int score2 = 80; String type1 = score1 < 60 ? "fail," : "pass"; String type2 = score2 < 60 ? "fail," : "pass"; System.out.println(type1); System.out.println(type2); } } result fail, pass
Package mechanism
-
In order to better organize classes, Java provides a package mechanism to distinguish the namespace of class names
-
The syntax format of the package statement is:
package pkg1[. pkg2[. pkg3]];
-
Generally, the company domain name is inverted as the package name
-
In order to use the members of a package, we need to explicitly import the package in the ava program and use "imoort"
import package1[. package2...].(classname|*);
JavaDoc
- The javadoc command generates its own API document
- parameter information
- @Author author name
- @Version version number
- @since you need the earliest jdk version
- @param parameter name
- @Return return value
- @throws exception thrown
package operater; /** * @author xie_xuchun * @create 2021-12-26 21:42 */ public class Demo9 { String name; /** * @author xie_xuchun * @param name * @return * @throws Exception */ public String abc(String name) throws Exception{ return name; } }
Chapter II
Scanner object
-
The basic syntax we learned before did not realize the interaction between programs and people, but Java provides us with a tool class that we can get user input. java.util.Scanner is a new feature of Java 5. We can get user input through the scanner class.
-
Basic syntax:
Scanner s = new Scanner(System.in);
-
Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to judge whether there is still input data.
public class Demo1 { public static void main(String[] args) { Scanner scanner1 = new Scanner(System.in); Scanner scanner2 = new Scanner(System.in); System.out.println("use next Reception mode:"); if(scanner1.hasNext()){ // if judgment is available but not required String str = scanner1.next(); System.out.println("The output content is:"+ str); } System.out.println("use nextLine Reception mode:"); if(scanner2.hasNextLine()){ String str1 = scanner2.nextLine(); System.out.println("The output content is:"+ str1); } scanner1.close(); // The IO flow method should be closed, otherwise it will occupy memory. Note that it should be closed at the end scanner2.close(); } } result use next Reception mode: hello world The output content is: hello use nextLine Reception mode: hello world The output content is: hello world
public class Demo2 { public static void main(String[] args) { // Enter multiple numbers, calculate and calculate the average value. It will exit automatically when it is not a number Scanner scanner = new Scanner(System.in); double sum = 0; int m = 0; System.out.println("Please enter data:"); while(scanner.hasNextDouble()){ double x = scanner.nextDouble(); m++ ; sum = sum + x; System.out.println("You entered the number"+m+"Data, current result sum="+sum); } System.out.println(m+"The sum of the numbers is:"+sum); System.out.println(m+"The average number is:"+(sum/m)); scanner.close(); } } result Please enter data: 10 You entered the first data, the current result sum=10.0 20 You entered the second data, the current result sum=30.0 30 You entered the third data, the current result sum=60.0 dfgh 3 The sum of the numbers is 60.0 3 The average number is 20.0
Sequential structure
-
The basic structure of JAVA is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order.
-
The structure of the algorithm is the simplest
-
Statements and boxes are executed from top to bottom. It is composed of several steps that are executed in turn. It is the basic algorithm structure that any algorithm is inseparable from.
Select structure
- if single selection structure
- if double selection structure
- if multiple selection structure
- Nested if structure
- switch multiple selection structure
if single selection structure
-
We often need to judge whether a thing is feasible before executing it. Such a process is represented by an if statement
-
Syntax:
If (Boolean expression){
/ / if true, the statement to be executed
}
public class Demo1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter:"); String str = scanner.nextLine(); if(str.equals("hello")){ System.out.println("You entered:"+str); } System.out.println("End"); scanner.close(); } } result Please enter: hello You entered: hello End
if double selection structure
-
grammar
If (Boolean expression){
/ / execute the code when it is true
}else{
/ / code when the execution is false
}
public class Demo2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter the test result:"); Double score = scanner.nextDouble(); if(score>=60){ System.out.println("Pass the exam!"); }else{ System.out.println("Fail in the exam!"); } scanner.close(); } } result Please enter the test result: 90 Pass the exam!
if multiple selection structure
-
Syntax:
If (Boolean expression 1){
/ / execute if Boolean expression 1 is true
}Else if (Boolean expression 2){
/ / execute if Boolean expression 2 is true
}Else if (Boolean expression 3){
/ / execute if Boolean expression 3 is true
}else{
/ / execute when none of the above Boolean expressions are valid
}
public class Demo3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter the test result:"); Double score = scanner.nextDouble(); if(score==100){ System.out.println("Full mark!"); }else if(score >= 90 && score <100){ System.out.println("A level"); }else if(score >= 80 && score <90){ System.out.println("B level"); }else if(score >= 70 && score <80){ System.out.println("C level"); }else if(score >= 60 && score <70){ System.out.println("D level"); }else if(score >= 0 && score < 60){ System.out.println("fail,"); }else{ System.out.println("wrongful"); } scanner.close(); } } result Please enter the test result: 85 B level
Nested if structure
-
grammar
If (Boolean expression 1){
/ / execute when Boolean expression 1 is true
If (Boolean expression 2){
/ / execute when Boolean expression 2 is true
}
}
switch multiple selection structure
-
The switch case statement is another implementation of the multi selection structure.
-
The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch
-
grammar
-
The variable types in the switch statement can be:
- byte, short, int or char
- Starting with java SE7, switch supports String type
- At the same time, the case tag must be a string constant or literal
public class Demo4 { public static void main(String[] args) { String name = "Jiangnan"; switch (name){ case "ha-ha": System.out.println("ha-ha"); break; case "Jiangnan": System.out.println("Jiangnan"); break; default: System.out.println("Nothing"); break; } } } result Jiangnan
Cyclic structure
- while Loop
- do... while loop
- for loop
- The enhanced for loop, which is mainly used for arrays, has been introduced in Java 5
while Loop
-
while is the most basic loop. Its structure is:
While (Boolean expression){
/ / loop structure
}
-
As long as the Boolean expression is true, the loop will continue to execute
-
In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop
-
In a few cases, the loop needs to be executed all the time, which is not as good as the server's request response listening, etc
-
If the loop condition is not true all the time, it will cause dead loop. We should try our best to avoid dead loop in normal business programming, which will affect the program performance or cause jamming and collapse
public class Demo5 { public static void main(String[] args) { int sum = 0; int i = 0; while(i<=100){ sum = sum + i; i++; } System.out.println("0-100 The sum of is:"+sum); } } result 0-100 Sum of: 5050
do... while loop
-
For while, if the conditions are not met, the loop cannot be entered. But sometimes we need to perform at least once even if the conditions are not met
-
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once
do{
/ / code statement
}While (Boolean expression);
-
The difference between while and do... While
- while is to judge before execution, do... while is to judge after execution
- do... while always ensures that the loop body is executed at least once. This is their main difference
public class Demo6 { public static void main(String[] args) { int i = 0; while (i<0){ System.out.println(i); } System.out.println("==============="); do{ System.out.println(i); }while(i<0); } } result =============== 0
for loop
-
for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure
-
The number of times the for loop is executed is determined before execution. The syntax format is as follows
For (initialization: Boolean expression; update){
/ / code structure
}
public class Demo7 { public static void main(String[] args) { // Calculate the sum of odd and even numbers between 0-100 int oddSum = 0; int evenSum = 0; for (int i = 0; i <= 100; i++) { if(i%2!=0){ // Modulo is not equal to 0-bit odd number oddSum+=i; }else{ evenSum+=i; } } System.out.println("Odd sum:"+oddSum); System.out.println("Even sum:"+evenSum); } } result Odd sum: 2500 Even sum: 2550
public class Demo8 { public static void main(String[] args) { // Output the number that can be divided by 5 between 1-50, and change a line every 3 for (int i = 1; i <= 50; i++) { if(i%5==0){ System.out.print(i+"\t"); } if(i%(5*3)==0){ System.out.print("\n"); } } } } result 5 10 15 20 25 30 35 40 45 50
public class Demo9 { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(j+"*"+i+"="+i*j+"\t"); } System.out.println(); } } } result 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
public class Demo10 { public static void main(String[] args) { int[] numbers = {10,20,30,40,50}; for (int i = 0; i < 5; i++) { System.out.print(numbers[i]+"\t"); } System.out.println(); System.out.println("================"); for (int x:numbers){ System.out.print(x+"\t"); } } } result 10 20 30 40 50 ================ 10 20 30 40 50
break && continue
- Break in the main part of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop
- The continue statement is used in a loop statement to terminate a loop process, that is, to skip the unexecuted statements in the loop body, and then determine whether to execute the loop next time
practice
public class Demo11 { public static void main(String[] args) { // Print a triangle for (int i = 1; i <= 5; 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(); } } } result * *** ***** ******* *********
Chapter III
method
What is method?
- Java methods are collections of statements that together perform a function
- Method is an ordered 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
- Design principle of the method: the original intention of the method is the function block, which is the collection of statement blocks to realize a certain function. When we design the method, we'd better keep the atomicity of the method, that is, a method only completes one function, which is conducive to our later expansion.
public class Demo1 { public static void main(String[] args) { int add = add(1, 2); System.out.println(add); } public static int add(int a,int b){ return a+b; } } result 3
Definition of method
-
Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax:
-
The method contains a method header and a method body. The following are all parts of a method:
-
Modifier: optional, tells the compiler how to call the method. Defines the access type of the method
-
Return value type: the method may return a value. returnValueType is the data type returned by the method. Some methods perform the required operations, but do not return a value. The keyword is void.
-
Method name: the parameter is a placeholder. When a method is called, a value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.
- Formal parameter: used to receive external input data when the method is called.
- Argument: the data actually passed to the method when the method is called.
-
Method body: the method body contains specific statements that define the function of the method.
Modifier return value type method name(Parameter type formal parameter){ Method body Return value }
-
-
Method call
-
Calling method: object name Method name (argument list)
-
Java supports two methods of calling methods, which are selected according to whether the method returns a value
-
When a method returns a value, the method call is usually regarded as a value, for example:
- int large = max(30,40);
-
If the return value of the method is void, the method call must be a statement.
- System.out.println("Hello,World");
-
Java is value passing
public class Demo2 { public static void main(String[] args) { int large = large(20, 20); System.out.println(large); } public static int large(int num1,int num2){ int result = 0; if(num1==num2){ return result; } if(num1 > num2){ result = num1; }else{ result = num2; } return result; } } result 0
Method overload
- Overloading is a function with the same function name but different formal parameters in a class.
- Rule of method overloading: simply put, it is different parameters with the same name
- 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.
- Realization theory
- If the method names are the same, the compiler will match them one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.
public class Demo2 { public static void main(String[] args) { double large = large(30.0, 20); System.out.println(large); } public static int large(int num1,int num2){ int result = 0; if(num1==num2){ return result; } if(num1 > num2){ result = num1; }else{ result = num2; } return result; } public static double large(double num1,double num2){ double result = 0; if(num1==num2){ return result; } if(num1 > num2){ result = num1; }else{ result = num2; } return result; } } result 30.0
Command line parameters
- Sometimes you want to pass parameters to a program when you run it, which depends on passing parameters to the main() function from the command line.
public class Demo3 { public static void main(String[] args) { for (int i = 0; i <args.length ; i++) { System.out.println("args The first"+i+"The first parameter is:"+args[i]); } } }
Variable parameters
- JDK1. Starting from 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. Any ordinary parameter must be declared before it.
public class Demo4 { public static void main(String[] args) { printMax(34,35,33,31.0,38); printMax(new double[]{11,25.6,33.0,45}); } public static void printMax(double... numbers){ if (numbers.length == 0){ System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 0; i < numbers.length; i++) { if (numbers[i] > result){ result = numbers[i]; } } System.out.println("The maximum number in the array is:"+result); } } result The maximum number in the array is:38.0 The maximum number in the array is:45.0
recursion
- Method A calls method B, which is easy for us to understand
- Recursion is: when A method calls A method, it calls itself
- Using recursion, we can solve some complex problems with simple programs. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small amount of program, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with limited statements.
- The recursive structure consists of two parts:
- Recursive header: when not to call its own method. If there is no header, it will fall into an endless loop
- Recursive body: when do I need to call my own method
public class Demo5 { public static void main(String[] args) { // Recursive calculation 5! int f = f(5); System.out.println(f); } public static int f(int n){ if (n == 1){ return 1; } return n*f(n-1); } } result 120
array
- An array is an ordered collection of data of the same type
- Array describes several data of the same type, which are arranged and combined in a certain order
- Among them, each data is called an array element, and each array element can access them through a subscript
Array declaration creation
-
Array variables must be declared before they can be used in programs. The following is the syntax for declaring array variables:
-
dataType[] arrayRefvar; // Preferred method
or
dataType arrayRefvar[]; // The same effect, but not the preferred method
-
-
The Java language uses the new operator to create arrays. The syntax is as follows:
- dataType[] arrayRefvar = new dataType[arraySize];
-
The elements of the array are accessed through the index. The array index starts from 0
-
Get array length: arrays length
public class Demo1 { public static void main(String[] args) { int[] nums = new int[10]; // Declare and create an array for (int i = 0; i < nums.length; i++) { // Assign a value to an array nums[i]=i+1; System.out.print(nums[i]+"\t"); } int sum = 0; for (int i = 0; i < nums.length; i++) { // Summation of array elements sum = sum + nums[i]; } System.out.println(); System.out.println(sum); } } result 1 2 3 4 5 6 7 8 9 10 55
Four basic characteristics of arrays
- Its length is fixed. Once the 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 type and reference type
- Array variables are of reference type. An array can also be regarded as an object. Each element in the array is equivalent to the member variable of the object
- The array itself is an object. In Java, the object is in the heap. Therefore, whether the array saves the original type or other object types, the array object itself is in the heap
Three kinds of initialization
- initiate static
- dynamic initialization
- Default initialization of arrays
- Array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element in it is implicitly initialized in the same way as the instance variables
public class Demo2 { public static void main(String[] args) { // initiate static int[] a = {1,2,3}; Man[] mans = {new Man(),new Man()}; System.out.println(a[1]); // dynamic initialization int[] b = new int[5]; b[0] = 1; b[1] = 2; System.out.println(b[1]); // The default initialization of the array. The default value is 0.0 null String[] c = new String[8]; System.out.println(c[5]); } } result 2 2 null
Array boundary
- Legal range of subscript: [0, length-1]. If it exceeds the range, an error will be reported
- ArrayIndexOutOfBoundsException: array index out of bounds exception
- Summary
- An array is an ordered collection of the same data type (the data type can be any type)
- Arrays are also objects. An array element is equivalent to a member variable of an object
- The array length is fixed and immutable. If the boundary is crossed, an error will be reported.
Use of arrays
-
Normal for loop
-
For each loop
-
Array as method input parameter
-
Array as return value
public class Demo3 { public static void main(String[] args) { int[] nums = {-1,1,2,3,4,-5}; // Print out all elements of the array for (int i = 0; i < nums.length; i++) { System.out.print(nums[i]+"\t"); } System.out.println(); System.out.println("==========================="); // Gets the maximum value in the array int max = nums[0]; for (int i = 0; i < nums.length; i++) { if (nums[i] > max){ max = nums[i]; } } System.out.println(max); } } result -1 1 2 3 4 -5 =========================== 4
public class Demo4 { public static void main(String[] args) { int[] nums = {-1,1,2,3,4,-5}; // Print out all elements of the array for (int array: nums) { System.out.print(array+"\t"); } } } result -1 1 2 3 4 -5
public class Demo5 { public static void main(String[] args) { int[] nums = {-1,1,2,3,4,-5}; int[] reverse = reverse(nums); show(reverse); } public static int[] reverse(int[] arrays){ int[] result = new int[arrays.length]; for (int i = 0,j=arrays.length-1; i < arrays.length; i++,j--) { result[j] = arrays[i]; } return result; } public static void show(int[] reverse){ for (int array: reverse) { System.out.print(array+"\t"); } } } result -5 4 3 2 1 -1
Multidimensional array
- Multidimensional arrays can be regarded as arrays. For example, a two-dimensional array is a special pile of arrays, and each element is a pile of arrays
- Two dimensional array
public class Demo6 { public static void main(String[] args) { int[][] array = {{1,2},{3,4},{5,6},{7,8}}; System.out.println(array.length); System.out.println(array[3][1]); System.out.println(array[1].length); System.out.println("========================"); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]+"\t"); } } } } result 4 8 2 ======================== 1 2 3 4 5 6 7 8
Arrays class
- Array tool class java util. Arrays
- There are no methods for us to call array objects, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on data objects.
- View JDK help documentation
- The methods in the Arrays class are static methods decorated with static. When using them, you can call them directly with the class name instead of using the object (note that it is "no", not "no")
- It has the following common functions
- Assign a value to the array: through the fill method
- Sort the array: sort in ascending order through the sort method
- Compare arrays: use the equals method to compare whether the element values in the array are equal
- Find array elements: binary search can be performed on the sorted array through the binarySearch method
public class Demo7 { public static void main(String[] args) { int[] a = {12,15,486,14,579,5416,265}; int[] b = {12,15,486,14,579,5416,265}; System.out.println(Arrays.toString(a)); Arrays.sort(a); System.out.println(Arrays.toString(a)); Arrays.fill(a,0,3,5); System.out.println(Arrays.toString(a)); System.out.println(Arrays.equals(a,b)); System.out.println(Arrays.binarySearch(a,0,a.length,5416)); } } result [12, 15, 486, 14, 579, 5416, 265] [12, 14, 15, 265, 486, 579, 5416] [5, 5, 5, 265, 486, 579, 5416] false 6
Bubble sorting
- Bubble sorting is undoubtedly one of the most famous sorting algorithms. There are eight sorting algorithms in total!
- The bubble code is quite simple. The 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 0.
public class Demo8 { public static void main(String[] args) { double[] a = {1,58,45.6,32,15.5,54,89.0,32,54}; double[] sort = sort(a); System.out.println(Arrays.toString(sort)); } public static double[] sort(double[] arrays){ double temp = 0; for (int i = 0; i < arrays.length-1; i++) { boolean flag = false; for (int j = 0; j < arrays.length-1; j++) { if (arrays[j+1] < arrays[j]){ temp = arrays[j+1]; arrays[j+1] = arrays[j]; arrays[j] = temp; flag = true; } } if (flag == false){ break; } } return arrays; } } result [1.0, 15.5, 32.0, 32.0, 45.6, 54.0, 54.0, 58.0, 89.0]
Chapter IV
Object oriented & process oriented
- Process oriented thought
- The steps are clear and simple, what to do in the first step, what to do in the second step
- Process oriented is suitable for dealing with some simple problems
- Object oriented thought
- Birds of a feather flock together, the thinking mode of classification. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
- Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation.
- For describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it.
What is object oriented
- Object oriented programming, OOP
- The essence of object-oriented programming is to organize code by class and data by object.
- abstract
- Three characteristics:
- encapsulation
- inherit
- polymorphic
- From the perspective of epistemology, there are objects before classes. Objects are concrete things. Class is abstract, which is the abstraction of objects
- From the perspective of code operation, there are classes before objects. A class is a template for an object
Relationship between class and object
- Class is an abstract data type. It is the overall description / definition of a certain kind of things, but it can not represent a specific thing.
- Animals, plants, mobile phones, computers
- Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing
- Objects are concrete instances of abstract concepts
- Zhang San is a concrete example of people, and Wang CAI in Zhang San's family is a concrete example of dogs
- What can reflect the characteristics and functions is a concrete example, not an abstract concept
Creating and initializing objects
- Create an object using the new keyword
- When using the new keyword, in addition to allocating memory space, the created object will be initialized and the constructor in the class will be called.
- The constructor in a class is called a constructor and must be called when creating an object. And the constructor has the following two characteristics:
- Must be the same as the class name
- There must be no return type and void cannot be written
- Constructors must master
// Define a student class public class Student { String name; int age; } public class Man { public static void main(String[] args) { // Instantiate student class Student student1 = new Student(); Student student2 = new Student(); student1.name="xiaohong"; student1.age = 10; student2.name = "xiaoming"; student2.age = 10; System.out.println(student1.name); System.out.println(student1.age); System.out.println(student2.name); System.out.println(student2.age); } } result xiaohong 10 xiaoming 10
Conclusion: class is abstract and object is concrete. Instantiate abstract classes into objects one by one through the new keyword.
constructor
Instantiating an object through the new keyword actually calls the constructor in the abstract class (the constructor is actually a method), which is divided into parametric construction and nonparametric construction. When nothing is written, there will be a parameterless construct by default. After the parameterless construct is written, if you want to use the parameterless construct, the parameterless construct must be written out explicitly.
public class Person { String name; int age; // A parameterized construct is written, and a nonparametric construct must be written explicitly public Person(){} public Person(String name,int age){ this.name = name; this.age = age; } public Person(String name){ this.name = name; } } public class Application { public static void main(String[] args) { // The new procedure actually calls the constructor in the class Person person = new Person("xiaoming",10); System.out.println(person.name); } } result: xiaoming
Create object memory analysis
public class Pet { public String name; public int age; public void shout(String str){ System.out.println(str + "Let out a cry..."); } } public class Animal { public static void main(String[] args) { Pet dog = new Pet(); dog.name = "Wangcai"; dog.age = 3; dog.shout(dog.name); Pet cat = new Pet(); cat.name = "prosperous"; cat.age = 2; cat.shout(cat.name); } } result Wangcai shouted... Boom gave a cry...
The stack stores references to methods and objects. Specific instance objects are stored in the heap, and the method area also belongs to the heap. It has been loaded when the class is loaded, so static methods can be called directly.
Object summary
-
Classes and objects
- Class is a template: abstraction. Object is a concrete instance.
-
method
- Definition and call
-
Application of object
- Reference type, basic type (eight categories)
- Objects are operated by reference: stack – > heap
-
attribute
- Field, member variable
- Default initialization:
- Number: 0.0
- char: u0000
- boolean: false
- Reference type: ull
- Modifier attribute type attribute name = attribute value
-
Object creation and use
- You must use the new keyword to create an object, and the constructor Person xxc = new Person();
- Object properties: xxC name;
- Object method: xxC 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 operation details of the class are completed by themselves, 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.
- It's enough to remember this sentence: property private, get/set
public class Student { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age > 120 || age < 0){ this.age = 3; }else{ this.age = age; } } } public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("xxc"); s1.setAge(150); System.out.println(s1.getName()); System.out.println(s1.getAge()); } } result xxc 3
Note: encapsulation is the encapsulation of attributes.
inherit
- The essence of inheritance is to abstract a certain class, so as to realize better modeling of the real world
- Extensions means "extension". A subclass is an extension of a parent class.
- In Java, there is only single inheritance, not multiple inheritance. A son can only have one father.
- Inheritance is a relationship between classes. In addition, the relationships between classes include dependency, composition, aggregation and so on.
- Two classes of inheritance relationship: one is a child class (derived class) and the other is a parent class (base class). The subclass inherits from the parent class and is represented by the keyword extends.
- In a sense, there should be a "is a" relationship between the child class and the parent class.
- object class
- super - this
- Method Rewriting: emphasis – > polymorphism
public class Person { private String name; private int age; public void sleep(int age , String name){ System.out.println(name+"this year"+age+"Years old, now asleep..."); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } // If a subclass inherits from the parent class, it will have all the methods of the parent class public class Student extends Person { } public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("Xiao Wang"); s1.setAge(3); String name = s1.getName(); int age = s1.getAge(); s1.sleep(age,name); } } result Xiao Wang is 3 years old. Now he is asleep...
super detailed explanation
public class Person { protected String name = "xxc"; } public class Student extends Person{ private String name = "jiangnan"; public void test(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name); } } public class Application { public static void main(String[] args) { Student student = new Student(); student.test("Wangzi"); } } result Wangzi jiangnan xxc
super note:
- super calls the constructor of the parent class, which must be in the first instance of the constructor
- super must only appear in subclass methods or constructor methods
- super and this cannot call constructor at the same time
super vs this:
- The objects represented are different
- this: the object itself is the caller
- super: represents a reference to a parent object
- premise
- this: can be used without inheritance
- super: can only be used under inheritance conditions
- Construction method
- this(); Original structure
- super(); Construction of parent class
rewrite
public class Person { public void show(){ System.out.println("Person=>show"); } } public class Student extends Person{ public void show(){ System.out.println("Student=>show"); } } public class Application { public static void main(String[] args) { // A parent class reference points to a child class object Person student = new Student(); student.show(); } } result Student=>show
rewrite:
-
Inheritance relationship is required. The subclass overrides the method of the parent class
-
- Method names must be the same
- The parameter list must be the same
- Modifier: the range can be expanded but not reduced. public>protected>defaule>private
- Exception thrown: the scope can be reduced, but not expanded. classNotFoundException<Exception
-
Override: the methods of the subclass and the parent class must be the same, but the method bodies are different
-
Why rewrite:
- The functional subclasses of the parent class do not necessarily need or meet the requirements.
polymorphic
-
That is, the same method can take many different behavior modes according to different sending objects
-
The actual type of an object is determined, but there are many types of references that can point to an object
-
Conditions for the existence of polymorphism
- There is an inheritance relationship
- Subclasses override methods of the parent class
- A parent class reference points to a child class object
-
Note: polymorphism is the polymorphism of a method and has nothing to do with attributes
-
instanceof
public class Person { public void show(){ System.out.println("Here is Person"); } } public class Student extends Person{ public void show(){ System.out.println("Here is Student"); } public void eat(){ System.out.println("Student==>eat"); } } public class Application { public static void main(String[] args) { Student student1 = new Student(); Person student2 = new Student(); student1.show(); // Displays the method results of the Student itself student2.show(); // Displays the overridden method results student1.eat(); // Displays the method results of the Student itself ((Student) student2).eat(); // Cannot override, can only cast first } } result Here is Student Here is Student Student==>eat Student==>eat
instanceof
public class Person { public void show(){ System.out.println("Here is Person"); } } public class Student extends Person { public void show(){ System.out.println("Here is Student"); } public void eat(){ System.out.println("Student==>eat"); } } public class Teacher extends Person{ } public class Application { public static void main(String[] args) { Student student1 = new Student(); System.out.println(student1 instanceof Object); System.out.println(student1 instanceof Student); //System.out.println(student1 instanceof Teacher); // Compilation reports an error because Student1 has nothing to do with teacher System.out.println("=========================="); Object student = new Student(); System.out.println(student instanceof Object); System.out.println(student instanceof Teacher); // No error is reported during compilation, because both Student and Teacher inherit from Object System.out.println(student instanceof Student); System.out.println("=========================="); Person student2 = new Student(); student2.show(); ((Student) student2).eat(); // Person itself does not have eat(); Method, which needs to be cast } } result true true ========================== true false true ========================== Here is Student Student==>eat
Conclusion: cast of the reference type is similar to that of the base type. Low to high automatic conversion, high to low conversion requires forced type conversion.
static
public class Student { { // The initial value can be assigned in this way System.out.println("Anonymous code block"); } static { System.out.println("Static code block"); } public Student(){ System.out.println("Construction method"); } public static void main(String[] args) { Student student1 = new Student(); System.out.println("==========================="); Student student2 = new Student(); } } result Static code block Anonymous code block Construction method =========================== Anonymous code block Construction method
Conclusion: it can be found that static code blocks are executed first and only once. Other methods are executed every time an object is instantiated. Anonymous code blocks can be used to assign some initial values to objects, because anonymous code blocks execute before constructing methods
abstract class
- The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method. If you modify a class, the class is an abstract class
- Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes
- Abstract class: you cannot use the new keyword to create an object. It is used to let subclasses inherit
- Abstract method: there is only method declaration, no method implementation. It is used for subclass implementation
- If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class
public abstract class Action { public abstract void run(); } public class Action1 extends Action{ @Override public void run() { System.out.println("The subclass must implement the occurrence method in the parent class"); } } public class Application { public static void main(String[] args) { // Action action = new Action(); Cannot use the new keyword Action1 action1 = new Action1(); action1.run(); } } result The subclass must implement the occurrence method in the parent class
Conclusion: if the parent class is an abstract class, the subclass must implement the abstract methods in the parent class unless the subclass is also an abstract class. Abstract classes cannot be instantiated by the new keyword.
Interface
- General class: as long as the specific implementation
- Abstract classes: concrete implementations and specifications (abstract methods) are available
- Interface: as long as the specification. Separation of constraints and Implementation: interface oriented programming
- An interface is a specification that defines a set of rules.
- The essence of an interface is a contract. Just like the laws among us, it must be observed after it is formulated
public interface UserService { // Only methods can be defined, not implemented void add(); void delete(); void update(); void query(); } public interface TimerService { void timer(); } public class UserServiceImpl implements UserService,TimerService{ // Multiple inheritance @Override public void add() { // Implement specific methods System.out.println("I realized it add method"); } @Override public void delete() { System.out.println("I realized it delete method"); } @Override public void update() { System.out.println("I realized it update method"); } @Override public void query() { System.out.println("I realized it query method"); } @Override public void timer() { System.out.println("I realized it timer method"); } } public class Application { public static void main(String[] args) { UserServiceImpl userService = new UserServiceImpl(); userService.add(); userService.delete(); userService.update(); userService.query(); userService.timer(); } } result I realized it add method I realized it delete method I realized it update method I realized it query method I realized it Timer method
Inner class
- An internal class is to define another class inside a class. For example, if class B is defined in class A, class B is an internal class relative to class A, and class A is an external class relative to class B
- Member inner class
- Static inner class
- Local inner class
- Anonymous Inner Class
// Member inner class public class Outer { private int age = 10; public void run(){ System.out.println("Outer=>run"); } class Inner{ public void show(){ System.out.println("Inner=>run"); } public void getAge(){ System.out.println("I am an internal class. I can manipulate the properties and methods of external classes:"+age); } public void InnerRun(){ run(); } } } public class Application { public static void main(String[] args) { Outer outer = new Outer(); outer.run(); Outer.Inner inner = outer.new Inner(); inner.InnerRun(); // Get the method of the external class through the internal class inner.show(); inner.getAge(); } } result Outer=>run Outer=>run Inner=>run I am an internal class. I can manipulate the properties and methods of external classes: 10
Static internal classes can be decorated with static
// Local inner class public class Outer { public void method(){ System.out.println("Outer=>method"); class Inner{ public void in(){ System.out.println("I am a method of a local inner class"); } } Inner inner = new Inner(); inner.in(); } } public class Application { public static void main(String[] args) { Outer outer = new Outer(); outer.method(); } } result Outer=>method I am a method of a local inner class
Conclusion: local inner class can only be used locally, and can not be invoked in other classes.
// Anonymous Inner Class public class Outer { public void show(){ System.out.println("I am a method of an external class"); } } class Inner{ public void eat(){ System.out.println("I am the method of the inner class"); } } public class Application { public static void main(String[] args) { Outer outer = new Outer(); // I am instantiated as a concrete outer object outer.show(); // I called my method through my instantiated object new Inner().eat(); // Instead of being instantiated, I called the method directly } } result I am a method of an external class I am the method of the inner class
public class OuterService { public static void main(String[] args) { new UserService(){ @Override public void eat() { System.out.println("I rewritten it eat method"); } }.eat(); } } interface UserService{ void eat(); } result I rewritten it eat method
Chapter V
Exception architecture
- Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions
- Many Exception classes have been defined in the Java API. These Exception classes are divided into two categories: Error and Exception
Error
- The Error class object is generated and thrown by the Java virtual machine. Most errors have nothing to do with the operation performed by the coder
- Java virtual machine running error. OutOfMemoryError will appear when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine (JVM) generally selects thread termination
- In addition, when the virtual machine attempts to execute the application, such as class definition error (NoClassDefFoundError) and link error (LinkageError). These errors are not traceable because they are outside the control and processing power of the application, and most of them are not allowed when the program is running.
Exception
- There is an important subclass runtimeException (runtime Exception) in the Exception branch
- ArrayIndexOutOfBoundsException (array subscript out of bounds)
- NullPointerException (null pointer exception)
- ArithmeticException (arithmetic exception)
- MissingResourceException (missing resource)
- ClassNotFoundException (class not found) and other exceptions. These exceptions are not checked. The program can choose to capture and handle them or not.
- These exceptions are generally caused by program logic errors. The program should avoid these exceptions as much as possible from a logical point of view
- The difference between Error and Exception: Error is usually a catastrophic and fatal Error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose to terminate the thread; Exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program
Exception handling mechanism
- Throw exception
- Catch exception
- Five keywords for exception handling
- try, catch, finally, throw, throws
public class Test { public static void main(String[] args) { try { new Test().a(); }catch (Error e){ System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable e){ System.out.println("Throwable"); }finally { System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } } result Error finally
Conclusion:
- The five keywords try and catch must appear in pairs
- finally, it will always be executed
- Exceptions have a size order, and the maximum is Throwable. They should be placed last when captured, otherwise exceptions will be reported
public class Test { public static void main(String[] args) { int a = 1; int b = 1; try { new Test().test(a,b); System.out.println(new Test().shout(a,b)); } catch (Exception e) { System.out.println("There is an exception, please handle it"); }finally { System.out.println("finally"); } } public void test(int a,int b) { if (b == 0){ throw new ArithmeticException(); } } public int shout(int a,int b){ return a/b; } } result 1 finally
Summary: throw manually throws exceptions in the method. Throws actively throws exceptions in the method. It is generally used when the method cannot handle exceptions.
Custom exception
- Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can define exceptions themselves. You can customize the Exception class by inheriting the Exception class
- Using custom exception classes in programs can be roughly divided into the following steps:
- Create custom exception class
- Throw an exception object through the throw keyword in the method
- If you want to handle the exception in the method that throws the exception, you can use the try catch statement to catch and handle it. Otherwise, in the method declaration, use the throws keyword to indicate the exception to be thrown to the method caller, and continue with the next operation
- Catch and handle exceptions in the caller of the method where the exception occurred
Experience summary in practical application
- When handling runtime exceptions, logic is used to reasonably avoid and assist in try catch processing
- A catch (Exception) can be added after multiple catch blocks to handle exceptions that may be missed
- For uncertain code, you can also add try catch to handle potential exceptions
- Try to handle exceptions. Remember to simply print printStackTrace()
- How to handle exceptions should be determined according to different business requirements and exception types
Most of them are not allowed when the program is running.
Exception
- There is an important subclass runtimeException (runtime Exception) in the Exception branch
- ArrayIndexOutOfBoundsException (array subscript out of bounds)
- NullPointerException (null pointer exception)
- ArithmeticException (arithmetic exception)
- MissingResourceException (missing resource)
- ClassNotFoundException (class not found) and other exceptions. These exceptions are not checked. The program can choose to capture and handle them or not.
- These exceptions are generally caused by program logic errors. The program should avoid these exceptions as much as possible from a logical point of view
- The difference between Error and Exception: Error is usually a catastrophic and fatal Error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose to terminate the thread; Exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program
Exception handling mechanism
- Throw exception
- Catch exception
- Five keywords for exception handling
- try, catch, finally, throw, throws
public class Test { public static void main(String[] args) { try { new Test().a(); }catch (Error e){ System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable e){ System.out.println("Throwable"); }finally { System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } } result Error finally
Conclusion:
- The five keywords try and catch must appear in pairs
- finally, it will always be executed
- Exceptions have a size order, and the maximum is Throwable. They should be placed last when captured, otherwise exceptions will be reported
public class Test { public static void main(String[] args) { int a = 1; int b = 1; try { new Test().test(a,b); System.out.println(new Test().shout(a,b)); } catch (Exception e) { System.out.println("There is an exception, please handle it"); }finally { System.out.println("finally"); } } public void test(int a,int b) { if (b == 0){ throw new ArithmeticException(); } } public int shout(int a,int b){ return a/b; } } result 1 finally
Summary: throw manually throws exceptions in the method. Throws actively throws exceptions in the method. It is generally used when the method cannot handle exceptions.
Custom exception
- Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can define exceptions themselves. You can customize the Exception class by inheriting the Exception class
- Using custom exception classes in programs can be roughly divided into the following steps:
- Create custom exception class
- Throw an exception object through the throw keyword in the method
- If you want to handle the exception in the method that throws the exception, you can use the try catch statement to catch and handle it. Otherwise, in the method declaration, use the throws keyword to indicate the exception to be thrown to the method caller, and continue with the next operation
- Catch and handle exceptions in the caller of the method where the exception occurred
Experience summary in practical application
- When handling runtime exceptions, logic is used to reasonably avoid and assist in try catch processing
- A catch (Exception) can be added after multiple catch blocks to handle exceptions that may be missed
- For uncertain code, you can also add try catch to handle potential exceptions
- Try to handle exceptions. Remember to simply print printStackTrace()
- How to handle exceptions should be determined according to different business requirements and exception types
- Try to add finally statement blocks to release the occupied resources