Hard core dry goods! Java cultivation of Qi building foundation (continuously updated)

Posted by Dilb on Tue, 21 Dec 2021 02:00:06 +0100

	Because I'm still deeply impressed by the sky breaking of natural potatoes,
	So take the protagonist Xiao Yan for example. The stage of Qi training and foundation building is very important. Only when the foundation is firmly laid, can we cut through thorns and thorns all the way and fight higher and higher!
	Similarly, for fresh contact Java For my little partner, Java The foundation is the process of practicing Qi and building foundation. Only by laying a solid foundation can ten thousand storey high-rise buildings be pulled up and unshakable despite the wind and rain!
	Although I studied during my undergraduate course, I only remember some piecemeal contents, so I want to study systematically in my spare time of graduate school.
	Now let Xiao Zeng take you to learn java Foundation, let's practice Qi and build foundation together!

Java Foundation

1.1 notes, identifiers and keywords

notes

I believe everyone who has written code knows that comments are written for our programmers. When the project program is more complex, comments are also very important. Therefore, develop a good habit of comments, and details determine success or failure.
There are three types of annotations in Java:
Single line comment: only the current line can be commented, starting with / / until the end of the line
Multiline annotation: annotate a paragraph of text, starting with / and ending with /!

public class HelloWorld {
    public static void main(String[] args) {
        // Single line comment, which does not affect the operation of the program
        /* multiline comment 
        This form can be used when there are many statements that need to be commented out. Xiao once took you to learn java
         */
        System.out.println("hello,world");
    }
}

Document comments: used to produce API documents in conjunction with JavaDoc.
[note] we only want to know about document comments. We will tell you in detail when learning JavaDoc. It's good to know that there are such comments at present.

keyword

It represents the names defined in java, such as public static class, which have been defined and given relevant meanings. Therefore, we should try not to duplicate the names when naming.
Let's take a look at the keywords defined by Java itself?

Although it seems that there are many keywords, we will contact them in the later study. We look forward to meeting them next time.

identifier

An identifier is a symbol used to identify an entity.
All components of Java need names. Class names, variable names, and method names are all called identifiers.
There are several points to note about Java identifiers:

  • All identifiers should start with letters (a-z or a-z), dollar sign ($), or underscore ()
  • The first character can be followed by any combination of letters (a-z or a-z), dollar sign ($), underscore () or 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

The naming rules for java identifiers are actually quite important. Sometimes there are some basic interview questions, which still need to be paid attention to.

1.2 data type

1.2. 1. Strong and weak type language

Maybe some friends don't know much. We can see from the Java core volume that Java is a strongly typed language, which means that a type must be declared for each variable.

Strongly typed language

Strongly typed languages are also called strongly typed definition languages. 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. In other words, as long as a variable is specified with a data type, it will always be this data type if it is not converted.
The advantages and disadvantages are also obvious:
Advantages: high security, can effectively avoid many errors.
Disadvantages: the operation efficiency is relatively slow.

Weakly typed language

Weakly typed languages are also called weakly typed definition languages. Contrary to strong type definitions, languages such as vb and php belong to weak type languages. String '12' and integer 3 can be concatenated into string '123'

1.2. 2 data type

Java data types can be divided into two categories: basic types and reference types

[Note: the size of the reference data type is unified as 4 bytes, and the address of its reference object is recorded!]

The following table can also be used to represent the basic data types, memory and byte range in 8.
For students with C language foundation, these basic types are old friends and familiar.

 Add: for students with computer foundation, you can skip it. For Xiaobai who doesn't know it at all, you can understand the relevant contents of bytes
 Bit( bit): It is the smallest unit of data storage in the computer. 11001100 is an eight bit binary number. Byte( byte): It is the basic unit of data processing in the computer. It is customary to use uppercase B To represent,
  1B(byte,Bytes)= 8bit(Bit)
 Characters: letters, numbers, words and symbols used in computers
  ASCIIS Code: 
 1 English letters (regardless of case)= 1 Bytes of space  
 1 Chinese characters = 2 Bytes of space
 1 individual ASCII code = One byte
  UTF-8 code:
 1 English characters = 1 Byte English Punctuation = 1 Bytes
 1 Chinese = 3 Byte Chinese punctuation = 3 Bytes
Unicode code:
 1 English characters = 2 Byte English Punctuation = 2 Bytes 1 Chinese (including traditional) = 2 Bytes
 Chinese punctuation = 2 Byte 1 bit Represents 1 bit, 1 Byte Represents a byte 1 B=8b.   1024B=1KB
 1024KB=1M    1024M=1G. 
