[Twelve days to learn java] day03java basic grammar

1. Operators and expressions

operator:

It is a symbol that operates on constants or variables.

For example: + - * /

expression:

An expression that uses operators to connect constants or variables and conforms to the Java syntax is an expression.

For example: the whole of a + b is an expression.

And + is a kind of arithmetic operator, so this expression is also called arithmetic expression.

2. Arithmetic operators

Classification:

+ - * / %

Computing features:

+ - * :跟小学数学中一模一样没有任何区别.
/:
1.整数相除结果只能得到整除,如果结果想要是小数,必须要有小数参数。
2.小数直接参与运算,得到的结果有可能是不精确的。
案例:
System.out.println( 10 / 3);//3
System.out.println(10.0 / 3);//3.3333333333333335
%:取模、取余。
   他做的也是除法运算,只不过获取的是余数而已。
案例:
System.out.println(10 % 2);//0
System.out.println(10 % 3);//1
应用场景:
//可以利用取模来判断一个数是奇数还是偶数
System.out.println(15 % 2);//1  奇数

Exercise: Numeric Splitting

Requirement: Enter a three-digit number with the keyboard, split it into ones, tens, and hundreds, and print it on the console

Code example:

//1.键盘录入一个三位数
//导包 --- 创建对象 --- 接收数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个三位数");
int number = sc.nextInt();//123

//2.获取这个三位数的个位、十位、百位并打印出来
//公式:
//针对于任意的一个数而言
//个位: 数字 % 10
int ones = number % 10;
//十位: 数字 / 10 % 10
int tens = number / 10 % 10;
//百位: 数字 / 100 % 10
int hundreds = number / 100  % 10;

//输出结果
System.out.println(ones);
System.out.println(tens);
System.out.println(hundreds);

official:

Get every digit of any number.

Units: number % 10

Tens place: number / 10 % 10

Hundreds place: number / 100 % 10

Thousands: number / 1000 % 10

. . . and so on. . .

3. Implicit conversion

concept:

Also known as automatic type promotion.

It is to assign a data or variable with a small value range to another variable with a large value range. At this time, we do not need to write additional code to implement it separately, and the program will automatically complete it for us.

Simple memory:

That is, the small ones can be given to the big ones directly.

Two promotion rules:

  • The value range is small, and the value range is large. The small value will be promoted to the large value first, and then the operation will be performed.
  • The three types of data, byte, short, and char, will be directly promoted to int before the operation is performed.

The relationship between the value range from small to large:

byte short int long float double

4. Exercises for implicit conversions

Please see if there is any error in the following case, if there is a problem, please state the reason, if there is no problem, please state the operation process and result

Case number one:

double d = 10;
System.out.println(d);//10.0

explain:

10 is an integer, and the integer is of type int by default.

And in the order of value range: byte short int long float double

When assigning a value, an int type is assigned to a double type. Assigning a small one to a big one is straightforward.

Case two:

byte b = 100;
int i = b;//可以成功赋值

explain:

Because the value range of byte is small, and the value range of int is large, implicit conversion is performed at the bottom layer, so we don’t need to write additional code to implement it separately, and can directly assign values.

Case three:

int i = 10;
long n = 20L;
??? result = i + n;
问变量result是什么类型的?

explain:

The variable i is of type int and the variable n is of type long.

And in the order of value range: byte short int long float double

The value in the variable i will be automatically upgraded to the long type, and the final result is actually the addition of two longs, so the final result is of the long type.

Case 4:

int i = 10;
long n = 100L;
double d = 20.0;
??? result = i + n + d;
问变量result是什么类型的?

explain:

The variable i is of type int, the variable n is of type long, and the variable d is of type double.

And in the order of value range: byte short int long float double

Therefore, when the values ​​in variable i and variable n participate in the operation, their types will be promoted and become double.

In the end, it is actually the addition of three doubles, and the final result is of type double.

Case five:

byte b1 = 10;
byte b2 = 20;
??? result = b1 + b2;//int
问变量result是什么类型的?

explain:

