day02 - Java basic syntax

day02 - Java basic syntax

0. Type conversion problem

Type conversion (understanding)

In Java, there will be different types of data that need to participate in the operation together, so these data types need to be converted to each other. There are two cases: automatic type conversion and forced type conversion.

Automatic type conversion

*Variables with small type range can be directly assigned to variables with large type range * *.

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 the type of 10 to double directly
System.out.println(num); // Output 10.0

byte a = 12 ;
int b = a;
System.out.println(b); // 12

Automatic type conversion of expressions

In the expression, the variable of small range type will be automatically converted to the current large range type for re operation.

matters needing attention:

The end result type of an expression is determined by the highest type in the expression.

In the expression, byte, short and char are directly converted into int types to participate in the operation.

Cast type

Data or variables with a large type range cannot be directly assigned to variables with a small type range, and an error will be reported. Assigning a value or variable with a large data range to another variable with a small data range must be forced type conversion.

Forced type conversion 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)

explain:

  1. The conversion of char type data to int type is calculated according to the corresponding int value in the code table. For example, in the ASCII code table, 'a' corresponds to 97.
int a = 'a';
System.out.println(a); // Output 97
  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);
  1. boolean type cannot be converted to other basic data types.

1. Operator

1.1 arithmetic operators (understanding)

1.1.1 operators and expressions

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.

1.1.2 arithmetic operators

Symboleffectexplain
+plusSee grade one of primary school
-reduceSee grade one of primary school
*rideSee grade two, and“ ×” identical
/exceptSame as "grade 2" in primary school
%SurplusWhat is obtained is the remainder of the division of two data

be careful:

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

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

1.1.3 "+" operation of characters

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

tips: because of the above reasons, we rarely use byte or short type to define integers in program development. Char type is rarely used to define characters, and string type is used, and char type is not used for arithmetic operation.

1.1.4 "+" operation of string

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: dark horse in 199
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

1.2 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.

Symboleffectexplain
=assignmenta=10, assign 10 to variable a
+=Assignment after additiona+=b, give the value of a+b to a
-=Assignment after subtractiona-=b, give the value of a-b to a
*=Assignment after multiplicationa*=b, set a × The value of b is given to a
/=Assignment after divisiona/=b, give the quotient of a ÷ b to a
%=Assignment after remaindera%=b, 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);

1.3 self increasing and self decreasing operators (understanding)

Symboleffectexplain
++Self increasingAdd 1 to the value of the variable
Self subtractionThe value of the variable minus 1

matters needing attention:

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

When used alone, + + and -- whether placed before or after variables, 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 as + + or –.

When participating in the operation, if it is placed in front of the variable, take the variable as + + or –, and then take the variable to 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!

1.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.

Symbolexplain
==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 whether a is greater than b, true or false
>=a> = b, judge whether a is greater than or equal to b, true or false
<If a < b, judge whether a is less than b. if true, it is 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, either true or false.

Never mistakenly write "" as "=", "is the relationship to judge whether it is equal," = "is the 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

1.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.

Symboleffectexplain
&Logic andA & b, a and b are true, and the result is true, otherwise it is false
|Logical ora|b, a and B are false, and the result is false, otherwise it is true
^Logical XORa^b, the results of a and b are different and true, and the same 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

Short circuit logic operator

Symboleffectexplain
&&Short circuit andThe function is the same as & but it has short circuit effect
||Short circuit orThe function is the same as | but it 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

1.6 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

Ternary operator case:

1. Demand: there are two tigers in the zoo. It is known that the two tigers weigh 180kg and 200kg respectively. Please use the program to judge whether the two tigers weigh the same.

public class OperatorTest01 {
	public static void main(String[] args) {
		//1: Two variables are defined to save the weight of the tiger, in kg. Here, only the value can be reflected.
		int weight1 = 180;
		int weight2 = 200;	
		//2: Use the ternary operator to judge the weight of the tiger. If the weight is the same, return true; otherwise, return false.
		boolean b = weight1 == weight2 ? true : false;	
		//3: Output results
		System.out.println("b:" + b);
	}
}

2. Demand: there are three monks living in a temple. Their heights are known to be 150cm, 210cm and 165cm respectively. 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);
	}
}

2. Data input (application)

We can get the user's input through the Scanner class. The steps are as follows:

1. Guide bag. Scanner class in Java Util package, so you need to import this class. The statement of package guide needs to be defined on the top of the class.

import java.util.Scanner; 

2. Create a Scanner object.

Scanner sc = new Scanner(System.in);// Create a Scanner object, sc represents the variable name, and others are immutable

3. Receive data

int i = sc.nextInt(); // Indicates that the value entered by the keyboard is returned as an int number.

Example:

import java.util.Scanner;
public class ScannerDemo {
	public static void main(String[] args) {
		//create object
		Scanner sc = new Scanner(System.in);
		//receive data 
		int x = sc.nextInt();
		//output data
		System.out.println("x:" + x);
	}
}

Rewrite the three monk cases and enter the data with the keyboard.

import java.util.Scanner;
public class ScannerTest {
	public static void main(String[] args) {
		//The height is unknown, which is realized by keyboard entry. First import the package, and then create the object.
		Scanner sc = new Scanner(System.in);
		//Enter three heights on the keyboard and assign them to three variables respectively.
		System.out.println("Please enter the height of the first monk:");
		int height1 = sc.nextInt();
		System.out.println("Please enter the height of the second monk:");
		int height2 = sc.nextInt();
		System.out.println("Please enter the height of the third monk:");
		int height3 = sc.nextInt();
		//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;
		//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;
		//Output results.
		System.out.println("The tallest of the three monks is:" + maxHeight +"cm");
	}
}
import java.util.Scanner;
public class IfTest02 {
	public static void main(String[] args) {
		//Xiao Ming's test score is unknown. You can use the keyboard to get the value
		Scanner sc = new Scanner(System.in);	
		System.out.println("Please enter a score:");
		int score = sc.nextInt();
		//Because there are many kinds of rewards, they belong to a variety of judgments. If else... If format implementation
		//Set the corresponding conditions for each judgment
		//Set corresponding rewards for each judgment	
		//Data test: correct data, boundary data, wrong data
		if(score>100 || score<0) {
			System.out.println("The score you entered is incorrect");
		} else if(score>=95 && score<=100) {
			System.out.println("One mountain bike");
		} else if(score>=90 && score<=94) {
			System.out.println("Play in the playground once");
		} else if(score>=80 && score<=89) {
			System.out.println("A transformer toy");
		} else {
			System.out.println("Fat beat");
		}
	}
}
em.in);	
		System.out.println("Please enter a score:");
		int score = sc.nextInt();
		//Because there are many kinds of rewards, they belong to a variety of judgments. If else... If format implementation
		//Set the corresponding conditions for each judgment
		//Set corresponding rewards for each judgment	
		//Data test: correct data, boundary data, wrong data
		if(score>100 || score<0) {
			System.out.println("The score you entered is incorrect");
		} else if(score>=95 && score<=100) {
			System.out.println("One mountain bike");
		} else if(score>=90 && score<=94) {
			System.out.println("Play in the playground once");
		} else if(score>=80 && score<=89) {
			System.out.println("A transformer toy");
		} else {
			System.out.println("Fat beat");
		}
	}
}

Keywords: Java Back-end

Added by kman on Fri, 18 Feb 2022 23:07:52 +0200