Java basic syntax 2

Java basic syntax

1 type conversion

In Java, some data types can be converted to each other. There are two cases: automatic type conversion and forced type conversion.

1.1 implicit transformation (understanding)

Assign a value or variable representing a small data range to another variable representing a large data range. This conversion mode is automatic and can be written directly. For example:

double num = 10; // Assign 10 of type int directly to type double
System.out.println(num); // Output 10.0

Type from small to large diagram:

explain:

  1. Integers are of type int by default. byte, short and char data will be automatically converted to type int.

    byte b1 = 10;
    byte b2 = 20;
    byte b3 = b1 + b2;
    //The third line of code will report an error, b1 and b2 will be automatically converted to int type, and the calculation result is int. the assignment of int to byte requires forced type conversion.
    //Amend to read:
    int num = b1 + b2;
    //Or:
    byte b3 = (byte) (b1 + b2);

  2. boolean type cannot be converted to other basic data types.

1.2 forced conversion (understanding)

Assign a value or variable representing a large data range to another variable representing a small data range.

Cast format: target data type variable name = (Target data type)Value or variable;

For example:

double num1 = 5.5;
int num2 = (int) num1; // Cast num1 of double type to int type
System.out.println(num2); // Output 5 (decimal places are directly discarded)

1.3 type conversion cases (understanding)

Case code:

byte a = 3;
byte b = 4;
byte c = a + b; //Wrong. Because when two byte variables are added together, they will be promoted to int type first
byte d = 3 + 4; //correct. Constant optimization mechanism

Constant optimization mechanism:

During compilation, the calculation of integer constant will directly calculate the result, and will automatically judge whether the result is in byte Within the value range,

	In: compiled

	Not in: compilation failed
  1. operator

2.1 arithmetic operators

2.1.1 operators and expressions (understand)

Operator: a symbol that operates on a constant or variable

Expression: an expression that connects constants or variables with operators and conforms to java syntax can be called an expression.

                Expressions connected by different operators reflect different types of expressions.

For example:

int a = 10;
int b = 20;
int c = a + b;

+: is an operator and is an arithmetic operator.

a + b: is an expression. Since + is an arithmetic operator, this expression is called an arithmetic expression.

2.1.2 arithmetic operators (application)

Description of symbol function

  • plus   	See grade one of primary school       
    
  • reduce   	See grade one of primary school       
    
  • ride   	See grade two, and“×"identical
    

/Except for the second grade of primary school, it is the same as "÷"
%The remainder is the remainder of the division of two data

be careful:

  1. /The difference between% and%: divide the two data, / take the quotient of the result, and% take the remainder of the result.

  2. Integer operation can only get integers. To get decimal points, floating-point numbers must be involved in the operation.

    int a = 10;
    int b = 3;
    System.out.println(a / b); // Output result 3
    System.out.println(a % b); // Output result 1

2.1.3 "+" operation of characters (understanding)

char type participates in arithmetic operation and uses the decimal value corresponding to the bottom of the computer. We need to remember the values corresponding to the three characters:

'a' – 97 a-z is continuous, so the corresponding value of 'b' is 98 and 'c' is 99, which are added successively

'a' – 65 A-Z are continuous, so the corresponding value of 'B' is 66 and 'C' is 67, which are added successively

'0' – 48 0-9 are continuous, so the corresponding value of '1' is 49 and '2' is 50, which are added successively

// You can use characters and integers to do arithmetic operations to get the value corresponding to characters
char ch1 = 'a';
System.out.println(ch1 + 1); // Output 98, 97 + 1 = 98

char ch2 = 'A';
System.out.println(ch2 + 1); // Output 66, 65 + 1 = 66

char ch3 = '0';
System.out.println(ch3 + 1); // Output 49, 48 + 1 = 49

When an arithmetic expression contains values of different basic data types, the type of the entire arithmetic expression will be automatically promoted.

Promotion rules:

byte type, short type and char type will be promoted to int type, regardless of whether there are other types involved in the operation.

The type of the entire expression is automatically promoted to the same type as the highest level operand in the expression

   Rank order: byte,short,char --> int --> long --> float --> double

For example:

byte b1 = 10;
byte b2 = 20;
// byte b3 = b1 + b2; //  An error is reported in this line, because byte type participates in arithmetic operation and will be automatically prompted as int. assigning int to byte may lose precision
int i3 = b1 + b2; // int reception should be used
byte b3 = (byte) (b1 + b2); // Or cast the result to byte type
-------------------------------
int num1 = 10;
double num2 = 20.0;
double num3 = num1 + num2; // Use double to receive, because num1 will be automatically promoted to double type

2.1.4 "+" operation of string (understanding)