Because both b1 and b2 are of byte type. Therefore, when participating in the calculation, the values ​​in the variable b1 and the variable b2 will be automatically promoted to int type. In the end, it is actually the addition of two int types, and the final result is also of type int.

Case six:

byte b = 10;
short s = 20;
long n = 100L;
??? result = b + s + n;
问变量result是什么类型的?long

explain:

The variable b is of byte type, the variable s is of short type, and the variable n is of long type.

When variables of byte, short, and char types participate in operations, the value in the variable will be directly promoted to int first.

Step 1: The values ​​in variable b and variable s will be promoted to int to participate in the operation.

int + int + long

Step 2: The value range of the long type is greater than the value range of the int.

So the values ​​in variable b and variable s will be promoted to long again.

long + long + long。

So the final result is of type long.

5. Mandatory conversion

concept:

If you want to assign a data or variable with a large value range to another variable with a small value range. It is not allowed to operate directly.

If you must do this, you need to add mandatory conversion.

Writing format:

Target data type variable name = (target data type) the data to be forced;

Simple understanding:

To convert to any type, just write the type in parentheses.

case:

public class OperatorDemo2 {
    public static void main(String[] args) {
        double a = 12.3;
        int b = (int) a;
        System.out.println(b);//12
    }
}

important point:

Coercion may result in incorrect data. (the precision of the data is lost)

6. String + operation

Core skills:

  • When a string appears in the + operation, it is the connector of the string at this time, and the data before and after will be spliced ​​and a new string will be generated.
  • When the + operation is performed continuously, it is executed one by one from left to right.

7. Exercises for adding strings:

Case 1:

1 + "abc" + 1

Result: "1abc1"

explain:

Step 1: 1 + "abc". In this process, strings are involved, so the splicing operation is done to generate a new string "1abc"

Step 2: "1abc" + 1. In this process, strings are involved, so what is done is also a splicing operation to generate a new string "1abc1"

Case 2:

1 + 2 + "abc" + 2 + 1

Result: "3abc21"

explain:

The first step: 1 + 2. In this process, no string is involved, so the addition operation is done, and the result is 3.

Step 2: 3 + "abc". In this process, strings are involved, so what is done is the splicing operation to generate a new string "3abc".

The third step: "3abc" + 2. In this process, strings are involved, so the splicing operation is done to generate a new string "3abc2".

Step 4: "3abc2" + 1. In this process, strings are involved, so the splicing operation is done to generate a new string "3abc21"

Case 3:

String name = "黑默丁格";
System.out.println("我的名字是" + name);

Result: My name is Heimerdinger

Explanation: When a string is added to a variable, it is actually concatenated with the value in the variable.

8. Character + operation

rule:

When a character appears in the + operation, it will take the character to the computer's built-in ASCII code table to look up the corresponding number, and then calculate.

case:

char c = 'a';
int result = c + 0;
System.out.println(result);//97

In the ASCII code table:

‘a’   -----    97

‘A’   -----    65

9. Summary of Arithmetic Operators

Classification:

+ - * / %  这些操作跟小学数学几乎是一模一样的。

important point:

  • The difference between / and %: Both of them do division operations, and / takes the quotient of the result. % Takes the remainder of the result.
  • Integer operations can only get integers. If you want to get decimals, you must have floating-point numbers to participate in the operation.

Advanced usage of arithmetic operators:

The explanation is based on + as an example, and the operation rules of other subtraction, multiplication, and division are also the same.

Special case: String only has + operation, no other operations.

10. Increment and decrement operators

Classification:

++  自增运算符
--  自减运算符

++: It is to add 1 to the value in the variable

–: It is to put the value in the variable -1

How to use:

  • Put it in front of the variable, we call it first ++. For example: ++a
  • Put it after the variable, we call it after ++. For example: a++

important point:

Whether it is ++ first or ++ later. When written on a single line, the result of the operation is exactly the same.

case:

//++
int a = 10;
a++;//就是让变量a里面的值 + 1
System.out.println(a);//11
++a;//就是让变量a里面的值 + 1
System.out.println(a);//12

Application scenarios of self-increment and self-decrement operators:

In some cases, variables need to be added or subtracted by 1.