Then someone will ask: what is the difference between 32-bit and 64 bit computers?
 32 32-bit operating systems can only use 32-bit cpu,And 64 bit CPU You can install either a 32-bit operating system or a 64 bit operating system.
 Addressing capability is simply the memory size capability supported. A 64 bit system can support up to 128 GB The 32-bit system can only support up to 4 G Memory.
 32 A 32-bit operating system can only install software designed using a 32-bit architecture, while a 64 bit operating system CPU You can install and use either 32-bit software or 64 bit software.
Type conversion

Integer, real (constant) and character data can be mixed
In the operation, different types of data are first transformed into the same type, and then the operation is carried out.
Conversion from low-level to high-level (according to capacity)
byte,short,char—> int —> long—> float —> double

Data type conversion must meet the following rules:

  • Cannot type convert boolean type.
  • You cannot convert an object type to an object of an unrelated class.
  • Cast must be used when converting a high-capacity type to a low-capacity type.
  • Overflow or loss of accuracy may occur during conversion
  • The conversion of floating-point numbers to integers is obtained by discarding decimals, not rounding
example:
int i =128;
byte b = (byte)i;   //The byte type is 8 bits and the maximum value is 127. Therefore, when int is cast to byte type, the value 128 will cause overflow.
(int)23.7 == 23;       
(int)-45.89f == -45
Automatic type conversion

Automatic type conversion: data types with small capacity can be automatically converted to data classes with large capacity
byte,short,char—> int —> long—> float —> double

Cast type

The syntax format of cast type conversion is: (type)var, and the type in the operator "()" represents the target data class to which the value var is to be converted
Type. The condition is that the converted data types must be compatible.

public static void main(String[] args) {
		double x = 3.14;
		int nx = (int)x; //A value of 3 forces the conversion of double type to int type
		
		char c = 'a';
		int d = c+1;
		System.out.println(d); //98
		System.out.println((char)d); //b
}


Note: when one type is cast to another type and it exceeds the representation range of the target type, it will be truncated into a completely different value and overflow.
public static void main(String[] args) {
		int x = 300;
		byte bx = (byte)x; //The value is 44
		System.out.println(bx);
}

1.3 variables and constants

variable

What is the variable: it is the variable!
for instance:
It's like we have a big wardrobe in our home. There are many small squares in it. We label the squares, put clothes, shoes, watches, etc. at this time, we know where to put what. However, we don't know what brand of shoes, clothes or pants are put in it. That label is equivalent to our variable. We named it, but we need to put what we put in it ourselves.

Points to note:
1. Java is a strongly typed language, and each variable must declare its type.
2. Java variable is the most basic storage unit in a program. Its elements include variable name, variable type and scope.

Basic format: data type variable name = Value;
int a, b, c; // Declare three int integers: a, b, c
int d = 3, e = 4, f = 5; // Declare three integers and give initial values
byte z = 22; // Declare and initialize z
String s = "runoob"; // Declare and initialize string s
double pi = 3.14159; // The double precision floating-point variable pi is declared
char x = 'x'; // Declare that the value of variable x is the character 'x'.

Variable scope

Variables can be divided into three types according to scope:

  • Class variables (static variables: static variables): variables independent of methods, modified with static.
  • Instance variable (member variable): a variable independent of the method, but without static modification.
  • Local variable: a variable in a method of a class.
Example
 public class Variable{
		static int allClicks=0; // Class variable
		String str="hello world"; // Instance variable
		public void method(){
				int i =0; // local variable
		}
}

constant

Constant: the value cannot be changed after initialization! Value that will not change.
The so-called constant can be understood as a special variable. After its value is set, it is not allowed to be changed during program operation.
Final constant name = value; final double PI=3.14; final String LOVE="hello";

1.4 operators

The Java language supports the following operators:

  • Arithmetic operators: +, -, *, /,%, + +, –
  • Assignment operator=
  • Relational operators: >, <, > =, < =, = == instanceof
  • Logical operators: & &, |, |,!
  • Bitwise operators: &, |, ^, ~, > >, <, > > (understand!!!)
  • Conditional operator?:
  • Extended assignment operators: + =, - =, * =/=

Operator these aspects are relatively simple, which will be described in detail later.

1.5 control process

Sequential structure


Sequential structure is the simplest algorithm structure: between statements and between boxes, it is carried out in the order from top to bottom. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from.

Select structure

1. if single selection structure

We often need to judge whether something is feasible before we execute it. Such a process is represented by an if statement in the program:

Meaning: if statement tests the conditional expression once. If the test is true, execute the following statement, otherwise skip the statement.

2. if double selection structure

Now there is a demand. The company wants to buy a software. If it succeeds, it will pay 1 million yuan to others. If it fails, it will find someone to develop it by itself. Such a requirement cannot be met with an if. We need to have two judgments and a double selection structure, so we have an if else structure.

