# 9. Operators in Java

Posted by dombrorj on Fri, 11 Feb 2022 09:09:23 +0100

## Operators in Java

Author: Han Ru

Company: procedural coffee (Beijing) Technology Co., Ltd

Program coffee: IT vocational skill evaluation platform

website: https://www.chengxuka.com ```1.Arithmetic operator
2.Assignment Operators
3.Comparison operator
4.Logical operator
5.Bitwise Operators
6.Shift Bitwise Operators
7.Ternary operator
```

### 1, Expressions and operators

Expression: an expression is a sequence of operators and operands that conform to certain syntax rules

```a
5.0 + a
(a - b) * c - 4
i < 30 && i % 10 != 0

The type and value of the expression
The result of the operation on the operands in the expression is called the value of the expression
```
• The value of the expression

The result of the operation on the operands in the expression is called the value of the expression

• Type of expression

The data type of the value of the expression is the type of the expression

• Operation order of expression

First, the priority of operators should be in the order from high to low

The operators are combined in the same priority direction

Operators: what are operators?

a + b - 3

The above is called an expression, in which a, b and 3 are called operands, and the +, - in the middle is called an operator.

There are several operators in Java:

```Arithmetic operators:+ , - , * , / , % , ++ , --
Assignment operator:= , += , -= , *= , /= , %=
Relational operators:> , < , >= , <= , == , !=
Logical operators:! , & , | , ^ , && , ||
Bitwise operator:& , | , ^ , ~ , >> , << , >>>(understand)
String concatenation operator:+
ternary operator  ?:
```

### 1, Arithmetic operator

Arithmetic operators can perform some mathematical calculations:

operatorOperation rulesexampleresult
+Plus sign+33
+plus2+35
+Connection string"China" + "country""China"
-minus signint a=3;-a-3
-reduce3-12
*ride2*36
/except5/22
%Take mold5%21
++Self increasingint a=1;a++/++a0
Self subtractionint a=3;a–/--a3

explain:

• The addition operator +. When connecting strings, it should be noted that it can be converted into a string only when it is directly added to the string.

• Division "/" when both sides are integers, take the integer part and round off the remainder. When one side is floating-point, divide according to the normal rules.

• "%" modulus (remainder), decimal remainder is meaningless.

• ++Operator: it will increase by 1 based on the original value

• – operator: it will subtract 1 from the original value

Using arithmetic operators requires attention

```1.+There are many ways to use it,
For an operand, it can be used as a positive sign to represent a positive number.
For two operands, it can be used for summation operation.
For two strings, you can splice strings. be careful:+Whenever a string is encountered, it acts as a connection
2.-There are two ways to use it,
For an operand, it can be used as a negative sign to represent a negative number.
Two operands can be used for subtraction.
3.about java In terms of language, division can be divided into two cases: quotient and remainder, also known as module.
Supplier:/
Surplus:%
4.Self increasing and self decreasing,++，--，It's for integers. Do not operate on other types.
``` Basic arithmetic operation, example code:

```/*
Arithmetic operator
*/
public class Demo10ArithmeticOperators
{
public static void main(String[] args)
{
/*
Arithmetic operators: +, -, *, /,%, + +--
*/
int a = 10;
int b = 3;
//1. Positive and negative numbers
System.out.println(+a);
System.out.println(-b);
//2. Addition, subtraction, multiplication and division
int sum = a + b;//Find the sum of a+b and assign the result to the sum variable
System.out.println(sum);
int sub = a - b;//Find a-b
System.out.println(sub);
int mul = a * b;//Find aXb
System.out.println(mul);
//Division: quotient and remainder
int div = a / b;//Quotient
System.out.println(div);//3

int mod = a % b;//Take remainder, take mold
System.out.println(mod);//1

}
}