For example, if the birthday is one year older, the auto-increment operator is used.

For example: In a shopping mall, selecting the quantity of goods also uses auto-increment or auto-decrement operators.

For example: to count a lot of data, how many data meet the requirements, and the self-increment operator is also used.

11. Assignment operator

Most commonly used: =

Operation process: assign the result on the right side of the equal sign to the variable on the left

case:

public class OperatorDemo6 {
    public static void main(String[] args) {
        //1.最为简单的赋值运算符用法
        int a = 10;//就是把10赋值给变量a
        System.out.println(a);

        //2.如果等号右边需要进行计算。
        int b = 20;
        int c = a + b;//先计算等号右边的,把计算的结果赋值给左边的变量
        System.out.println(c);

        //3.特殊的用法
        a = a + 10;//先计算等号右边的,把计算的结果赋值给左边的变量
        System.out.println(a);//20
    }
}

12. Spread assignment operator

Classification:

+=、-=、*=、/=、%=

Operation rules:

It is to calculate the left side and the right side, assign the final result to the left side, and have no effect on the right side.

case:

public class OperatorDemo7 {
    public static void main(String[] args) {
        //扩展赋值运算符
        int a = 10;
        int b = 20;
        a += b;//把左边和右边相加,再把最终的结果赋值给左边,对右边没有任何影响
        // 相当于 a = a + b;
        System.out.println(a);//30
        System.out.println(b);//20
    }
}

important point:

The hidden layer in the extended assignment operator also includes a cast.

Take += as an example.

a += b ; actually equivalent to a = (byte)(a + b);

public class OperatorDemo8 {
    public static void main(String[] args) {
        byte a = 10;
        byte b = 20;
        //a += b;
        a = (byte)(a + b);
        System.out.println(a);//30
    }
}

13. Relational Operators

It is also called a comparison operator. In fact, it just judges with the left and right.

Classification:

symbol explain
== It is to judge whether the left side is equal to the right side, if it is true, it is true, if it is not true, it is false
!= It is to judge whether the left side is not equal to the right side, if it is true, it is true, if it is not true, it is false
> It is to judge whether the left side is greater than the right side, if it is true, it is true, if it is not true, it is false
>= It is to judge whether the left side is greater than or equal to the right side, if it is true, it is true, if it is not true, it is false
< It is to judge whether the left side is smaller than the right side, if it is true, it is true, if it is not true, it is false
<= It is to judge whether the left side is less than or equal to the right side, if it is true, it is true, if it is not true, it is false

important point:

  • The final result of a relational operator must be of Boolean type. either true or false
  • When writing ==, never write =

14. Logical operators

Use of & and |:

&: logical AND (and)

Both sides are true, the result is true, as long as one of them is false, then the result is false.

|: logical or (or)

Both sides are false, the result is false, as long as one of them is true, then the result is true.

Code example:

// &  //两边都是真,结果才是真。
System.out.println(true & true);//true
System.out.println(false & false);//false
System.out.println(true & false);//false
System.out.println(false & true);//false

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

// | 或  //两边都是假,结果才是假,如果有一个为真,那么结果就是真。
System.out.println(true | true);//true
System.out.println(false | false);//false
System.out.println(true | false);//true
System.out.println(false | true);//true

scenes to be used:

According to the fixed scene, choose to use & or use |

  • User login.
    The user name is entered correctly & the password is entered correctly
    because only the user name and password are correct at the same time, then the login can be successful, as long as one of them fails.
    Tips for use:
    When we need to satisfy both the left and right conditions at the same time, we can use and
  • Mother-in-law chooses son-in
    -law Mother-in-law: Son-in-law, you can either buy a house or a car. Then I can wear my little padded jacket.
    Buying a house | Buying a car
    Out of the two conditions, as long as one of them is met, you can wear a padded jacket.
    Tips:
    When only one of the two conditions is met, you can use or

^ (XOR) usage:

It won't be used much in the future, just take a look.

Calculation rules: if both sides are the same, the result is false, if the two sides are different, the result is true

Code example:

