From Beginner to Expert: A Complete Guide to Java Operators

Table of contents

1. Arithmetic operators

2. Incremental operator 

2.1 Increment/decrement operator

4. Logical operators

5. Bitwise operators

6. Shift operators  

 7. Conditional Operators



Introduction:
Java is a widely used programming language, and its operators are an essential part of writing code. This blog will introduce you to various operators in Java in detail, from basic arithmetic operators to advanced bit operators and ternary operators, and open the door to the mysteries of operators for you. We will help you better understand and apply these operators through code samples and simple examples.

1. Arithmetic operators

Basic four operators: Arithmetic operators are used to perform basic mathematical operations, including addition, subtraction, multiplication, division, modulus, etc. Following are some common arithmetic operators and their usage:
int a = 10;
int b = 5;

int sum = a + b;        // 加法运算
int difference = a - b; // 减法运算
int product = a * b;    // 乘法运算
int quotient = a / b;   // 除法运算
int remainder = a % b;  // 取余运算

Precautions:

1. Both are binary operators, and there must be two left and right operands when using them

int a = 10;
int b = 5;

int sum = a + b;        // 加法运算
int difference = a - b; // 减法运算
int product = a * b;    // 乘法运算
int quotient = a / b;   // 除法运算
int remainder = a % b;  // 取余运算

2. The result of int / int is still int type, and it will be rounded down

inta=3;
intb=2;
//在数学中应该是1.5但是在Java中输出结果为1会向下取整,即小数点之后全部舍弃掉了System.out.println(a/b);

//如果要得到数学中的结果,可以使用如下方式
doubled=a*1.0/b;   //只要相乘数有一位数字是小数,结果就为小数
System.out.println(d);

3. When doing division and modulus, 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)

4.% It is not only possible to take the modulus of the integer type, but also of the double type, but it is meaningless. Generally, it is used to take the modulus of the integer type

System.out.println(11.5 % 2.0);
// 运行结果
1.5

5. When the types of the operands on both sides are inconsistent, the type is improved

System.out.println(1+0.2);
//+的左侧是int,右侧是double,在加之前int被提升为double型
//故输出1.2

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.
Specific examples are as follows:
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

Note: Only variables can use this operator, not constants.

2.1 Increment / decrement operator

The increment operator comes in two flavors: prefix increment and postfix increment. The prefix increment operator ( ++x ) will first increment the value of a variable by 1 and then return the incremented value. The postfix increment operator ( x++ ) will return the original value of the variable before incrementing it by 1. The decrement operator also has similar prefix and postfix forms.
Specific examples are as follows:
int x = 5;

// 前缀递增
int y = ++x;
// y的值为6,x的值也为6

// 后缀递增
int z = x++;
// z的值为6,x的值变为7

// 前缀递减
int a = --x;
// a的值为6,x的值变为6

// 后缀递减
int b = x--;
// b的值为6,x的值变为5

The increment operator is commonly used in programming for loops, conditional statements, and other scenarios where variables need to be incremented or decremented. They provide a concise and convenient way to update the value of a variable.

3. Relational Operators

Relational operators are used to compare the relationship between two values ​​and return a boolean value (true or false) . Here are some common relational operators and their usage:

int a = 10;
int b = 5;

boolean isEqual = a == b;      // 相等运算
boolean isNotEqual = a != b;   // 不相等运算
boolean isGreater = a > b;     // 大于运算
boolean isLess = a < b;        // 小于运算
boolean isGreaterOrEqual = a >= b; // 大于等于运算
boolean isLessOrEqual = a <= b;    // 小于等于运算

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

4. Logical operators

When logical judgments are required in conditional statements or Boolean expressions, Boolean values ​​(true or false) are manipulated through logical operators.

1. Logical AND operator (&&)
The logical AND operator means that the entire expression is true only when both conditions must be true. If any one of the conditions is false, the entire expression is false.

boolean a = true;
boolean b = false;
boolean result = a && b;  // 结果为false,因为b为false

