[Java SE] Detailed explanation of operators

This article is about understanding the various operators in Java SE and becoming proficient in them;

Table of contents

1. What is an operator?

2. Arithmetic operators 

2.1 Basic four arithmetic operators

 2.2 Increment operator 

 2.3. Increment/decrement operators

3. Relational operators

4. Logical operators (emphasis) 

 4.1. Logical AND &&

 4.2 Logical OR ||

3. Logical negation!

 5. Bit operators

 5.1 Bitwise AND &:

5.2. Bitwise OR |: 

 5.3 Bitwise negation ~:

5.4 Bitwise XOR ^:

6. Shift operation (understand)

 1. Move left <<

2. Move right >> 

3. Unsigned right shift >>>

7. Conditional operator 

8. Operator precedence 

Summarize:  



1. What is an operator?

One of the most basic uses of computers 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 used to operate 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, etc. 


2. Arithmetic operators 

2.1 Basic four arithmetic operators

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

    public static void main(String[] args) {
        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 --->模运算相当于数学中除法的余数
    }

 Notice:

int / int The result is still of type int and will be rounded down:

They are all binary operators, and they must have two operands on the left and right when using them.

int a = 3;
int b = 2;
// It should be 1.5 in mathematics but the output result is 1 in Java. Round down, that is, all decimal points are discarded
System.out.println(a / b); // 1
// If you want to get mathematics For the result in , you can use the following method
double d = a*1.0 / b;
System.out.println(d)

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

int a = 1;
int b = 0;
System.out.println(a / b)
// 运行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Test.main(Test.java:5) 

% can not only take the modulo of the integer type, but also the double type, but it is meaningless. Generally, it takes the modulo of the integer type:

System.out.println(11.5 % 2.0);
// Operation result
1.5 

Note: In C language, the left and right sides of % must be integers.

 When the operand types on both sides are inconsistent, promote to the larger type:

System.out.println(1+0.2); // The left side of + is int and the right side is double. Int is promoted to double

// Therefore: output 1.2 


 2.2 Increment operator 

  +=  -=  *=  %= 

Note: This operator can only be used with variables, not constants.​ 


 2.3. Increment/decrement operators

  ++  --

++ is to add +1 to the value of the variable, and -- is to be -1 to the value of the variable.​ 

If used alone, there is no difference between [prefix++] and [post++]:

If used in combination, [prefix ++] first +1, and then use the value after the variable +1, [postfix ++] first use the original value of the variable, and +1 the variable at the end of the expression:

Note: Only variables can use the increment/decrement operator, constants cannot be used because constants are not allowed to be modified.


3. Relational operators

There are six main relational operators: == != < > <= >= , the calculation result is true or false .

Note: When multiple judgments are required, they cannot be written consecutively, such as: 3 < a < 5. There is a difference between Java programs and mathematics. 

改法:a >3 && a  < 5


4. Logical operators (emphasis) 

There are three main logical operators: &&  ||  ! , the operation results are all of boolean type. 

 4.1. Logical AND &&

Grammar rules:Expression 1 && Expression 2, the left and right expressions must beboolean type result.
It is equivalent to and in real life. For example: if you are a student and you have a student ID card, you can enjoy half ticket.
Both expressions are true, and the result is truefalse, the result is true, as long as one of them is

Note: In addition to a logical AND; there is also a short-circuit AND 

Short-circuit AND: As long as expression 1 is false, expression 2 will not be executed;

int a = 1;
int b = 2;
System.out.println(a == 2 && (b / 0 == 0));

// false
// a == 2 is already false
// Expression 2 b / 0 == 0 will not be executed  
// So no error will be reported


 4.2 Logical OR ||

Grammar rules:Expression 1 || Expression 2, the left and right expressions must be boolean type of result.
It is equivalent to or in real life, for example: when paying for a house, you can pay in full or with a mortgage. If you pay in full or with a mortgage, the house belongs to you, otherwise you stand aside. 

Expression 1 Expression 2 result
real real real
real Fake real
Fake real real
Fake Fake Fake

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

Short-circuit OR: As long as expression 1 is true, expression 2 will not be executed. Similarly, logical AND


3. Logical negation!

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

Note: The first way of writing is wrong, it must be of type boolean 

int a = 1;
System.out.println(!(a == 1)); // a == 1 is true, otherwise it is false
System.out.println(!(a != 1)); // a != 1 is false, whichever is true


 5. Bit operators

