In the previous content, I have learned how to define and initialize variables. The purpose of defining variables is to manipulate data. The Java language provides us with code symbols specifically used to operate these data, collectively called "operators".
According to the usage of operators, we can divide them into the following categories:
Arithmetic operators
Assignment operator
Self-increase and self-decrease operators
Logical operators
Relational operators
bit operator
Don't worry, they are just symbols that help us process the operation data. The following uses code examples to illustrate the usage of these operators one by one.
1. Arithmetic operators
Arithmetic operators are arithmetic operations for adding, subtracting, multiplying, dividing, and taking remainder of numeric variables:
Add: +
reduce:-
take:*
remove:/
Take balance: %
public class OperatorsDemo { public static void main(String[] args) { int num1 = 100; int num2 = 20; //Add System.out.println("num1 + num2: " + (num1 + num2) ); //Subtract System.out.println("num1 - num2: " + (num1 - num2) ); //Multiply System.out.println("num1 * num2: " + (num1 * num2) ); //Discount System.out.println("num1 / num2: " + (num1 / num2) ); //Get the remaining System.out.println("num1 % num2: " + (num1 % num2) ); }}Output result:
num1 + num2: 120num1 - num2: 80num1 * num2: 2000num1 / num2: 5num1 % num2: 0
2. Assignment operator
Like most programming languages, Java uses the '=' operator to perform assignment operations. This operation assigns the calculation result on the right (called the rvalue) to the variable on the left. The assignment operators in Java include:
= (num2 = num1)
+= (num2 += num1 equivalent num2 = num2 + num1)
-= (num2 -= num1 equivalent num2 = num2 - num1)
*= (num2 *= num1 equivalent num2 = num2 * num1)
/= (num2 /= num1 equivalent num2 = num2 / num1)
%= (num2 %= num1 equivalent num2 = num2 % num1)
public class OperatorsDemo { public static void main(String[] args) { int num1 = 10; int num2 = 20; num2 = num1; System.out.println("= Output: "+num2); num2 += num1; System.out.println("+= Output: "+num2); num2 -= num1; System.out.println("-= Output: "+num2); num2 *= num1; System.out.println("*= Output: "+num2); num2 /= num1; System.out.println("/= Output: "+num2); num2 %= num1; System.out.println("%= Output: "+num2); }}Results output:
= Output: 10+= Output: 20-= Output: 10*= Output: 100/= Output: 10%= Output: 0
3. Self-increase and self-decrease operators
The self-increment and self-decrease operators only operate on one variable, and the value of the variable changes.
num++ (equivalent num = num + 1) increases by itself, mainly for numerical variables, adding 1 to the value of its own variable.
num―(equivalent num = num -1) self-deducting, mainly targeting numeric variables, subtracting the value of the body variable by 1.
public class OperatorsDemo { public static void main(String[] args) { int num1=100; int num2=200; num1++; num2--; System.out.println("num1++ is: "+num1); System.out.println("num2-- is: "+num2); }}Results output:
num1++ is: 101num2-- is: 199
4. Logical operators
Logical operators, as the name suggests, are used for logical judgments. The result of the operation is a value of type boolean, that is, true or false. Logical uniform operators have
| Logical operators | Logical relationships |
|---|---|
| && | and |
| ` | |
| ! | No |
b1 && b2: If both b1 and b2 are true, b1 && b2 will return true, otherwise false
b1 || b2: If both b1 and b2 are false, false will be returned, otherwise true will be returned.
! b1: Will return the value opposite to b1, if b1 is false, return true; if b1 is true, return false
public class OperatorsDemo { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; System.out.println("b1 && b2: " + (b1&&b2)); System.out.println("b1 || b2: " + (b1||b2)); System.out.println("!(b1 && b2): " + !(b1&&b2)); }}Output result:
b1 && b2: falseb1 || b2: true!(b1 && b2): true
Logical short circuit:
In Java, logical operators support short-circuit operations, and once the value of the entire expression can be clearly expressed, we do not need to calculate the rest of the expression. For example, we need to judge that an object is not empty and that the return value of its method is not empty, so we can make a judgment like this:
if (object != null && object.someFunction() != null) { // do something.}If object is empty, the first part expression object != null will return false, then regardless of the result of the expression object.someFunction() != null after the && operator, the final value is false. The compiler will automatically optimize this part of the operation and will not execute object.someFunction() != null.
5. Relational operators
Used to compare the size of two variable data, return the value of boolean, that is, true or false
Relational operators include:
| Relational operators | relation |
|---|---|
| > | Greater than |
| < | Less than |
| == | equal |
| != | Not equal to |
| >= | Greater than or equal to |
| <= | Less than or equal to |
'==' and '!=' are suitable for all types of values and objects (i.e. primitive type variables and reference type variables).
'>', '<', '>=' and '<=' do not apply to values of Boolean types, because they only have true or false, and greater than and less than has no practical significance.
public class OperatorsDemo { public static void main(String[] args) { int num1 = 10; int num2 = 50; if (num1==num2) { System.out.println("num1 and num2 are equal"); } else{ System.out.println("num1 and num2 are not equal"); } if( num1 != num2 ){ System.out.println("num1 and num2 are not equal"); } else{ System.out.println("num1 and num2 are not equal"); } else{ System.out.println("num1 and num2 are not equal"); } equal"); } if( num1 > num2 ){ System.out.println("num1 is greater than num2"); } else{ System.out.println("num1 is not greater than num2"); } if( num1 >= num2 ){ System.out.println("num1 is greater than or equal to num2"); } else{ System.out.println("num1 is less than num2"); } if( num1 < num2 ){ System.out.println("num1 is less than num2"); } if( num1 < num2 ){ System.out.println("num1 is less than num2"); } else{ System.out.println("num1 is not less than num2"); } if( num1 <= num2){ System.out.println("num1 is less than or equal to num2"); } else{ System.out.println("num1 is greater than num2"); } }}Output result:
num1 and num2 are not equalnum1 and num2 are not equalnum1 is not greater than num2num1 is less than num2num1 is less than num2num1 is less than or equal to num2
6. Bit operator
The operation object targeted by the bit operator is binary "bits", which can be applied to integer types (int), long, short, character type (char), and byte type (byte) and other types. During operation, the corresponding Bit bit (0 or 1) will be performed in Boolean algebraic operation or moving operations.
| bit operator | Computational logic |
|---|---|
| & | AND operation: For a certain bit, as long as both operands are 1, the result of the bit is 1, otherwise it is 0. |
| ` | ` |
| ^ | XOR operation: For a certain bit, if the two operands are not the same, the result of the bit is 1, otherwise it is 0. |
| ~ | Non-operation: bitwise complement operator flips each bit of the operand |
| << | Binary left shift operator: the left operand is bit-left shifted by the right operand. |
| >> | Binary right shift operator: the left operand is bit-right shifted by the right operand. |
| >>> | Binary right shift zero-complement operator: The value of the left operand is shifted right according to the number of bits specified by the right operand, and the resulting empty bit is filled with zero |
The description of computational logic is somewhat obscure, and we can use examples to understand more clearly how bit operators perform calculations. Assume that if x is equal to 60; y is equal to 13; their binary representations, and the results of bit operations are as follows:
x = 0011 1100y = 0000 1101-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Note the difference between >> and >>>:
Right shift operator >>, if the value of the operation is positive, 0 is inserted in the high position; if the value is negative, 1 is inserted in the high position;
Move right to fill zero operator >>>, insert 0 at the high position regardless of positive or negative.
> If you don't understand the bit operation, skip it first. When it is actually used, you can study it again.
7. Operator priority
Operator priority determines the grouping of terms in an expression. It affects how an expression is evaluated. A certain operator has higher priority than other operators.
For example: the multiplication operator has higher priority than the addition operator, and the expression 1 + 5 * 6. According to the operator's priority, the compiler will first calculate 5 * 6, then calculate 30 + 1, and finally get the result 31.
The priority of various operators is from large to small:
., (), []Monocular + (right to left combined), Monocular - (right to left combined), ++, --, ~, !*, /,%+ (left to right combined), - (left to right combined)>>, <<, >>><, <=, >, >==, !=&|^&&||?:=, += etc. assignment operators
Don't worry about such a complex priority list. In most cases, the expression itself is easy to see priority. For example, the assignment operation must have the lowest priority. In cases where priority is not clear, we can change the priority the way we want it to, so there is no need to remember the operator priority too much.
8. Other operators
Three-way operator:
The conditional operator in Java is a ternary operator, and its form is as follows:
booleanExpression ? valueWhenTrue : valueWhenFalse
If the Boolean expression value is true, the value of the expression is the value of valueWhenTrue, otherwise the value of valueWhenFalse.
For example, if we want to calculate the absolute value of x, we can implement it through the following code:
if (x >= 0) { y = x;} else { y = -x;}Through the ternary operator, you only need one statement y = x >= 0 ? x : -x; to complete it, which is more concise.
Type conversion operator:
We use type conversion in many cases. At appropriate times, Java will automatically convert the data type to another according to the data type. For example, if we assign an integer value to the float variable, the compiler will convert int into float and assign it to the variable.
However, in many cases, Java cannot determine whether we need to perform type conversion. At this time, we need type conversion operators, which allow us to explicitly perform type conversion, such as:
int a = 10;long b = (long) a;long c = (long) 100;
We can type convert both variables and constants.
When performing type conversion of floating-point numbers, we need to pay attention to the problem of truncation. If we want to type convert 10.9: (int) 10.9, its value is not rounded 11, but 10