//^   //左右不相同,结果才是true,左右相同结果就是false
System.out.println(true ^ true);//false
System.out.println(false ^ false);//false
System.out.println(true ^ false);//true
System.out.println(false ^ true);//true

! (Negative) use:

Yes negation, also known as negation.

Calculation rules: false negation is true, true negation is false

Reminder: only one can be used for negation.

Code example:

System.out.println(!false);//true
System.out.println(!true);//false

System.out.println(!!false);//注意点:取反最多只用一个。

15. Short-circuiting logical operators

Category: && ||

&&:

The operation result is exactly the same as &, except that it has a short-circuit effect.

||:

The operation result is exactly the same as |. It's just a short circuit.

Logic core:

When the left side cannot determine the result of the entire expression, the right side will be executed.

When the left side can determine the result of the entire expression, the right side will not be executed. Thereby improving the operating efficiency of the code.

Example:

  • User login case
    Username is correct & password is correct
    If an & is used, the password will be verified regardless of whether the username is correct or not.

think:

If the user name is entered correctly, it is in line with business logic for us to judge whether the password is correct.

But if the user name is entered incorrectly, is it necessary to compare the password now? No more.

If a & is used, the left and right will be executed regardless of the circumstances.

Username is correct && password is correct

If the user name is entered correctly, then it will be verified whether the password is entered correctly.

If the user name is entered incorrectly, then there is no need to verify whether the password is correct, and the final result is directly false. Thereby improving the efficiency of program operation.

  • Mother-in-law chooses son- in-
    law Have a house | Have a car
    First check if there is a house, and if you find it, then go to see if there is a car.

think:

Since there are houses, why go to see the car? unnecessary.

Have a house|| have a car

First of all, check if there is a room, if there is, then the right side will not be executed. The final result is directly true.

If there is no house, you will check to see if there is a car on the right.

Summarize:

The results of && and &, || and | are exactly the same.

But short-circuiting logical operators can improve the running efficiency of the program.

suggestion:

Most commonly used: && || !

16. Ternary operator

Also known as: ternary expression or question mark colon expression.

Format:

relational expression? expression1: expression2;

Calculation Rules:

  • Computes the value of a relational expression.
  • If the relational expression evaluates to true, then expression1 is executed.
  • If the relational expression evaluates to false, expression 2 is executed.

important point:

The final result of the ternary operator must be used, either assigned to a variable or printed directly.

case:

public class OperatorDemo12 {
    public static void main(String[] args) {
        //需求:求两个数的较大值
        int a = 10;
        int b = 20;

        //格式:关系表达式 ? 表达式1 : 表达式2 ;
        //注意点:
        //三元运算符的最终结果一定要被使用。
        //要么赋值给一个变量,要么直接输出。
       int max =  a > b ? a : b ;
        System.out.println(max);


        System.out.println(a > b ? a : b);
    }
}

17. Exercise 1 - Two Tigers

need:

There are two tigers in the zoo, and the weights of the two tigers are obtained through keyboard input,

Please use the program to determine whether the weight of two tigers is the same.

Code example:

//1.获取两只老虎的体重
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一只老虎的体重");
int weight1 = sc.nextInt();
System.out.println("请输入第二只老虎的体重");
int weight2 = sc.nextInt();

//2.利用三元运算符求出最终结果
String result = weight1 == weight2 ? "相同" : "不相同";
System.out.println(result);

18. Exercise 2 - find the maximum value of three numbers

need:

There are three monks living in a temple, and their heights are known to be 150cm, 210cm, and 165cm respectively.

Please use the program to obtain the highest height of the three monks.

Code example:

//1.定义三个变量记录和尚的身高
int height1 = 150;
int height2 = 210;
int height3 = 165;

//2.利用三元运算符求出两个数中的较大值。
int temp = height1 > height2 ? height1 : height2;

//3.求出最终的结果
int max = temp > height3 ? temp : height3;

System.out.println(max);

19. Operator precedence

There are many operators involved in Java, and each operator has its own priority. But these priorities require no memory.

We just need to know one thing:

Parentheses take precedence over all.

Guess you like

Origin blog.csdn.net/weixin_60257072/article/details/129665361