When a string appears in the "+" operation, the "+" is a string connector, not an arithmetic operation.

System.out.println("itheima"+ 666); // Output: itheima666

In the "+" operation, if a string appears, it is a connection operator, otherwise it is an arithmetic operation. When the "+" operation is carried out continuously, it is carried out one by one from left to right.

System.out.println(1 + 99 + "Year dark horse");            // Output: 100 year dark horse
System.out.println(1 + 2 + "itheima" + 3 + 4);   // Output: 3itheima34
// You can use parentheses to change the priority of an operation 
System.out.println(1 + 2 + "itheima" + (3 + 4)); // Output: 3itheima7

2.1.5 numerical splitting (application)

Requirements:

Enter a three digit number on the keyboard, divide it into single digit, ten digit and hundred digit, and print it on the console

Example code:

import java.util.Scanner;
public class Test {
	public static void main(String[] args) {
		// 1: Use the Scanner keyboard to enter a three digit number
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a three digit number");
		int num = sc.nextInt();
		// 2: Calculation of bits: value% 10
		int ge = num % 10;		
		// 3: Ten digit calculation: value / 10% 10
		int shi = num / 10 % 10;	
		// 4: Calculation of hundredth: value / 100
		int bai = num / 100;
		// 5: Splice one, ten and hundred bits into the correct string and print it
		System.out.println("integer"+num+"Bits are:" + ge);
		System.out.println("integer"+num+"Ten for:" + shi);
		System.out.println("integer"+num+"Hundred for:" + bai);
		
	}
}

2.2 self increasing and self decreasing operators (understanding)

Description of symbol function
++Add 1 to the value of the self increasing variable
– the value of the self decreasing variable minus 1

matters needing attention:

++and-- It can be placed either behind the variable or in front of the variable.

When used alone, ++and-- Whether it is placed before or after the variable, the result is the same.

When participating in the operation, if it is placed behind the variable, take the variable to participate in the operation first, and then take the variable to do the operation++perhaps--. 

When participating in the operation, if it is placed in front of the variable, take the variable first++perhaps--,Take the variable and participate in the operation.

The most common usage: use alone.

int i = 10;
i++; // Use alone
System.out.println("i:" + i); // i:11

int j = 10;
++j; // Use alone
System.out.println("j:" + j); // j:11

int x = 10;
int y = x++; // Assignment operation, + + is in the back, so the original value of x is used to assign to y, and x itself increases by 1
System.out.println("x:" + x + ", y:" + y); // x:11,y:10

int m = 10;
int n = ++m; // In the assignment operation, + + is in the front, so the value of m increases automatically is assigned to n, and m itself increases by 1
System.out.println("m:" + m + ", m:" + m); // m:11,m:11

practice:

int x = 10;
int y = x++ + x++ + x++;
System.out.println(y); // What is the value of y?
/*
Parsing, the three expressions are all + + after, so the value before self increment is used every time, but the program is executed from left to right, so 10 is used for calculation in the first self increment, but the value of x has increased to 11 in the second self increment, so 11 is used in the second self increment, and then self increment again...
So the whole formula should be: int y = 10 + 11 + 12;
The output is 33.
*/
Note: through this exercise, we can deeply understand the law of self increase and self decrease, but it is strongly recommended not to write such code in actual development! Be careful of being beaten!

2.3 assignment operator (application)

The assignment operator is used to assign the value of an expression to the left. The left must be modifiable and cannot be a constant.

Description of symbol function
=Assign a=10 and assign 10 to variable a
+=Assign a+=b after addition, and assign the value of a+b to a
-=Assign a-=b after subtraction, and assign the value of a-b to a
=Multiply and assign a=b to a × The value of b is given to a
/=Assign a/=b after division, and give the quotient of a ÷ b to a
%=After taking the remainder, assign a%=b and give the remainder of a ÷ b to a

be careful:

The extended assignment operator implies a cast.

short s = 10;
s = s + 10; // This line of code is reported because s is promoted to int type in the operation, and the assignment of int to short may lose precision

s += 10; // There is no problem with this line of code, which implies forced type conversion, which is equivalent to s = (short) (s + 10);

2.4 relational operators (application)

There are six kinds of relational operators: less than, less than or equal to, greater than, equal to, greater than or equal to, and not equal to.

Symbol description
==a==b, judge whether the values of a and b are equal, true or false
!= a!=b. Judge whether the values of a and B are not equal. If it is true, it is false

a>b,judge a Greater than b,Established as true,Not established as false     

=A > = b, judge whether a is greater than or equal to b, true or false
< a < b, judge whether a is less than b, true or false
< = a < = b, judge whether a is less than or equal to b, true or false

matters needing attention:

The results of relational operators are boolean Type, or true,Either false. 