```

Operation results: Self increasing and self decreasing, example code:

```/**
*Arithmetic operator
*/
public class Demo11ArithmeticOperators
{
public static void main(String[] args)
{
/*
i++,++i，Self increment 1
i++And + + i, both add 1 to i
After execution, the value of i will be increased by 1.

Difference: the process is different
i++The value of is equivalent to i itself. After execution, i added 1.0 to myself
Calculate first and then add 1

++i The value of is equivalent to i+1
Add 1 first and then calculate

i--,--i，Self subtraction 1
*/
//1. Self increase and self decrease
int x = 3;
System.out.println(x);//3

System.out.println(x);//4

x--;//Subtract 1 from yourself
System.out.println(x);//3
System.out.println("-----------");

int i = 3;
System.out.println(i);//3
System.out.println(i++);//3
System.out.println(i);//4

i = 3;
System.out.println(++i);//4
System.out.println(i);//4
System.out.println("-----------");

//3. Participate in other operations
int j = 2;
int res = j++ + 3; //2 + 3=5
System.out.println(res);//5
System.out.println(j);//3

j = 2;
res = ++j + 3; //3 + 3
System.out.println(res);//6
System.out.println(j);//3

i = 2;
i = i++;
System.out.println(i);//2
}
}

```

Operation results: +A string is encountered to connect. Example code:

```public class Demo12ArithmeticOperators
{
public static void main(String[] args)
{
int num = 520;
String msg = "Program coffee";
System.out.println(msg + num);

int a = 3;
int b = 2;
//Print the sum of a and b, which is 5
System.out.println(a + b);//5
//Because "" content is encountered here, the following + is used to connect
System.out.println(a + " + " + b + " = " + a + b);//3 + 2 = 32
//To add a to b, try enclosing it in parentheses
System.out.println(a + " + " + b + " = " + (a + b));//3 + 2 = 5
}
}

```

Operation results: Stepping on the pit: during the division calculation, if the division by 0 program will report an error, the computer will not divide by 0 anyway. If you don't believe it, open the calculator and try it. 😂

### 2, Assignment operator

In the java language, we need to use assignment operators to assign values to some variables or constants. We generally use the equal sign = for assignment.

operatorOperation rulesexampleresult
=assignmentint a=22
-=Assignment after subtractionint a=2，a-=20
*=Assignment after multiplicationint a=2，a*=24
/=Assignment after divisionint a=2，a/=21
%=Assignment after module takingint a=2，a%=20

Assignment operator:

```int a = 2;
int b = a * 3;
```

The above operator is used to assign the value 2 on the = right to the variable a on the = left.

If the right side of the equal sign is complex, the calculation will be carried out on the right side of the equal sign, and the result will be automatically converted to the data type on the left of the equal sign, and then assigned to the variable on the left of the equal sign.

Based on the equal sign =, there are some extended assignment operators: + =, - =, * =, / =,% =.

```int a = 2;
a += 3;//Equivalent to a = a + 3
```

In the above two lines of code, first define variable a and assign value to 2. The second line of code means adding 3 to a and then reassigning it to a.

Example code:

```/**
*Assignment Operators
*/
public class Demo13AssignmentOperators
{
public static void main(String[] args)
{
/*
Assignment operators: =, + =, - =, * =, / =,%=
=: Assign the value of = right to the variable of = left
+=: a += b;//Equivalent to: a = a + b
-=: a -= b;//Equivalent to: a = a - b
*=: a *= b;//Equivalent to: a = a * b
/=: a /= b;//Equivalent to: a = a / b
%=: a %= b;//Equivalent to: a = a% B
*/
int a = 3;//Assign the value of 3 to the variable a
System.out.println(a);

a += 2;//Equivalent to: a = a + 2, that is, add 2 to a and assign it to a
System.out.println(a);//5

a -= 1;//Equivalent to: a = a - 1
System.out.println(a);//4

a %= 2;//Equivalent to: a = a% 2
System.out.println(a);//0

a = 2;
int b = 3;
a *= ++b; // Equivalent to a =a*(++b)
System.out.println(a);//8
System.out.println(b);//4
}
}

