Basic Java syntax (keywords, reserved words, identifiers, variables, operators, program flow control statements)

2. Basic Java syntax

1. Use of Java keywords

Definition: a string (word) with special meaning given by the Java language for special purposes
Features: all letters in the keyword are lowercase
Specific keywords:

2. Reserved word: the current Java version has not been used, but the later version may be used as a keyword.
Specific reserved words: goto, const
Avoid using these identifiers when naming yourself

3. Use of identifiers
Definition: any place where you can name yourself is called an identifier.
Structure involved:
Package name, class name, interface name, variable name, method name, constant name
Rule: (must be followed. Otherwise, the compilation fails)

Specification: (it can not be complied with, which will not affect the compilation and operation. But it is required to be complied with)

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wproe6iv-1646234208724)( )]

When naming, in order to improve the reading ability, we should try our best to "see the name and know the meaning".

1. Classification of variables
1.1 classification by data type

detailed description:

  1. Integer: byte(1 byte = 8bit) \ short(2 bytes) \ int(4 bytes) \ long(8 bytes)
    ① byte range: - 128 ~ 127
    ② Declare a long variable, which must end with "L" or "L"
    ③ In general, int is used when defining integer variables.
    ④ Integer constant. The default type is int

  2. Floating point type: float(4 bytes) \ double(8 bytes)
    ① Floating point type that represents a numeric value with a decimal point
    ② float indicates that the range of values is larger than long
    ③ When defining a float type variable, the variable should end with "F" or "F"
    ④ When double is used, floating-point variables are usually defined.
    ⑤ Floating point constant. The default type is double

  3. Character type: char (1 character = 2 bytes)
    ① A pair of '' is usually used to define char type variables, and only one character can be written inside
    ② Representation: 1 Declare a character 2 Escape character 3 Use Unicode values directly to represent character constants

  4. boolean: boolean
    ① You can only take one of two values: true and false
    ② It is often used in condition judgment and loop structure

    1.2 classification by declared location (understanding)

2. Define the format of variables

Data type variable name = variable value;
Data type variable name;
Variable name = variable value;

3. Precautions for variable use:
① Variables must be declared before use
② Variables are defined within their scope. It is valid within the scope. In other words, out of scope, it is invalid
③ Two variables with the same name cannot be declared in the same scope
4. Operation rules between basic data type variables
4.1 basic data types involved: 7 types except boolean
4.2 automatic type conversion (involving only 7 basic data types)

Conclusion: when the variables of the data type with small capacity are calculated with the variables of the data type with large capacity, the result will be automatically promoted to the data type with large capacity.
	byte ,char ,short --> int --> long --> float --> double 
	Special: when byte,char,short When three types of variables are operated, the result is int type
 Note: the capacity size at this time refers to the large and small range of numbers. For example: float Capacity should be greater than long Capacity of

4.3 forced type conversion (involving only 7 basic data types): the inverse operation of automatic type promotion operation.

1.Strong conversion is required:()
2.Note: cast may result in loss of precision.

4.4 operation between string and 8 basic data types

  1. 1. String It belongs to the reference data type,String
    2. statement String Type variable, use a pair of""
    3. String It can operate with 8 basic data type variables, and the operation can only be connection operation:+
    4. The result of the operation is still String type
       String s = 123;//Compilation error
       String s1 = "123";
       int i = (int)s1;//Compilation error

    3. Binary conversion

    1. Hexadecimal and representation involved in programming:

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xoavupah-1646234208727)( )]

    2. Instructions for binary system:
    2.1 storage mode at the bottom of the computer: all numbers exist in binary form at the bottom of the computer.
    2.2 storage mode of binary data: all values, whether positive or negative, are stored in the form of complement at the bottom.
    2.3 description of original code, inverse code and complement code:
    Positive number: three in one
    Negative number:

    3. Conversion between hexadecimals:
    3.1 diagram:

    3.2 conversion from binary to decimal:

    3.3 conversion of decimal system to binary system:

    3.4 conversion between binary, octal and hexadecimal:

1. Arithmetic operator: + - + - * /% (front) + + (rear) + + (front) -- (rear) --+
[typical code]

//Division number:/
int num1 = 12;
int num2 = 5;
int result1 = num1 / num2;
// %: remainder operation
//The sign of the result is the same as that of the module
//In development, we often use% to judge whether it can be eliminated.
int m1 = 12;
int n1 = 5;
System.out.println("m1 % n1 = " + m1 % n1);
int m2 = -12;
int n2 = 5;
System.out.println("m2 % n2 = " + m2 % n2);