Never put“=="Miswrite“=","=="Is to judge whether it is equal,"="Is assignment.

int a = 10;
int b = 20;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a >= b); // false
System.out.println(a < b); // true
System.out.println(a <= b); // true

// The result of relational operation must be of boolean type, so the operation result can also be assigned to a variable of boolean type
boolean flag = a > b;
System.out.println(flag); // Output false

2.5 logical operators (application)

Logical operators connect the relational expressions of various operations to form a complex logical expression to judge whether the expression in the program is true or false.

Description of symbol function
&Logic and a & b, a and b are true, and the result is true, otherwise it is false
|Logic or a|b, a and B are false, and the result is false, otherwise it is true
^Logical XOR a^b, different results of a and b are true, and the same result is false
! Logical non! a. The result is opposite to that of A

//Define variables
int i = 10;
int j = 20;
int k = 30;

//&"And", and the result is false as long as one value in the expression is false
System.out.println((i > j) & (i > k)); //False & false, output false
System.out.println((i < j) & (i > k)); //True & false, output false
System.out.println((i > j) & (i < k)); //False & true, output false
System.out.println((i < j) & (i < k)); //True & true, output true
System.out.println("--------");

//|"Or" or relationship. As long as one value in the expression is true, the result is true
System.out.println((i > j) | (i > k)); //false | false, output false
System.out.println((i < j) | (i > k)); //true | false, output true
System.out.println((i > j) | (i < k)); //false | true, output true
System.out.println((i < j) | (i < k)); //true | true, output true
System.out.println("--------");

//^"XOR", the same is false, the different is true
System.out.println((i > j) ^ (i > k)); //false ^ false, output false
System.out.println((i < j) ^ (i > k)); //true ^ false, output true
System.out.println((i > j) ^ (i < k)); //false ^ true, output true
System.out.println((i < j) ^ (i < k)); //true ^ true, output false
System.out.println("--------");

//!  "Non", negative
System.out.println((i > j)); //false
System.out.println(!(i > j)); //! false, output true

2.6 short circuit logic operator (understanding)

Description of symbol function
&&Short circuit has the same function as and & but has short circuit effect
||Short circuit or function is the same as | but has short circuit effect

In logic and operation, as long as the value of one expression is false, the result can be determined as false. It is not necessary to calculate the values of all expressions. Short circuit and operation have such effects, which can improve efficiency. Similarly, in logic or operation, once the value is found to be true, the expression on the right will no longer participate in the operation.

  • Logic and &, whether true or false on the left, must be executed on the right.

  • Short circuit and &, if the left is true, execute on the right; If the left is false, the right is not executed.

  • Logic or |, whether true or false on the left, must be executed on the right.

  • Short circuit or 𞓜 if the left is false, execute on the right; If the left is true, the right is not executed.

    int x = 3;
    int y = 4;
    System. out. println((x++ > 4) & (y++ > 5)); // Both expressions can operate
    System.out.println(x); // 4
    System.out.println(y); // 5

    System. out. println((x++ > 4) && (y++ > 5)); // It can be determined that the result on the left is false, and the right does not participate in the operation
    System.out.println(x); // 4
    System.out.println(y); // 4

2.7 ternary operator (understanding)

Ternary operator syntax format:

Relational expression ? Expression 1 : Expression 2;

Explanation: the position in front of the question mark is the condition of judgment. The judgment result is boolean. When it is true, expression 1 is called, and when it is false, expression 2 is called. The logic is: if the conditional expression is true or satisfied, execute expression 1, otherwise execute the second.

give an example:

int a = 10;
int b = 20;
int c = a > b ? a : b; // Judge whether a > b is true. If true, take the value of a; if false, take the value of B

2.8 ternary operator case (application)

Requirements:

There are three monks living in a temple. They are known to be 150 in height cm,210cm,165cm,Please use the program to obtain the maximum height of the three monks.

public class OperatorTest02 {
	public static void main(String[] args) {
		//1: Three variables are defined to save the monk's height. The unit is cm. Here, only the value can be reflected.
		int height1 = 150;
		int height2 = 210;
		int height3 = 165;	
		//2: Use the ternary operator to obtain the higher height value of the first two monks and save it with a temporary height variable.
		int tempHeight = height1 > height2 ? height1 : height2;		
		//3: Use the ternary operator to obtain the temporary height value and the height higher value of the third monk, and save it with the maximum height variable.
		int maxHeight = tempHeight > height3 ? tempHeight : height3;	
		//4: Output results
		System.out.println("maxHeight:" + maxHeight);
	}
}
  1. Process control statement