Logical OR operator (||)
The logical OR operator means that when at least one of the two conditions is true, the entire expression is true. The entire expression is false only if both conditions are false.

boolean a = true;
boolean b = false;
boolean result = a || b;  // 结果为true,因为a为true

Logical NOT operator (!)
The logical NOT operator is used to negate the operation, changing true to false and false to true.

boolean a = true;
boolean result = !a;  // 结果为false,因为a为true

short circuit evaluation

Both the AND operator (&&) and the OR operator (||) feature short-circuit evaluation. Short-circuit evaluation means that when the result of the entire expression can be determined from the result of the first condition, the second condition is not evaluated.

Note two points:

  1. For the logical AND operator (&&), if the first condition is false, the entire expression must be false, and the evaluation of the second condition will not be performed.
  2. For the logical OR operator (||), if the first condition is true, the entire expression must be true, and the calculation of the second condition will not be performed.

boolean a = true;
boolean b = false;
boolean result = a || (b && someOtherCondition);  // 如果a为true,则整个表达式为true,不会计算第二个条件

Effect: Short-circuit evaluation can improve the performance of the program, and in some cases avoid unnecessary calculations. Logical operators play an important role in control flow statements, conditional statements, and Boolean expressions. They allow us to make complex logical judgments and combinations of conditions to control the behavior of the program. Understanding the meaning and usage of logical operators is crucial to writing correct and readable code.

5. Bitwise operators

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

12 & 5

12:  00001100
5:   00000101
-------------
     00000100
结果: 00000100 (4)

Bitwise OR (|) : If both binary bits are 0, the result is 0, otherwise the result is 1

12 | 5

12:  00001100
5:   00000101
--------------
     00001101
结果: 00001101 (13)

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.

Bitwise inversion ~: If the bit is 0 , turn it to 1, if the bit is 1 , turn it to 0
~12

12:  00001100
------------
结果: 11110011 (-13)

Precautions:

1. 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.
2. 0xf means 15 in decimal, which is 1111 in binary.
3. printf can format the output content, %x means output in hexadecimal
4.\n represents a newline character

 Bitwise XOR ^: If the binary bits of the two numbers are the same , the result is 0, and if they are different, the result is 1

12 ^ 5

12:  00001100
5:   00000101
--------------
     00001001
结果: 00001001 (9)

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


6. Shift operators  

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

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

12 << 2

12:  00001100
------------
结果: 00110000 (48)

2. Shift right >> : The rightmost bit is unnecessary , and the leftmost complements the sign bit ( positive numbers complement 0, negative numbers supplement 1) 

12 >> 2

12:  00001100
------------
结果: 00000011 (3)

3. Unsigned right shift >>>: The rightmost bit is not needed , and the leftmost is filled with 0. 

-12 >>> 2

-12:  11110011
------------
结果: 00111100 (60)
Notice:
1. Left shift by 1 bit is equivalent to the original number * 2. Left shift by N bits is equivalent to the original number * 2 to the Nth power.
2. 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.
3. Since the efficiency of computer shift calculation is higher than that of multiplication and division, when a certain code just multiplies and divides 2 to the Nth power, it can be replaced by a shift operation.
4. It doesn't make sense to move negative digits or shift digits too large.

 7. Conditional Operators

There is only one conditional operator : the ternary operator

The structure is: condition?result1 :result2

If the condition is true, then the result of the entire expression is result 1; if the condition is false, the result is result 2.

Think of conditional operators as a quiz game. The condition is a question, and if the answer is true, we choose result 1 as the answer; if the answer is false, we choose result 2 as the answer.

Here's a concrete example:
 

int age = 20;
String message = (age >= 18) ? "成年人" : "未成年人";

In the above example, we select different information based on the conditional judgment of age. If the age is greater than or equal to 18 years, we select "Adult" as the information; otherwise, we select "Minor" as the information.

Okay, that’s all for the content. If there are any mistakes above, please point them out in the comment area. If I can help you, I hope you can support me again and again, thank you. Heap Tang students will agree very much.

Guess you like

Origin blog.csdn.net/LHY537200/article/details/132131419