```

Operation results: ### 3, Relational operator

Comparison operator, also known as relational operator, is used to judge the size relationship and equality relationship of two operands. The result is Boolean true or false.

operatorOperation rulesexampleresult
==Equal to4==3False
!=Not equal to4!=3True
<less than4<3False
>greater than4>3True
<=Less than or equal to4<=3False
>=Greater than or equal to4>=3True

Example code:

```/*
*Relational operator
*/
public class Demo14RelationalOperators
{
public static void main(String[] args)
{
/*
Relational operator: indicates the relationship between two numbers, and the calculation result is of boolean type. True,False
>,<,>=,<=,==,!=

==，Compare two values equal. If equal, the result is true, otherwise it is false
!=，
*/
int a = 4;
int b = 4;
boolean res = a > b;

boolean res2 = a <= b;

System.out.println(res);//true

System.out.println(res2);//false

boolean res3 = a == b;// 4 == 4,true
System.out.println(res3);

boolean res4 = a != b;// 4!= 4,false
System.out.println(res4);//false
}
}

```

Operation results: ### 4, Logical operator

Logical operator, which is used for Boolean operation. The final result of the operation is Boolean true or false

operatorOperation rulesexampleresult
&And, understood as andfalse&trueFalse
|Or, understood as orfalse|trueTrue
^XORtrue^flaseTrue
!wrong!trueFlase
&&Short circuit andfalse&&trueFalse
||Short circuit orfalse||trueTrue
• &: and operation, operation rule: if multiple operands are true, the result will be true. If one is false, the result will be false.

One false is false, and the whole truth is true

• |: or operation, operation rule: if multiple operands are false, the result will be false, and if one is true, it will be true

One true is true, and all false is false

• &&: short circuit and short circuit. If false is encountered, the result will be returned as false, which will not be calculated later

• ||: short circuit or, if a true is encountered, the result will be returned as true, which will not be calculated later

• !: Take negative

• ^: XOR operation. If the operation values are different, the result is true, but the same is false.

Example code:

```/**
*Logical operator
*/
public class Demo15LogicalOperators
{
public static void main(String[] args){
/*
Logical operators: &, |,!, & &, |^
&: "And operation“
Operation rule: if all operands are true, the result will be true. If one is false, the result will be false

Summary: equivalent to "and". One false is false, and the whole truth is true.
Boys in girls' eyes: one mistake, total negation.

|: "Or operation“
Operation rule: if all operands are false, the result will be false. If one is true, the result will be true

Summary: equivalent to "or". One truth is true, and all false is false.
The girl in the eyes of boys: a bright spot makes her whole body glow.

&&: "Short circuit and“
The result of the operation is the same as the & operation.
The calculation process is different: & will calculate the whole formula and give a final result.
&&In the process of calculation, if a false is encountered, the result will be returned directly as false, and the following will not be calculated.

||: "Short circuit or“
The operation result and | operation are the same.
The calculation process is different: | the whole formula will be calculated to give a final result.
||In the calculation process, if you encounter a true, you will directly return the result as true, and the subsequent ones will not be calculated

!: "Take negative“
!true--->false
!false--->true

^: "XOR“
Operation rule: different is true, but the same is false.
Different -- > different
If the values of two operands are the same, the result of XOR is false
If the values are different, the XOR result is true
*/
boolean b1 = true;
boolean b2 = false;
boolean b3 = true;

boolean res1 = b1 & b2 & b3;
System.out.println(res1);//false

boolean res2 = b1 | b2 | b3;
System.out.println(res2);//true

boolean res3 = b1 && b2 && b3;
System.out.println(res3);//false

boolean res4 = b1 || b2 || b3;
System.out.println(res4);

boolean b4 = true;
System.out.println(b4);//true
System.out.println(!b4);//false

boolean res5 = b1 ^ b2;//XOR
System.out.println(res5);//true
boolean res6 = b1 ^ b3;
System.out.println(res6);//false

}
}
```

Operation results: ### 5, Bitwise operator

Bitwise operators operate on each binary bit of two operands.

Bitwise operator function

• Reverse by bit: ～
• Bitwise AND:&
• Bitwise OR: ｜
• Bitwise exclusive or:^
operatorOperation rulesexampleresult
~The original bit 1 turns to 0, and the original bit 0 turns to 1false&trueFalse
&The corresponding bits are all 1, the result bit is 1, and one is 0false|trueTrue
The corresponding bits are all 0, the result bit is 0, and one is 1true^flaseTrue
^The same value on the corresponding bit is 0, and the difference is 1!trueFlase

Bitwise inversion: for an operand, first convert the value to binary. Then reverse by bit.

For example, for the value 79, we need to convert to binary before we can analyze and calculate by bit. 79 is converted to binary: 01001111, and then reverse by bit. The original 1 is converted to 0, and the original 0 is converted to 1. Then the result is - 80. Example code:

```/**
*Bit operation
*/
public class Demo16BitOperators
{
public static void main(String[] args)
{

//1. Reverse by bit
//Defines an integer of type int
int a = 79;
//In fact, its corresponding binary representation: 0100 1111

System.out.println(Integer.toBinaryString(a));

int res = ~a;
/*
* Bitwise inversion:
* a=79
* Original binary: 0100 1111
* After bit inversion: 1011 0000
* Then the final calculation result is - 80
*/
System.out.println(res);
System.out.println(Integer.toBinaryString(res));

}
}

