1, Preface, introductory program, constant, variable
1.1 what is the Java language
Java language is a high-level programming language launched by Sun Corporation (Stanford University Network) in 1995. The so-called programming language is the language of the computer. People can use the programming language to give orders to the computer and let the computer complete the functions that people need.
1.2 what can the Java language do
Java language is mainly used in the development of Internet programs. Common Internet programs, such as tmall, jd.com, logistics system and online banking system, as well as the storage, query and data mining of big data processed by the server background, also have many applications.
1.3 basic knowledge of computer
In binary number system, each 0 or 1 is a bit, which is called bit.
Byte is the smallest storage unit in our common computer. Any data stored by the computer is stored in bytes. Right click the file attribute to view the byte size of the file. 8 bits (binary bits) 0000-0000 are expressed as 1 byte, written as 1 byte or 1 B.
8 bit = 1 B
1024 B =1 KB
1024 KB =1 MB
1024 MB =1 GB
1024 GB = 1 TB
1.4 common DOS commands
DOS is an early operating system, which has been replaced by Windows system. For our developers, we need to complete some things in DOS, so we need to master some necessary commands.
Common commands:
start-up | Win+R, enter cmd and press enter |
---|---|
Switch drive letter | Drive letter name: |
Enter folder | cd folder name |
Enter multi-level folder | cd folder 1 \ Folder 2 \ folder 3 |
Return to the previous level | cd ... |
Direct back to root path | cd \ |
View current content | dir |
Clear screen | cls |
sign out | exit |
1.5 JVM, JRE and JDK
JVM (Java Virtual Machine): Java Virtual Machine, referred to as JVM for short. The JVM realizes the cross platform characteristics of Java language. The program we write runs on the JVM, while the JVM runs on the operating system. Java Virtual Machine itself does not have cross platform function. There are different versions of virtual machines under each operating system.
JRE (Java Runtime Environment): it is the runtime environment of Java programs, including the JVM and the core class libraries required by the runtime.
JDK (Java Development Kit): it is a Java program development kit, including tools used by JRE and developers.
(to run an existing Java program, you only need to install JRE; to develop a new Java program, you must install JDK.)
Relationship among the three: JDK > JRE > JVM
1.6 HelloWorld starter
Three steps of Java program development: Writing (lava source program), compiling (compiled source program is bytecode file) and running (JVM).
//The file name must be HelloWorld. Ensure that the file name is consistent with the name of the class. Pay attention to case. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
Compile Java source files:
On the DOS command line, enter the directory of Java source files, javac HelloWorld Java, a new file HelloWorld Class is a Java executable file, called bytecode file, which runs java HelloWorld.
1.7 introduction procedure description
Compilation: it refers to translating the Java source file into the class file recognized by the JVM. In this process, the javac compiler will check whether there are errors in the program we write. If there are errors, it will be prompted. If there are no errors, it will be compiled successfully.
Run: it refers to giving the class file to the JVM to run. At this time, the JVM will execute the program we write.
Main method: called the main method. The writing method is fixed and cannot be changed. The main method is the entry point or starting point of the program. No matter how many programs we write, the JVM will start executing from the main method when running.
Note: it is the explanation and explanation of the code. Single line comment with / /; Multiline comment with / * * /.
Keyword: refers to the words defined by Java in the program, which have special meanings.
Identifier: refers to the content defined by ourselves in the program. For example, the name of the class, the name of the method and the name of the variable.
Identifier naming and specification:
Naming rules: (mandatory)
Identifiers can contain English letters (case sensitive), numbers, $and.
Identifier cannot start with a number.
Identifier cannot be a keyword.
Naming conventions: (soft recommendations)
Class name specification: capitalize the first letter, and capitalize the first letter of each subsequent word (big hump type).
Method name specification: the first letter is lowercase, and the first letter of each subsequent word is capitalized (small hump type).
Variable name specification: all lowercase.
1.8 constants
Constant: refers to the fixed data in the Java program.
Classification:
type | meaning | Data examples |
---|---|---|
integer constant | All integers | 0,1, 567, -9 |
Decimal constant | All decimals | 0.0, -0.1, 2.55 |
character constants | When enclosed in single quotation marks, only one character can be written, and there must be content | 'a', 'OK' |
string constant | Enclosed in double quotation marks, you can write multiple characters or not | "A" ,"Hello" ,"" |
Boolean Literals | Only two values (explained in process control) | true , false |
Null constant | Only one value (explained in reference data type) | null |
1.9 variables and data types
Variable: constant is fixed data, so the amount that can be changed in the program is called variable. Java requires that a variable can only save one data at a time, and the data type to be saved must be specified.
Data type classification:
The data types of Java are divided into two categories:
Basic data types: including integer, floating point number, character and Boolean.
Reference data type: including class, array and interface.
Four categories and eight basic data types:
data type | keyword | Memory occupation | Value range |
---|---|---|---|
Byte type | byte | 1 byte | -128~127 |
Short | short | 2 bytes | -32768~32767 |
integer | int (default) | 4 bytes | -The 31st power of 231 ~ 2 - 1 |
Long integer | long | 8 bytes | -63rd power of 2 ~ 63rd power of 2 - 1 |
Single-precision floating-point | float | 4 bytes | 1.4013E-45~3.4028E+38 |
Double precision floating point number | double (default) | 8 bytes | 4.9E-324~1.7977E+308 |
character | char | 2 bytes | 0-65535 |
Boolean type | boolean | 1 byte | true,false |
The default type in Java: integer type is int and floating point type is double.
Definition of variables:
The format of variable definition includes three elements: data type, variable name and data value.
Format: data type variable name = data value;
be careful:
long type: it is recommended to add L after the data. float type: it is recommended to add F after the data.
Variable name: variable names cannot be the same within the same brace range.
Variable assignment: defined variable. It cannot be used without assignment.
2, Introduction to data type conversion, operators and methods
2.1 data type conversion
Automatic conversion: automatically promote a type with a small value range to a type with a large value range.
Byte type memory occupies 1 byte, which will be promoted to int type when operating with int type, and 3 bytes will be added automatically
public static void main(String[] args) { int i = 1; byte b = 2; // byte x = b + i; // report errors //Int type and byte type operation, and the result is int type int j = b + i; System.out.println(j); }
Similarly, when an int variable and a double variable operate, the int type will be automatically promoted to double type for operation.
public static void main(String[] args) { int i = 1; double d = 2.5; //int type and double type operation, and the result is double type //int type is promoted to double type double e = d+i; System.out.println(e); }
Conversion rule: type with small range is promoted to type with large range, and byte, short and char are directly promoted to int during operation.
byte,short,char‐‐>int‐‐>long‐‐>float‐‐>double
Cast: cast a type with a large value range into a type with a small value range.
In comparison, automatic conversion is performed automatically by Java, while forced conversion needs to be performed manually by ourselves.
Conversion format: data type variable name = (data type) converted data value;
public static void main(String[] args) { //short type variable, 2 bytes in memory short s = 1; /* Compilation failure occurred s When doing operations with 1, 1 is of type int, and s will be promoted to type int s+1 The result after is of type int, and an error occurs when assigning the result to type short short Memory 2 bytes, int type 4 bytes int must be forced to short to complete the assignment */ s = s + 1;//Compilation failed s = (short)(s+1);//Compiled successfully }
be careful:
Converting floating point to integer and directly canceling the decimal point may cause data loss of accuracy.
int is forcibly converted to short and 2 bytes are cut off, which may cause data loss.
ASCII encoding table:
Coding table: it is to form a table by corresponding human words with a decimal number.
ASCII table example:
character | numerical value |
---|---|
Space | 32 |
0 | 48 |
9 | 57 |
A | 65 |
Z | 90 |
a | 97 |
z | 122 |
public static void main(String[] args) { //Character type variable char c = 'a'; int i = 1; //Character type and int type calculation System.out.println(c+i);//The output is 98 }
be careful:
During the calculation of char type and int type, char type characters first query the coding table to get 97, and then sum with 1 to get 98. Char type promoted to int type. Char type memory 2 bytes, int type memory 4 bytes.
2.2 operators
Arithmetic operators: +, -, *, /,%, + +, –
+Operation of symbol in string:
+When a symbol encounters a string, it indicates the meaning of connection and splicing.
The result of "a" + "b" is "ab", connecting the meaning
public static void main(String[] args){
System.out.println(“5+5=”+5+5);// Output 5 + 5 = 55
}
Assignment operators: =, + =, - =, * =, / =,% =; The assignment operator is to assign the value on the right of the symbol to the variable on the left.
Comparison operators: = =, <, >, < =, > =,! =; Comparison operator is the operation of comparing two data, and the operation resu lt is Boolean value true or false.
Logical operators: & &, |!; Logical operator is an operator used to connect two Boolean results. The operation results are Boolean values true or false.
public static void main(String[] args) { System.out.println(true && true);//true System.out.println(true && false);//false System.out.println(false && true);//false, not calculated on the right System.out.println(false || false);//falase System.out.println(false || true);//true System.out.println(true || false);//true, not calculated on the right System.out.println(!false);//true }
Ternary operator:
Ternary operator format: data type variable name = boolean type expression? Result 1: result 2
The expression result is true, the variable assignment result is 1, otherwise the assignment result is 2.
public static void main(String[] args) { int i = (1==2 ? 100 : 200); System.out.println(i);//200 int j = (3<=4 ? 500 : 600); System.out.println(j);//500 }
2.3 introduction to methods
Method: extract a function and define the code in a brace to form a separate function.
Method definition format:
Modifier return value type method name (parameter list){ code... return ; } public static void methodName() { System.out.println("This is a method"); }
Method call: after the method is defined, the method will not run by itself and must be called before execution. We can call the method defined by ourselves in the main method.
public static void main(String[] args) { //Call the defined method method(); } //Define a method, which is called by the main method public static void method() { System.out.println("Self defined methods need to be main Call run"); }
Precautions for method definition:
Methods must be defined outside of methods in a class
Method cannot be defined in another method
Expand knowledge points
+=Symbol extension:
public static void main(String[] args){ short s = 1; s+=1; System.out.println(s); }
Analysis: s += 1 is logically regarded as s=s+1. The calculation result is promoted to int type, and an error occurs when assigning value to short type, because the type with large value range cannot be assigned to the type with small value range. However, s=s+1 performs two operations. + = is an operator, which only operates once, and has the characteristics of forced conversion. That is, s += 1 is s = (short)(s + 1). Therefore, the program has no problem. It compiles and runs with the result of 2
Operation of constants and variables:
public static void main(String[] args){ byte b1=1; byte b2=2; byte b3=1 + 2; byte b4=b1 + b2; System.out.println(b3); System.out.println(b4); }
Analysis: b3=1 + 2. 1 and 2 are constants and are fixed data. When compiling (compiler javac), it has been determined that the result of 1 + 2 does not exceed the value range of byte type and can be assigned to variable b3. Therefore, b3=1 + 2 is correct.
On the contrary, B4 = b2+b3, b2 and b3 are variables, and the value of variables may change. During compilation, the compiler javac is not sure what the result of b2+b3 is, so it will process the result as int type, so int type cannot be assigned to byte type, so compilation fails.
3, Process control statement
3.1 sequence structure
public static void main(String[] args){ //Execute sequentially, and run from top to bottom according to the writing order System.out.println(1); System.out.println(2); System.out.println(3); }
3.2 judgment statement
if statement format:
(1)
If (relational expression)
Sentence body;
}
First, judge the relational expression to see whether the result is true or false
If true, execute the statement body
If false, the statement body is not executed
(2)
If (relational expression){
Sentence body 1;
}else {
Sentence body 2;
}
First, judge the relational expression to see whether the result is true or false
If true, execute statement body 1
If false, execute statement body 2
(3)
if (judgment condition 1){
Execute statement 1;
}else if (judgment condition 2){
Execute statement 2;
}
...
}else if (judgment condition n){
Execute statement n;
} else {
Execute statement n+1;
}
First, judge the relationship expression 1 to see whether the result is true or false
If true, execute statement body 1
If it is false, continue to judge relationship expression 2 to see whether the result is true or false
If true, execute statement body 2
If it is false, continue to judge the relational expression... To see whether the result is true or false
...
If no relational expression is true, the statement body n+1 is executed.
Sentence exercise:
- Assign test scores and judge student grades
90-100 excellent
80-89 okay
70-79 good
60-69 pass
Fail below 60
public static void main(String[] args) { int score = 100; if(score<0 || score>100){ System.out.println("Your grades are wrong"); }else if(score>=90 && score<=100){ System.out.println("Your grades are excellent"); }else if(score>=80 && score<90){ System.out.println("Your grades are good"); }else if(score>=70 && score<80){ System.out.println("Your grades are good"); }else if(score>=60 && score<70){ System.out.println("Your grade is a pass"); }else { System.out.println("Your grade is a failure"); } }
Interchange of if statement and ternary operator:
public static void main(String[] args) { int a = 10; int b = 20; //Define variables and save the larger values of a and b int c; if(a > b) { c = a; } else { c = b; } //The above functions can be rewritten into the form of ternary operators c = a > b ? a:b; }
3.3 selection statement
Select statement – switch:
switch Statement format: switch(expression) { case Constant value 1: Statement body 1; break; case Constant value 2: Statement body 2; break; ... default: Statement body n+1; break; }
First, calculate the value of the expression
Secondly, compare with case in turn. Once there is a corresponding value, the corresponding statement will be executed, and the break will end in the process of execution.
Finally, if all case s do not match the value of the expression, the body of the default statement is executed, and the program ends.
public static void main(String[] args) { //Define the variable and judge the day of the week int weekday = 6; //switch statement implementation selection switch(weekday) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("The number you entered is wrong"); break; } }
In the switch statement, the data type of the expression can be byte, short, int, char, enum (enumeration), and the string can be received after JDK7.
Penetration of case: in the switch statement, if break is not written after the case, penetration will occur, that is, the value of the next case will not be judged and will be transported back directly
Line until a break is encountered or the overall switch ends.
public static void main(String[] args) { int i = 5; switch (i){ case 0: System.out.println("implement case0"); break; case 5: System.out.println("implement case5"); case 10: System.out.println("implement case10"); //break; default: System.out.println("implement default"); } } //After executing case5, because there is no break statement, the program will go back all the time. It will not judge the case until it encounters a break. Otherwise, it will directly run the complete switch.
3.4 circular statements
for loop statement format:
for(Initialization expression①; Boolean expression②; Step expression④){ Circulatory body③ }
Execution process:
Execution sequence: ① ② ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
① Responsible for completing the initialization of loop variables
② Be responsible for judging whether the cycle conditions are met. If not, jump out of the cycle
③ Specific executed statement
④ After the cycle, the change of variables involved in the cycle conditions
- Loop exercise: use a loop to calculate the even sum between 1-100
public static void main(String[] args) { //1. Define an initialization variable, record accumulation and summation, and the initial value is 0 int sum = 0; //2. Use the for loop to obtain the number between 1-100 for (int i = 1; i <= 100; i++) { //3. Judge whether the obtained array is odd or even if(i % 2==0){ //4. If it is an even number, accumulate and sum sum += i; } } //5. After the cycle ends, print the accumulation result System.out.println("sum:"+sum); }
while loop statement format:
Initialization expression① while(Boolean expression②){ Circulatory body③ Step expression④ }
Execution process:
Execution sequence: ① ② ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
① Responsible for completing the initialization of loop variables.
② Be responsible for judging whether the cycle conditions are met. If not, jump out of the cycle.
③ Specific execution statement.
④ After the cycle, the change of the cycle variable.
- The while loop calculates the sum between 1-100
public static void main(String[] args) { //Using the while loop //Define a variable and record the cumulative sum int sum = 0; //Define initialization expression int i = 1; //Use the while loop to change the value of the initialization expression while(i<=100){ //Cumulative summation sum += i ; //A step expression changes the value of a variable i++; } //Print summed variables System.out.println("1‐100 The sum of is:"+sum); }
do... while loop format:
Initialization expression① do{ Circulatory body③ Step expression④ }while(Boolean expression②);
Execution process:
Execution sequence: ① ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
① Responsible for completing the initialization of loop variables.
② Be responsible for judging whether the cycle conditions are met. If not, jump out of the cycle.
③ Specific executed statement
④ Changes of cyclic variables after cycling
Characteristics of do... while loop: unconditionally execute the loop body once. Even if we directly write the loop condition as false, it will still loop once. In this way
Loops have certain risks, so beginners are not recommended to use do... while loops.
public static void main(String[] args){ do{ System.out.println("Unconditional execution once"); }while(false); }
Differences between circular statements:
Minor differences between for and while:
The variable controlled by the control condition statement can no longer be accessed after the end of the for loop, and the while loop can continue to be used. If you want to continue to use it, use while, otherwise it is recommended to use for. The reason is that when the for loop ends, the variable disappears from memory, which can improve the efficiency of memory use (here refers to the variable defined in for()).
for is recommended when the number of cycles is known and while is recommended when the number of cycles is unknown.
Jump out statement:
break: terminate the switch or the nearest loop.
Continue: end this cycle and continue the next cycle.
Expand knowledge points
Dead loop: that is, the condition in the loop is always true, and the dead loop is a loop that never ends. For example: while(true) {}.
Nested loop: the loop body of one loop is another loop. For example, there is also a for loop in the for loop, which is a nested loop.
- Exercise: using nested loops, print a 5 * 8 rectangle
public static void main(String[] args) { //5 * 8 rectangle, print 5 lines of * marks, 8 for each line //External circulation for 5 times and internal circulation for 8 times for (int i = 0; i < 5; i++) { for (int j = 0; j < 8; j++) { //Print asterisks without line breaks System.out.print("*"); } //After 8 asterisks are printed in the inner loop, a line feed is required System.out.println(); } }
4, Method
4.1 installing and using the development tool IntelliJ IDEA
4.2 method
Method definition and call:
public class test { public static void main(String[] args) { print(); } private static void print() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 8; j++) { System.out.print("*"); } System.out.println(); } } } //The print method directly outputs the result after being called by the main method, and the main method does not need the execution result of the print method, so it is defined as void .
4.3 format of definition method
Modifier return value type method name(parameter list){ //Code omission return result; //Return result; In the development of the "result" here, we correctly call it the return value of the method }
Modifier: public static fixed writing method
Return value type: the data type representing the result of the method operation. After the method is executed, the result is returned to the caller
Parameter list: unknown data in the operation of the method, which is passed when the caller calls the method
Return: bring the result of the method execution to the caller. After the method is executed to return, the overall method operation ends
Two explicit definitions of methods: explicit return value type and explicit parameter list
- Requirements: define the method to realize the summation calculation of two integers.
Specify the return value type: the method calculates the sum of integers, and the result must be an integer. The return value type is defined as int type.
Explicit parameter list: it is not clear which two integers to calculate the sum, but it can be determined that they are integers. The parameter list can define two int type variables, which are passed by the caller when calling the method
public class test { public static void main(String[] args) { // Call the method getSum and pass two integers. The actual data passed here is also called the actual parameter // And receive the result calculated by the method and return the value int sum = getSum(5, 6); System.out.println(sum); } /* Defines how to calculate the sum of two integers Return value type. The calculation result is int Parameter: sum uncertain data, define int parameter Parameters are also called formal parameters */ public static int getSum(int a, int b) { return a + b; } }
Flow diagram of calling method:
4.4 definition method exercise
Compare whether two integers are the same:
- Analysis: to define a method to implement a function, there need to be two explicit, namely, the return value and the parameter list.
- Clear return value: when comparing integers, there are only two possible results, the same or different. Therefore, the result is Boolean and the same result is true.
- Explicit parameter list: the two integers compared are uncertain, so two int type parameters are defined by default.
public static void main(String[] args) { //Call the compare method and pass two integers //And receive the result calculated by the method, Boolean value boolean bool = compare(3, 8); System.out.println(bool); } /* Defines a method to compare whether two integers are the same Return value type, boolean type of comparison result Parameter: two integers involved in the comparison are uncertain */ public static boolean compare(int a, int b) { if (a == b) { return true; } else { return false; } }
Calculate the sum of 1 + 2 + 3... + 100:
- Analysis: to define a method to implement a function, you need to have two explicit: return value and parameter.
- Specify the return value: the sum of 1 ~ 100 must be an integer after calculation, and the return value type is int
- Explicit parameters: the calculated data is known in the requirements, there is no unknown data, and the parameters are not defined
public class test { public static void main(String[] args) { //Call method getSum //And receive the result calculated by the method, integer int sum = getSum(); System.out.println(sum); } /* Define the summation method for calculating 1 ~ 100 Return value type, calculation result integer int Parameter: no uncertain data */ public static int getSum() { //Define variable save summation int sum = 0; //Cycle from 1 to 100 for (int i = 1; i <= 100; i++) { sum = sum + i; } return sum; } }
Print indefinitely:
- Analysis: to define a method to implement a function, you need to have two explicit: return value and parameter.
- Specify the return value: just print HelloWorld in the method. There is no calculation result, and the return value type is void.
- Explicit parameter: if it is unclear after printing several times, the parameter defines an integer parameter
public class test { public static void main(String[] args) { //Call the method printHelloWorld to pass an integer printHelloWorld(9); } /* Define the HelloWorld method for printing The return value type has no result void Parameter: print several times indefinitely */ public static void printHelloWorld(int n) { for (int i = 0; i < n; i++) { System.out.println("HelloWorld"); } } }
Considerations for defining methods:
Define the location outside the method in the class.
The return value type must be the same as that returned by the return statement, otherwise the compilation fails.
You cannot write code after return. Return means that the method ends and all subsequent codes will never be executed. It is invalid code.
There are three forms of calling methods:
Direct call: direct write method name call
Assignment call: call a method, define variables in front of the method, and receive the return value of the method
Output statement call: call method in output statement, System. out. Println (method name ()). A method of type void cannot be called with an output statement. Because there is no result after the method is executed, nothing can be printed.
4.5 method overload
Method overloading: more than one method with the same name is allowed in the same class, as long as their parameter lists are different, regardless of modifiers and return value types.
Parameter list: different numbers, data types and orders.
Overloaded method call: the JVM calls different methods through the parameter list of the method.
Method overload exercise:
- Compare whether the two data are equal. The parameter types are two byte types, two short types, two int types, two long types, and
Test in the main method.
public class test { public static void main(String[] args) { //Define variables of different data types byte a = 10; byte b = 20; short c = 10; short d = 20; int e = 10; int f = 10; long g = 10; long h = 20; // call System.out.println(compare(a, b)); //byte System.out.println(compare(c, d));//short System.out.println(compare(e, f));//int System.out.println(compare(g, h));//long } // Two byte type public static boolean compare(byte a, byte b) { System.out.println("byte"); return a == b; } // Two types of short public static boolean compare(short a, short b) { System.out.println("short"); return a == b; } // Two int s public static boolean compare(int a, int b) { System.out.println("int"); return a == b; } // Two long type public static boolean compare(long a, long b) { System.out.println("long"); return a == b; } }