10 > 20 && 10 / 0 == 0 is equal to connecting small light bulbs in series?---JAVA operator

Series Article Directory

Do you really know how to knock out Hello World with java? —Do you know why data types are divided when you first know JAVA ? ——JAVA data types and variables



foreword

In the previous article, we learned about variables in JAVA, variables and operators form expression statements, and expressions can be used in the logic control of our programs.


1. What is an operator?

One of the most basic uses of a computer is to perform mathematical operations such as:

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

The above + and < are operators, that is, symbols when operating on operands. Different operators have different meanings.
As a computer language, Java also provides a rich set of operators to manipulate variables. Operators in Java can be divided into the following: arithmetic operators (+ - */), relational operators (< > ==), logical operators, bit operators, shift operators, and conditional operators.

1.1 Arithmetic operators

Basic four operators:

1.1.1 Addition, subtraction, multiplication and division (+ - * / %)

  • Addition, subtraction, multiplication and division (+ - * / %) are all binary operators, and there must be two left and right operands when used, as follows:
int a = 20;
int b = 10;
System.out.println(a + b); // 30
System.out.println(a - b); // 10
System.out.println(a * b); // 200
System.out.println(a / b); // 2
System.out.println(a % b); // 0 --->模运算相当于数学中除法的余数

  • int / int The result is still of int type, and it will be rounded down, and all after the decimal point will be discarded. As shown in the rectangle in the figure below.
    If you want to get the result in mathematics, you can use the following method:
int a = 10;
int b = 3;
double d = a*1.0 / b;
System.out.println(d);
  • It is indeed different from the C language that the operands on both sides of the % operator in C language must never appear floating point numbers. In JAVA, the operands on both sides of the % operator can have floating point numbers, % operator The two sides can be of different types . So % can not only take the modulus of the integer type, but also take the modulus of the double type. But it doesn’t make sense, it’s generally modulo integers. As shown in the circle in the figure below.
    / and % often error-prone operations
    It’s meaningless to modulo double types
    Take the modulo of the double type, but it doesn't make sense
  • When doing division and modulo, the right operand cannot be 0

When doing division and modulo, the right operand cannot be 0
ArithmeticException: Arithmetic exception

  • When the types of operands on both sides are inconsistent, the type is greatly promoted

1.1.2 Incremental operator += -= *= %=

After the operation of this type of operator is completed, the result of the operation will be assigned to the left operand.

  • Increment/decrement operator ++ –
        int a = 1;
        a += 2; // 相当于 a = a + 2
        System.out.println(a); // 输出3
        a -= 1; // 相当于 a = a - 1
        System.out.println(a); // 输出2
        a *= 3; // 相当于 a = a * 3
        System.out.println(a); // 输出6
        a /= 3; // 相当于 a = a / 3
        System.out.println(a); // 输出2
        a %= 3; // 相当于 a = a % 2
        System.out.println(a); // 输出2

Only variables can use the self-increment/decrement operators, constants cannot be used, because constants are not allowed to be modified

  • += -= *= %= will automatically help us to perform type conversion,
    if the self-increment operator is not used, an error will be reported

auto-increment operator type conversion

1.2.3 Increment/decrement operator ++ –

  • If used alone, there is no difference between [Pre ++] and [Post ++]
    insert image description here
    insert image description here
  • If mixed use, [Pre ++] first + 1, and then use the value after the variable + 1, that is, first + 1 and then use . [Post ++] Use the original value of the variable first, and give the variable + at the end of the expression 1, that is, use it first and then +1 .
    insert image description here

int a = 1;
a++; // 后置++ 表示给a的值加1,此时a的值为2
System.out.println(a++); // 注意:后置++是先使用变量原来值,表示式结束时给变量+1,因此输出2
System.out.println(a); // 输出3             
++a; // 前置++ 表示给a的值加1
System.out.println(++a); // 注意:前置++是先给变量+1,然后使用变量中的值,因此输出5
System.out.println(a); // 输出5
// --操作符给操作-1,与++含义类似
  • Note that it is different from the C language, as shown in the code in the figure below, JAVA has its own processing method: The
    insert image description here
    method and process of taking values ​​and assigning values ​​​​in JAVA are different. Detailed analysis will be given in future chapters, so stay tuned.
  • Only variables can use the self-increment/decrement operators, constants cannot be used, because constants are not allowed to be modified

1.2 Relational operators == != < > <= >=

  • In JAVA, relational operators have results, and the results can only be true or false, that is, boolean type.