```

Operation results: Bitwise AND: converts both operands to binary, and then performs and operations on the corresponding bits.

For example, one operand is - 53 and the other is 109. First, convert - 53 to binary as 11001011, and the value 109 to binary as 01101101. Then, and operation is performed on the corresponding bit. The calculation result is bit 01001001, which is 73 when converted to decimal. Example code:

```/**
*Bit operation
*/
public class Demo16BitOperators
{
public static void main(String[] args)
{
//2. Bitwise AND
int x = -53;
int y = 109;
System.out.println(Integer.toBinaryString(x));
System.out.println(Integer.toBinaryString(y));
/*
*Bitwise AND
*-53		1100 1011
*109		0110 1101
*Bitwise AND 		 0100 1001
*The result is: 73
*/
int res2 = x & y;
System.out.println(res2);
System.out.println(Integer.toBinaryString(res2));
}
}

```

Operation results: Bitwise OR: converts both operands to binary, and then performs or operations on the corresponding bits.

For example, one operand is - 53 and the other is 109. First, convert - 53 to binary as 11001011, and the value 109 to binary as 01101101. Then the or operation is performed on the corresponding bit. The calculation result bit is 11101111, which is - 17 when converted to decimal. Example code:

```/**
*Bit operation
*/
public class Demo16BitOperators
{
public static void main(String[] args)
{
//3. Bitwise OR
int x = -53;
int y = 109;
System.out.println(Integer.toBinaryString(x));
System.out.println(Integer.toBinaryString(y));
/*
*Bitwise OR
*-53		1100 1011
*109		0110 1101
*Bitwise OR 		 1110 1111
*The result is: - 17
*/
int res3 = x | y;
System.out.println(res3);
System.out.println(Integer.toBinaryString(res3));

}
}

```

Operation results: Bitwise XOR: convert both operands to binary, and then XOR the corresponding bits.

For example, one operand is - 53 and the other is 109. First, convert - 53 to binary as 11001011, and the value 109 to binary as 01101101. Then, and operation is performed on the corresponding bit. The calculation result bit is 10100110. If it is converted to decimal, it is - 90. Example code:

```/**
*Bit operation
*/
public class Demo16BitOperators
{
public static void main(String[] args)
{

//4. Bitwise XOR
int x = -53;
int y = 109;
System.out.println(Integer.toBinaryString(x));
System.out.println(Integer.toBinaryString(y));
/*
*Bitwise XOR
*-53		1100 1011
*109		0110 1101
*Bitwise XOR 	 1010 0110
*The result is: - 90
*/
int res4 = x ^ y;
System.out.println(res4);
System.out.println(Integer.toBinaryString(res4));

}
}