3. if multiple selection structure

Cyclic structure

Sequential program statements can only be executed once. If you want to perform the same operation multiple times, you need to use a loop structure.
There are three main loop structures in Java:

  • while loop
  • do... while loop
  • for loop
1. while loop
while( Boolean expression ) {
	//Cyclic content
}


[illustration] at the beginning of the loop, the value of "Boolean expression" is calculated once. If the condition is true, the loop body is executed. For each subsequent additional loop, it will be recalculated before starting to judge whether it is true. Until the condition is not tenable, the loop ends.

2. do... while loop

For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to perform at least once even if the conditions are not met.

do {
	//Code statement
}while(Boolean expression);

Difference: the do... While loop is similar to the while loop. The difference is that the do... While loop will be executed at least once.

Note: the Boolean expression follows the loop body, so the statement block has been executed before detecting the Boolean expression. If the value of the Boolean expression is true, the statement block executes until the value of the Boolean expression is false.

3. For loop

Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler.

Advantages: or loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.

for(initialization; Boolean expression; to update) {
		//Code statement
}


Notes before for recycling:

  • Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements.
  • Then, the value of the Boolean expression is detected. If true, the loop body is executed. If false, the loop terminates and starts executing the statement after the loop body.
  • After executing a loop, update the loop control variable (the iteration factor controls the increase or decrease of the loop variable). Detect the Boolean expression again. Loop through the above procedure.
public static void main(String[] args) {
			int a = 1; //initialization
			
			while(a<=100){ //Conditional judgment
				System.out.println(a); //Circulatory body
				a+=2; //iteration
			}
			System.out.println("while End of cycle!");
			
			for(int i = 1;i<=100;i++){ //Initialize / / condition judgment / / iteration
				System.out.println(i); //Circulatory body
			}
			System.out.println("for End of cycle!");
}

In fact, it can also be seen that the for loop simplifies the code and improves readability when the number of cycles is known.

4,break & continue

In a loop statement, if we want to jump out of the loop in advance, what should we do?
Don't worry, break & continue can give you the answer

break keyword

break is mainly used in loop statements or switch statements to jump out of the whole statement block.
break jumps out of the innermost loop and continues to execute the following statements of the loop.

Example:
public static void main(String[] args) {
		int i=0;
		while (i<100){
			i++;
			System.out.println(i);
			if (i==30){
				break;
			}
		}
}
continue keyword

continue applies to any loop control structure. The function is to make the program jump to the iteration of the next loop immediately.
In the for loop, the continue statement causes the program to immediately jump to the update statement.
In the while or do... While loop, the program immediately jumps to the judgment statement of Boolean expression.

public static void main(String[] args) {
			int i=0;
			while (i<100){
				i++;
				if (i%10==0){
					System.out.println();
					continue;
				}
				System.out.print(i);
			}
	}
Break & continue differences
  • 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 the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time.

5. Small instance

Theoretical knowledge is so simple. It's not enough to have theory alone. We still need to combine theory with practice. Today, we mainly talk about simply writing a printed 9 * 9 multiplication table. For small partners, it's relatively simple. I'll introduce it below. I hope you can follow the pace and learn together.

Print results:

Idea: use nested for loops

The realization is mainly divided into three steps

Step 1: let's print the first column first, which everyone should know
for (int i = 1; i <= 9; i++) {
			System.out.println(1 + "*" + i + "=" + (1 * i));
}

Step 2: we wrap the fixed 1 in a loop
for (int i = 1; i <= 9 ; i++) {
	for (int j = 1; j <= 9; j++) {
		System.out.println(i + "*" + j + "=" + (i * j));
	}
}
Step 3: remove duplicates, j<=i
for (int i = 1; i <= 9 ; i++) {
		for (int j = 1; j <= i; j++) {
			System.out.println(j + "*" + i + "=" + (i * j));
		}
}

Final complete code:
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();
}

Summary: in case of problems, we should slowly develop a thinking of how to analyze and cut into problems, peel the cocoon of a large problem, decompose it into several small problems, and then solve them one by one.

1.6 summary

The above content is the most basic content of Java, which is equivalent to the foundation of thousands of high-rise buildings on the ground. It is also the first stage of building a foundation by practicing Qi. Understanding these contents has only taken the first step in learning Java. Let's cheer together, work hard, Xiao Zeng, and take you to learn java together

Writing is not easy. Welcome to support and pay attention to me to learn Java together!

At present, the main reference book is the Java core volume. At present, I am also reading it, so I record some basic contents that I think are important.
For some reference videos, I mainly read the basic article of crazy God talking about java in station B. It is easy to understand and worth recommending!
https://space.bilibili.com/95256449? , interested students can go to station B to have a look

Topics: Java Algorithm