int m3 = 12;
int n3 = -5;
System.out.println("m3 % n3 = " + m3 % n3);

int m4 = -12;
int n4 = -5;
System.out.println("m4 % n4 = " + m4 % n4);
//(front) + +: increase by 1 first and then calculate
//(later) + +: calculate first and then increase by 1
int a1 = 10;
int b1 = ++a1;
System.out.println("a1 = " + a1 + ",b1 = " + b1);

int a2 = 10;
int b2 = a2++;
System.out.println("a2 = " + a2 + ",b2 = " + b2);

int a3 = 10;
int b3 = a3;
//(front) --: subtract 1 first and then calculate
//(later) --: operation first, then self subtraction 1

int a4 = 10;
int b4 = a4--;//int b4 = --a4;
System.out.println("a4 = " + a4 + ",b4 = " + b4);

[specially specified]

1.(front)++ :Self increment 1 first, then operation
   (after)++ :First operation, then self increment 1
2.(front)-- :Subtract 1 first and then operate
   (after)-- :First operation, then self subtraction 1
3.Connector:+: Can only be used in String Used with other data type variables.

2. Assignment operator: = + = - = * = / =%=
[typical code]

int i2,j2;
//continuous assignment 
i2 = j2 = 10;
int i3 = 10,j3 = 20;
int num1 = 10;
num1 += 2;//num1 = num1 + 2;
int num2 = 12;
num2 %= 5;//num2 = num2 % 5;

short s1 = 10;
//s1 = s1 + 2;// Compilation failed
s1 += 2;//Conclusion: the data type of the variable itself will not be changed

[specially specified]
1. The result of the operation will not change the data type of the variable itself
2. In development, if you want the variable to realize the operation of + 2, how many methods are there? (premise: int num = 10;)

//Method 1: num = num + 2;
//Mode 2: num += 2; (recommended)
//In development, if you want the variable to realize the operation of + 1, how many methods are there? (premise: int num = 10;)
//Method 1: num = num + 1;
//Mode 2: num += 1; 
//Mode 3: num + +; (recommended)

3. Comparison operator (relational operator): = =! = > < > =<= instanceof
[typical code]

int i = 10;
int j = 20;

System.out.println(i == j);//false
System.out.println(i = j);//20

boolean b1 = true;
boolean b2 = false;
System.out.println(b2 == b1);//false
System.out.println(b2 = b1);//true

[specially specified]
1. The result of the comparison operator is boolean
2. > < > = < =: can only be used between numeric data types.

3. = = and! =: It can be used not only between numeric type data, but also between other reference type variables.

Account acct1 = new Account(1000);
Account acct2 = new Account(1000);
boolean b1 = (acct1 == acct2);//Compare whether two accounts are the same Account.
boolean b2 = (acct1 != acct2);//

instanceof is a reserved keyword of Java. On the left is an object, on the right is a class, and the return type is Boolean. Its specific function is to test whether the object on the left is the instance object created by the right class or its subclass. If yes, it returns true, otherwise it returns false.

Precautions for using instanceof
First there is the inheritance relationship, and then the use of instanceof.
When the test object is created, any one of the declaration type on the right and the class on the left must be the same branch of the inheritance tree or have an inheritance relationship with the test class, otherwise the compiler will report an error.
instanceof usage example

public class Application {