int a = 10;
int b = 20;
// 注意:在Java中 = 表示赋值,要与数学中的含义区分
// 在Java中 == 表示相等
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a < b); // true
System.out.println(a > b); // false
System.out.println(a <= b); // true
System.out.println(a >= b); // false
  • When multiple judgments are required, they cannot be written consecutively, for example: 3 < a < 5, there is a difference between Java programs and mathematics

1.3 Logical operators (emphasis)

1.3.1 Logical AND &&

Grammar rules: expression 1 && expression 2, the left and right expressions must be the result of boolean type.
It is equivalent to real life and , for example: if you are a student, you can enjoy half the ticket only if you have a student ID card.
Both expressions are true, the result is true, as long as one of them is false, the result is false. False is false

int a = 1;
int b = 2;
System.out.println(a == 1 && b == 2); // 左为真 且 右为真 则结果为真
System.out.println(a == 1 && b > 100); // 左为真 但 右为假 则结果为假
System.out.println(a > 100 && b == 2); // 左为假 但 右为真 则结果为假
System.out.println(a > 100 && b > 100); // 左为假 且 右为假 则结果为假

1.3. 2 Logic||

Grammar rules: expression 1 || expression 2, the left and right expressions must be the result of boolean type. It is equivalent to or in real life. For example: when buying a house and paying for it, the full payment or the mortgage is acceptable. If the full payment or the mortgage is used, the house is yours, otherwise stand aside.

If at least one of the left and right expressions is true, the result is true. true is true

int a = 1;
int b = 2;
System.out.println(a == 1 || b == 2); // 左为真 且 右为真 则结果为真
System.out.println(a == 1 || b > 100); // 左为真 但 右为假 则结果也为真
System.out.println(a > 100 || b == 2); // 左为假 但 右为真 则结果也为真
System.out.println(a > 100 || b > 100); // 左为假 且 右为假 则结果为假

1.3. 3 Logical NOT !

Grammar rules: ! Expression
True becomes false, false becomes true.

int a = 1;
System.out.println(!(a == 1)); // a == 1 为true,取个非就是false
System.out.println(!(a != 1)); // a != 1 为false,取个非就是true

1.3.4 Short-circuit evaluation

&& and || abide by the rules of short-circuit evaluation:
we can compare the circuit knowledge we learned in junior high school, as shown in the figure below, the statement formed by && and || is equivalent to a small light bulb circuit in series. The light bulb is broken (the first condition of the && statement is false, and the first condition of the || statement is true), no matter whether the small light bulb behind is good or bad (the following statement is true or false), other small light bulbs will not light up ( None of the other statements will be executed).

System.out.println(10 > 20 && 10 / 0 == 0); // 打印 false
System.out.println(10 < 20 || 10 / 0 == 0); // 打印 true

We all know that calculating 10 / 0 will cause the program to throw an exception. But the above code can run normally, indicating that 10 / 0 is not really evaluated. This is because:
for
&&, if the value of the left expression is false , the result of the expression must be false, and the expression on the right side does not need to be calculated if it is false.
For ||, if the value of the expression on the left is true, the result of the expression must be true, and the expression on the right side does not need to be calculated if it is true formula.
& and | also represent logical operations if the result of the expression is boolean. But compared with && ||, they do not support short-circuit evaluation

System.out.println(10 > 20 & 10 / 0 == 0); // 程序抛出异常
System.out.println(10 < 20 | 10 / 0 == 0); // 程序抛出异常

1.4 bitwise operators

The smallest unit of data storage in Java is a byte, and the smallest unit of data manipulation is a bit. A byte is the smallest storage unit, each byte is composed of 8 binary bits, and multiple bytes are combined Can represent a variety of different data.
There are four main bitwise operators: & | ~ ^ , except ~ is a unary operator, the rest are binary operators.
Bit operation means binary bit operation. Computers use binary to represent data (a sequence of 0 or 1), and bitwise operation is to perform calculations according to each bit of the binary bit.

1. 4.1 Bitwise AND &

Bitwise AND &: If both binary bits are 1, the result is 1, otherwise the result is 0. All 1s are 1

int a = 10;
int b = 20;
System.out.println(a & b);

To perform bitwise operations, you need to convert 10 and 20 into binary first, which are 1010 and 10100 respectively

1.4.2 Bitwise OR |

Bitwise OR|: If both binary bits are 0, the result is 0, otherwise the result is 1. All 0s are 0

int a = 10;
int b = 20;
System.out.println(a | b);

The operation method is similar to that by position.
insert image description here

Note: When the operands of & and | are integers (int, short, long, byte), they represent bitwise operations, and when the operands are boolean, they represent logical operations.