```

Operation results: ### 6, Displacement operator

The shift operator refers to the shift left or right bit by bit after the value is converted to binary.

There are three types:

• Move left: "a < < B;"

Shift binary a bit by bit to the left by b bit, and fill 0 with the b bit vacated at the lowest bit

• Shift right with sign: "a > > b;"

Shift the binary form of a bit by bit to the right by b bit, and the b bit vacated in the highest bit complements the original symbol bit

• Unsigned right shift: "a > > > b;"

Shift binary a bit by bit to the right by b bit, and fill 0 with the b bit vacated from the highest bit

Take 2227 as an example: Example code:

```/**
*Displacement operation
*/
public class Demo17ShiftBitwiseOperators
{
public static void main(String[] args)
{
int x = 2227;
System.out.println(Integer.toBinaryString(x));
/*
*2227		00000000 00000000 00001000 10110011
*Shift left 3 bits 	 00000 000000 00001000 10110011 000, three zeros are added in the low position
*Shift right 3 bits 	 000 00000000 00000000 000000000 10110, discard the last three digits in the low position and supplement 0 in the high position
*unsigned right shift  		 Positive numbers shift right
*
*-2227		11111111 11111111 11110111 01001101
*Shift left 3 bits 	 11111 11111 11110111 01001101 000, three zeros are added in the low position
*Shift right 3 bits 	 111 11111 11111111 11110111 01001101, discard the last 3 bits in the low position and supplement 1 in the high position
*unsigned right shift  	 000 11111 11111 11110111 01001101, discard the last 3 bits in the low position and supplement 0 in the high position
*/
//Shift left 3 bits
int num1 = x << 3;
System.out.println(num1);//17816
System.out.println(Integer.toBinaryString(num1));//100010110011000
//Shift right 3 bits
int num2 = x >> 3;
System.out.println(num2);//278
System.out.println(Integer.toBinaryString(num2));//100010110
//unsigned right shift
int num3 = x >>> 3;
System.out.println(num3);//278
System.out.println(Integer.toBinaryString(num3));//100010110

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

int y = -2227;
System.out.println(Integer.toBinaryString(y));
//Shift left 3 bits
int num4 = y << 3;
System.out.println(num4);//-17816
System.out.println(Integer.toBinaryString(num4));//11111111111111111011101001101000
//Shift right 3 bits
int num5 = y >> 3;
System.out.println(num5);//-279
System.out.println(Integer.toBinaryString(num5));//11111111111111111111111011101001
//unsigned right shift
int num6 = y >>> 3;
System.out.println(num6);//536870633
System.out.println(Integer.toBinaryString(num6));//11111111111111111111011101001
}
}

```

Operation results: ### 7, Ternary operator

The so-called ternary operator means that the operator operates on three operands at the same time, so it is called ternary operator. Then the corresponding operators like a+b and c/d that operate on two operands at the same time are called binary operators. Similar to + +, + +,! a. Such an operator corresponding to an operand is called a unary operator.

The syntax structure of ternary operators is:

```X ? Y : Z
1.X Must be boolean Type expression.
2.Y and Z The data type must be consistent.

Execution sequence
Execute first X
true  implement  Y
false   implement Z

Calculate first x Value of, if true，The result of the whole three eye operation is an expression y Otherwise, the whole operation result is an expression z Value of.

``` The ternary operator actually implements a branch selection. X can be regarded as its condition. The two cases are Y and Z respectively. Which one to choose depends on whether x is established. If it is established, choose Y and if not, choose Z.

Of course, if you want to implement a variety of situations and choose one, you need the nesting of ternary operators. But its code readability is not very good, it just looks ugly. In the next chapter, you can choose one from many through branch statements. Readability is much better than ternary operators.

Example code:

```/**
*Ternary operator
*/
public class Demo18TernaryOperation
{
public static void main(String[] args)
{
/*
Ternary operator: Purpose: select a result according to conditions.
Operator:
?   :
X ? Y : Z
X: Boolean expression: true/false
Y: Result 1
Z: Result 2

X If the value of is true, the result of the entire ternary operator is Y.
X If the value of is false, the result of the entire ternary operator is Z.
*/
int score = 59;
String res = score == 100 ? "Full mark" : "Not full marks";
System.out.println(res);

//Given a score, judge whether you pass or not? Pass, fail

String res2 = score >= 60 ? "pass" : "fail,";
System.out.println(res2);

String res3 = !(score < 60) ? "pass" :"fail,";
System.out.println(res3);

//Given a value, judge whether it is positive or negative, or 0
int num = -5;
String res4 = num > 0 ? "Positive number" : num < 0 ? "negative" : "0";
System.out.println(res4);

}
}

```

Operation results: Stepping on the pit: the three eye operator can be nested, but beginners should pay attention to the syntax structure.

### 9, Priority

Priority is the order of precedence calculated by the operator.

• Unary operators take precedence over binary operators.
• We can change the evaluation order of an expression by adding parentheses. 