  public static void main(String[] args) {
// Object > Person > teacher
// Object > Person > Student
// Object > String
Object o = new Student(); // It mainly depends on the type of this object and the instantiated class name
// instanceof keyword can determine whether the object on the left is an instance of the class or subclass on the right
System.out.println(o instanceof Student); // o is an instance object of student class, so judge whether the class on the right is related to student and whether the display declaration is related
System.out.println(o instanceof Person); // true
System.out.println(o instanceof Object); // true
System.out.println(o instanceof String); // false
System.out.println(o instanceof Teacher); // It doesn't matter
Person person = new Student();
System.out.println(person instanceof Person); // true
System.out.println(person instanceof Object); // true
// System.out.println(person instanceof String); //  Compilation error
System.out.println(person instanceof Teacher); // It doesn't matter

instanceof application scenario
You need to use instanceof to judge when you need to use the forced type conversion of an object.

4. Logical operators: & & ||||^
[typical code]
Distinguish & and&&
Same point 1: & and & & have the same operation result
Same point 2: when the left side of the symbol is true, both will perform the operation on the right side of the symbol
Difference: when the left side of the symbol is false, & continue to perform the operation on the right side of the symbol&& The operation to the right of the symbol is no longer performed.
During development, it is recommended to use&&

boolean b1 = true;
b1 = false;
int num1 = 10;
if(b1 & (num1++ > 0)){
System.out.println("I'm in Beijing now");
System.out.println("I'm in Nanjing now");
System.out.println("num1 = " + num1);

	boolean b2 = true;
	b2 = false;
	int num2 = 10;
	if(b2 && (num2++ > 0)){
		System.out.println("I'm in Beijing now");
		System.out.println("I'm in Nanjing now");

	System.out.println("num2 = " + num2);

	// Distinguish from: ||| 
	//Same point 1: the operation results of | and | are the same
	//Same point 2: when the left side of the symbol is false, both will perform the operation on the right side of the symbol
	//Difference 3: when the left side of the symbol is true, | continue to perform the operation on the right side of the symbol, and | no longer perform the operation on the right side of the symbol
	//During development, it is recommended to use||
	boolean b3 = false;
	b3 = true;
	int num3 = 10;
	if(b3 | (num3++ > 0)){
		System.out.println("I'm in Beijing now");
		System.out.println("I'm in Nanjing now");
	System.out.println("num3 = " + num3);

	boolean b4 = false;
	b4 = true;
	int num4 = 10;
	if(b4 || (num4++ > 0)){
		System.out.println("I'm in Beijing now");
		System.out.println("I'm in Nanjing now");
	System.out.println("num4 = " + num4);

[specially specified]
1. All logical operators operate on Boolean variables. And the result is of boolean type

^(XOR operator)

^It is for binary binary objects operator . Operation rule: if two binary values are the same on the same bit, the bit in the result is 0, otherwise it is 1

For example, 1011 ^ 0010 = 1001.

5. Bitwise operators: < > > > & | ^~
[typical code]
int i = 21;
i = -21;
System.out.println("i << 2 :" + (i << 2));
System.out.println("i << 3 :" + (i << 3));
System.out.println("i << 27 :" + (i << 27));

	int m = 12;
	int n = 5;
	System.out.println("m & n :" + (m & n));
	System.out.println("m | n :" + (m | n));
	System.out.println("m ^ n :" + (m ^ n));

[interview question] can you write the most efficient implementation of 2 * 8?
Answer: 2 < < 3 or 8 < < 1
[specially specified]

  1. Bitwise operators operate on integer data
  2. << : Within a certain range, every bit to the left is equivalent to * 2
    >> :Within a certain range, each shift to the right by 1 bit is equivalent to / 2

6. Ternary operator: (conditional expression)? Expression 1: expression 2
[typical code]
1. Get the larger value of two integers
2. Get the maximum value of three numbers
[special instructions]

1. explain
① The result of the conditional expression is boolean type
② Whether to execute expression 1 or expression 2 depends on whether the conditional expression is true or false.
If the expression is true,Expression 1 is executed.
If the expression is false,Expression 2 is executed.
③ Expression 1 and expression 2 are required to be consistent.
④ Ternary operators can be nested
2. Where ternary operators can be used, they can be rewritten as if-else
 On the contrary, it does not hold.
3. If the program can use both ternary operators and if-else Structure, then the ternary operator is preferred. Reason: simplicity and high execution efficiency.
1. If else condition judgment structure


Structure I:
if(Conditional expression){
	Execute expression

Structure 2: choose one from two
if(Conditional expression){
	Execute expression 1
	Execute expression 2

Structure III: n Choose one
if(Conditional expression){
	Execute expression 1
}else if(Conditional expression){
	Execute expression 2
}else if(Conditional expression){
	Execute expression 3
	Execute expression n

1.2. explain:

  1. else structure is optional.
  2. For conditional expressions:

    If multiple conditional expressions are mutually exclusive (or have no intersection), it doesn't matter which judgment and execution statement is declared above or below.
    If there is an intersection relationship between multiple conditional expressions, you need to consider which structure should be declared on it according to the actual situation.
    If there is an inclusive relationship between multiple conditional expressions, it is usually necessary to declare the small range on the large range. Otherwise, those with small scope will have no chance to implement.

  3. If else structures can be nested with each other.
  4. If the execution statement in the if else structure has only one line, the corresponding pair of {} can be omitted. However, it is not recommended to omit.

2. Switch case selection structure

case Constant 1:
	Execute statement 1;
case Constant 2:
	Execute statement 2;
	Execute statement n;

2. Description:
① Match the constants in each case in turn according to the value in the switch expression. Once the match is successful, it enters the corresponding case structure and calls its execution statement.
After the execution statement is called, the execution statements in other case structures will continue to be executed downward until the break keyword or this switch case structure is encountered
At the end.
② break, which can be used in the switch case structure, means that once this keyword is executed, it will jump out of the switch case structure
③ The expression in the switch structure can only be one of the following six data types:
byte, short, char, int, enumeration type (new in JDK5.0), String type (new in JDK7.0)
④ Only constants can be declared after case. Scope cannot be declared.
⑤ The break keyword is optional.
⑥ default: equivalent to else in the if else structure
The default structure is optional and the location is flexible.
3. If the execution statements of multiple cases in the switch case structure are the same, you can consider merging.
4.break is optional in switch case

1. Four elements of circular structure
① Initialization condition
② Loop condition - > is of boolean type
③ Circulatory body
④ Iterative condition
Note: generally, the cycle ends because the cycle condition in ② returns false.

2. Three cycle structures:
2.1 for loop structure


Execution process: ① - ② - ③ - ④ - ② - ③ - ④ -... - ②

2.2 while loop structure


Execution process: ① - ② - ③ - ④ - ② - ③ - ④ -... - ②
When writing a while loop, be careful not to lose the iteration condition. Once lost, it may lead to a dead cycle!

Summary of for and while loops:

  1. During development, we will basically choose from for and while to realize the loop structure.

  2. for loop and while loop can be converted to each other!
    Difference: the scope of the initialization condition part of the for loop and the while loop is different.

  3. We write programs to avoid dead cycles.
    2.3 do while loop structure


Execution process: ① - ③ - ④ - ② - ③ - ④ -... - ②

1. The do while loop will execute the loop body at least once!

2. In development, use for and while more. Less use of do while

3. "Infinite loop" structure: while(true) or for(; 😉
Summary: how to end a loop structure?
Method 1: when the loop condition is false
Method 2: execute break in the loop body

4. Nested loop
1. Nested loop: declaring one loop structure A in the loop body of another loop structure B constitutes A nested loop
Inner circulation: circulation structure A
Outer circulation: circulation structure B
2. Description:
① The inner loop structure is traversed once, which is only equivalent to the execution of the outer loop body once
② Suppose that the outer loop needs to be executed m times and the inner loop needs to be executed n times. At this time, the loop body of the inner loop has been executed m * n times
③ The outer loop controls the number of rows and the inner loop controls the number of columns
[typical exercise]
//Exercise 1:

for(int j = 1;j <= 4;j++ ){
for(int i = 1;i <= 6;i++){

/ / exercise 2:

/*			i((line number) 		 j(*)

*			1			1
**			2			2
***			3			3
****		4			4
*****		5			5
for(int i = 1;i <= 5;i++){//Number of control rows
for(int j = 1;j <= i;j++){//Number of control columns

//Exercise 3: 99 multiplication table
//Exercise 4: prime numbers within 100

Supplement: measure the advantages and disadvantages of a function code:
1. Correctness
2. Readability
3. Robustness
4. High efficiency and low storage: time complexity and space complexity (measure the quality of the algorithm)

Exercise on how to understand process control:
Use of process control structure + algorithm logic

break and continue Use of keywords
			Scope of use		Role of recycling(difference)		  Same point
break:		switch-case			
			In cyclic structure	   End current cycle					You cannot declare an execution statement after a keyword	

continue:	In cyclic structure	   End the current cycle					You cannot declare an execution statement after a keyword

Supplement: labeled break and continue Use of

return In the method.

How to get different types of variables from the keyboard: you need to use the Scanner class

Specific implementation steps:
1.Guide Package: import Java util. Scanner;
2.Scanner Instantiation of: Scanner scan = new Scanner(;
3.Call the relevant methods of the Scanner class (next() / nextXxx()) to get the variables of the specified type

be careful:
You need to enter the value of the specified type according to the corresponding method. If the input data type does not match the required type, an exception will be reported: InputMisMatchException
 Cause the program to terminate.
//1. Guide Package: import Java util. Scanner;
import java.util.Scanner;

class ScannerTest{
	public static void main(String[] args){
		//2. Instantiation of scanner
		Scanner scan = new Scanner(;
		//3. Call relevant methods of Scanner class
		System.out.println("Please enter your name:");
		String name =;

		System.out.println("Please enter your age:");
		int age = scan.nextInt();

		System.out.println("Please enter your weight:");
		double weight = scan.nextDouble();

		System.out.println("Do you like me?(true/false)");
		boolean isLove = scan.nextBoolean();

		//For the acquisition of char type, Scanner does not provide relevant methods. Only one string can be obtained
		System.out.println("Please enter your gender:(male/female)");
		String gender =;//"Male"
		char genderChar = gender.charAt(0);//Gets the character at position with index 0

Keywords: Java

Added by Gambler on Wed, 02 Mar 2022 17:35:13 +0200