1.4.3. Bitwise inversion ~

If the bit is 0, turn it to 1, if the bit is 1, turn it to 0. 1 is 0, 0 is 1

int a = 0xf;
System.out.printf("%x\n", ~a)

Note: The numbers prefixed with
0x are hexadecimal numbers. Hexadecimal can be regarded as a simplified representation of binary. A hexadecimal number corresponds to 4 binary digits. 0xf means 15 in decimal , which is binary The 1111 printf can format the output content, %x means output according to hexadecimal. \n means newline character



1.4.4 Bitwise XOR ^

Bitwise XOR^: If the binary digits of two numbers are the same, the result is 0, and if they are different, the result is 1. The same is 0 and the difference is 1. We
can regard the number as a small ball, and the ball on the left will fall , add 0 to the right. Move the ball on the left to the right and drop it, and the sign on the left.

int a = 0x1;
int b = 0x2;
System.out.printf("%x\n", a ^ b);

Note: If the two numbers are the same, the result of XOR is 0

1.5 shift operation

There are three shift operators: << >> >>> , all of which are binary operators and operate on binary bits.

1.5.1 Shift left <<

Left shift <<: The leftmost bit is not needed, and the rightmost bit is filled with 0.

int a = 0x10;
System.out.printf("%x\n", a << 1);
// 运行结果(注意, 是按十六进制打印的)
20

Note: When shifting to the left, what is discarded is the sign bit , so a left shift of a positive number may program a negative number.

1.5.2 Shift right >>

The rightmost bit is unnecessary, and the leftmost complement sign bit (positive numbers complement 0, negative numbers supplement 1)

int a = 0x10;
System.out.printf("%x\n", a >> 1);
// 运行结果(注意, 是按十六进制打印的)
8 
int b = 0xffff0000;
System.out.printf("%x\n", b >> 1);
// 运行结果(注意, 是按十六进制打印的)
ffff8000

1.5.3 Unsigned right shift >>>

Unsigned right shift is not available in C language. The rightmost bit is not needed, and the leftmost bit is filled with 0 whether it is positive or negative . >>>: The rightmost bit is not needed, and the leftmost bit is filled with 0.

int a = 0xffffffff;
System.out.printf("%x\n", a >>> 1);
// 运行结果(注意, 是按十六进制打印的)
7fffffff

Notice:

  • Left shift 1 bit, equivalent to the original number * 2. Left shift N bits, equivalent to the original number * 2 to the Nth power.
  • Shifting right by 1 bit is equivalent to the original number/2. Shifting right by N bits is equivalent to the original number/2 to the Nth power.
  • Since the calculation efficiency of computer shifting is higher than that of calculating multiplication and division, when a certain code happens to multiply and divide 2 to the Nth power, it can be replaced by a shift operation.
  • It doesn't make sense to shift negative bits or shift too many bits.

1.6 Conditional operators:

There is only one conditional operator: expression 1 ? expression 2 : expression 3

When the value of expression 1 is true, the value of the entire expression is the value of expression 2;
when the value of expression 1 is false, the value of the entire expression is the value of expression 3. It
is also the only one in Java The ternary operator is a simplified way of writing a conditional judgment statement.

// 求两个整数的最大值
int a = 10;
int b = 20;
int max = a > b ? a : b;

Notice:

  • If the results of expression 2 and expression 3 are of the same type, unless implicit type conversion can occur
int a = 10;
int b = 20;
int c = a > b? 1 : 2.0;
  • An expression cannot stand alone, its result must be used. That is, the result of the conditional operator must be assigned to a variable.
int a = 10;
int b = 20;
a > b? a : b; // 报错:Error:(15, 14) java: 不是语句
int c = a > b ? a : b ;//正确

1.7 Operator precedence

In an expression, various operators can be mixed together for operation, but the priority of the operators is different, for example: * and / have higher priority than + and -, in some cases, a little carelessness may cause serious problems Big trouble.
// Find the average of a and b

int a = 10;
int b = 20;
int c = a + (b - a) >> 1;
System.out.println(c);

In the above expression, since the priority of + is higher than that of >>, the result of a is added to the result of ba first, and the overall result is 20, and finally the right shift is performed, so the result is 10.
Note: There is a priority between operators. We don’t have to remember the specific rules. Just add parentheses to the code that may have ambiguity

// 求a和b的平均值
int a = 10;
int b = 20;
int c = a + ((b - a) >> 1);
System.out.println(c);

Guess you like

Origin blog.csdn.net/m0_74387295/article/details/129396100