In the process of a program execution, the execution order of each statement has a direct impact on the result of the program. Therefore, we must be clear about the execution process of each statement. Moreover, we often need to control the execution order of statements to achieve the functions we want.

3.1 classification of process control statements (understand)

Sequential structure

Branching structure(if, switch)

Cyclic structure(for, while, do...while)

3.2 sequential structure (understanding)

Sequential structure is the simplest and most basic process control in the program. There is no specific syntax structure. It is executed in sequence according to the sequence of codes. Most codes in the program are executed in this way.

Sequential structure execution flow chart:

3.3 if statement of branch structure

3.3.1 if statement format 1 (understanding)

Format:
if (Relational expression) {
    Statement body;	
}

Execution process:

① First, evaluate the value of the relationship expression

② If the value of the relational expression is true, the statement body is executed

③ If the value of the relational expression is false, the statement body is not executed

④ Continue to execute the following statements

Example:

public class IfDemo {
	public static void main(String[] args) {
		System.out.println("start");
        
		// If you are older than 18 years old, you can go to Internet cafes
		int age = 17;
		
		if(age >= 18){
			// int a = 10;
			System.out.println("You can go to Internet cafes");
		}
			
		System.out.println("end");
	}
}

3.3.2 if statement format 2 (understanding)

Format:
if (Relational expression) {
    Statement body 1;	
} else {
    Statement body 2;	
}

Execution process:

① First, evaluate the value of the relationship expression

② If the value of the relational expression is true, the statement body 1 is executed

③ If the value of the relationship expression is false, execute statement body 2

④ Continue to execute the following statements

Example: odd even number

If an integer is given arbitrarily, please use the program to judge whether the integer is odd or even, and output whether the integer is odd or even on the console.

public class Demo2If {
	public static void main(String[] args) {
		// The program determines whether a number is odd or even
		int num = 9;
		
		if(num % 2 == 0){
			System.out.println("even numbers");
		}else{
			System.out.println("Odd number");
		}
	}
}

3.3.3 if statement format 3 (understanding)

Format:
if (Relationship expression 1) {
    Statement body 1;	
} else if (Relational expression 2) {
    Statement body 2;	
} 
...
else {
    Statement body n+1;
}

Execution process:

① First, evaluate the value of relationship expression 1

② If the value is true, execute statement body 1; If the value is false, the value of relationship expression 2 is evaluated

③ If the value is true, execute statement body 2; If the value is false, the value of relationship expression 3 is evaluated

④...

⑤ If no relational expression is true, the statement body n+1 is executed.

Example:

Define one at 0~100 Variables between a, 90~100 Excellent, 80~89 Good, 70~79 Medium, 60~69 Pass, 0~59 Please work hard!

public class Demo3If {
	public static void main(String[] args){
		int score = 65;
		if(score >= 90 && score <= 100){
			System.out.println("excellent");
		}else if (score >= 80 && score <= 89){
			System.out.println("good");
		}else if (score >= 70 && score <= 79){
			System.out.println("secondary");
		}else if (score >= 60 && score <= 69){
			System.out.println("pass");
		}else if (score >= 0 && score <= 59){
			System.out.println("Please try to refuel");
		}else{
			System.out.println("Wrong grades!");
		}
	}
}

3.3.4 if statement format 3 case (application)

Demand: Xiaoming is about to take the final exam. Xiaoming's father told him that he will give him different gifts according to his different test scores. If you can control Xiaoming's score, please use the program to realize what kind of gift Xiaoming should get and output it on the console.

analysis:

①Xiao Ming's test score is unknown. You can use the keyboard to get the value

②Because there are many kinds of rewards, they belong to a variety of judgments, so if...else...if Format implementation

③Set the corresponding conditions for each judgment

④Set corresponding rewards for each judgment

import java.util.Scanner;
public class IfTest02 {
	public static void main(String[] args){
		// 1. Use Scanner to enter test scores
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter your grade:");
		int score = sc.nextInt();
		// 2. Judge whether the score is within the legal range of 0 ~ 100
		if(score >=0 && score <= 100){
			// Legal achievement
			// 3. Judge which award the score range meets in the legal sentence block
			if(score >= 95 && score <= 100){
				System.out.println("One bicycle");
			}else if(score >= 90 && score <= 94){
				System.out.println("Amusement park once");
			}else if(score >= 80 && score <= 89){
				System.out.println("Transformers one");
			}else {
				System.out.println("Get beaten up, There is another sad man in this city~");
			}
		}else{
			// If it is illegal, give an error prompt
			System.out.println("Your score is entered incorrectly!");
		}
	}
}

Not good at learning, thanks for your advice!

Keywords: Python Java Programming Big Data Data Analysis

Added by poison6feet on Tue, 01 Feb 2022 20:53:55 +0200