The smallest unit of data storage in Java is byte, and the smallest unit of data operation is bit. Byte is the smallest unit of storage, each byte is composed of 8 binary bits, and multiple bytes are combined together Can represent a variety of different data.


There are four main bitwise operators: & | ~ ^ , except ~ which is a unary operator, the rest are binary operators operator.


bit operation means binary bit operation. Computers all use binary to represent data (a sequence composed of 01), by bit The operation is to calculate each bit of the binary digits in sequence. 

 5.1 Bitwise AND &:

If both bits are 1, the result is 1, otherwise the result is 0. 

int a = 10;
int b = 20;
System.out.println(a & b);   // 结果为0

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

 


5.2. Bitwise OR |: 

If both bits are 0, the result is 0, otherwise the result is 1.

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

Note: When the operand of & and | is an integer (int, short, long, byte), it means bitwise operation, when the operand is boolean , represents a logical operation. 


 5.3 Bitwise negation ~:

If the bit is 0, it turns to 1, if the bit is 1, it turns to 0

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

//Print result is fffff0

Note:
The number prefixed by 0x is a hexadecimal number. Hexadecimal can be regarded as a simplified representation of binary. One hexadecimal number corresponds to 4 Binary bits.
0xf means 15 in decimal, which is 1111 in binary.
printf can format the output content, %x means output in hexadecimal .
\n represents newline character 

5.4 Bitwise XOR ^:

If the binary digits of the two numbers are the same, the result is 0; if they are different, the result is 1.

int a = 10;// 0 0 0 0 1 0 1 0

int b = 20;// 0 0 0 1 0 1 0 0

 a ^ b         //  0 0 0 1 1 1 1 0 //30

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


6. Shift operation (understand)

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

 1. Move left <<

 The leftmost bit is omitted, and the rightmost bit is filled with 0.

int a = 10;
// Shift left 0 0 0 0 1 0 1 0 << 1 10
//       0 0 0 1 0 1 0 0       20
//       0 0 1 0 1 0 0 0       40

 // Shift one digit to the left*2

2. Move right >> 

The rightmost bit is not needed, and the leftmost bit is filled with the sign bit (positive numbers are filled with 0, negative numbers are filled with 1) 

3. Unsigned right shift >>>

 The rightmost bit is omitted and the leftmost bit is filled with 0.

int a = 10;
// unsigned right shift
// Shift left 0 0 0 0 1 0 1 0 >> 1 10
//      0 0 0 0 0 1 0 1         5
//      0 0 0 0 0 0 1 0         2
//      0 0 0 0 0 0 0 1         1

//Shift one number to the right/2

Note:
1. Shift left by 1 bit, which is equivalent to the original number * 2. Shift N bits to the left, which is equivalent to the Nth power of the original number * 2.
2. Shift right by 1 bit, which is equivalent to the original number / 2. Shift right by N bits, which is equivalent to the Nth power of the original number / 2.
3. Because the computer calculates the shift Bit efficiency is higher than calculating multiplication and division. When a certain code exactly multiplies and divides 2 to the Nth power, it can be replaced by a shift operation.
4. It is meaningless to move negative bits or shift the number of bits too large. . (so unsigned right shift is generally used)


7. 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 ternary operator in Java and is a simplified way of writing conditional judgment statements.

 public static void main(String[] args) {
        // 求两个整数的最大值
        int a = 10;
        int b = 20;
        int max = a > b ? a : b;
        System.out.println(max);
 }

 Error demonstration:

1. The results of expression 2 and expression 3 must be of the same type, unless implicit type conversion can occur.

2. The expression cannot exist alone, and the result it produces must be used.

 


8. Operator precedence 

In an expression, various operators can be mixed for operation, but the priorities of operators are different. For example: * and / have higher priority than + and -. In some cases, if you are not careful, it may cause serious problems. Big trouble.

Note: There ispriority between operators. We don’t have to memorize the specific rules. Add the following in code where there may be ambiguities on

BracketsImmediately available.


Summarize:  

In the future, bloggers will gradually update the knowledge of Java SE.

If there are any deficiencies, please feel free to supplement and communicate.

Friends who see this, please support the blogger and have a free three-in-one, thank you!!!

Guess you like

Origin blog.csdn.net/chaodddddd/article/details/134137500