day04_ Common operators

Posted by not_skeletor on Sun, 20 Feb 2022 08:28:53 +0100

Operator overview

Operator: a symbol that operates on constants or variables. There are many kinds of Java operators that make up an expression (what are operands and operators, such as 1 + 2, where # 1 # and # 2 # are operands, + is an operator, and operators and operands combine to form an expression). Operators are divided according to the number of operands they require. They can include unary operators (1 ¢ operands), binocular operators (2 ¢ operands) and ternary operators (3 ¢ operands). Operators are divided according to their functions:

  • Arithmetic operator
  • Assignment Operators
  • Comparison operator (relational operator)
  • Logical operator
  • Bitwise Operators
  • Ternary operator

Operators have priority, so if you are not sure what to do with their priority, it's actually very simple. Just add parentheses directly. The priority with parentheses must be high, so you don't need to memorize the priority. If you are not sure, add parentheses, for example: 1 + 2 * 3. To ensure the sum first, you need to write: (1 + 2) * 3.

Arithmetic operator

Arithmetic operators include: + (sum of two numbers), - (subtraction of two numbers), * (product of two numbers), / (division of two numbers),% (modulo or remainder of two numbers), + + (monocular operator, add 1 to the number), -- (monocular operator, subtract 1 from the number). As shown in the figure below:

                                                                                                                                                                

matters needing attention:

  • /The difference between% and%: divide the two data, / take the quotient of the result, and% take the remainder of the result. Integer operation can only get integers. To get decimal points, floating-point numbers must be involved in the operation. Modulo operations are also valid for floating-point numbers
  • If you take the modulus of a negative number, you can ignore the negative sign of the modulus, such as 5% - 2 = 1. However, if the modulus is negative, it cannot be ignored. In addition, the result of modulo operation is not always an integer

Code example

/*
Division formula:
Quotient = divisor / divisor remainder
 For the expression of an integer, the division method uses integer division. When an integer is divided by an integer, the result is still an integer. Just look at the quotient, not the remainder.
Only for the division of integers, the modular operator has the meaning of remainder.
matters needing attention:
    1. Once there are different types of data in the operation, the result will be the one with a wide range of data types.
*/
public class Demo02Operator {
    public static void main(String[] args) {
        // Mathematical operations can be performed between two constants
        System.out.println(20 + 30);//50
 
        // Mathematical operations can also be performed between two variables
        int i = 20;
        int t = 30;
        System.out.println(i - t); // -10
 
        // Variables and constants can be mixed
        System.out.println(i * 10); // 200
 
        int x = 10;
        int y = 3;
 
        int result1 = x / y;
        System.out.println(result1); // 3
 
        int result2 = x % y;
        System.out.println(result2); // 1
 
        // int + double --> double + double --> double
        double result3 = x + 2.5;
        System.out.println(result3); // 12.5
 
        //Any four digits, flashback output, such as digital 1234 output 4321
        int a = 1234;
        //Get single digit
        int g = a % 10;
        //Get ten digits
        int s = a / 10 % 10;
        //Get hundreds
        int b = a / 100 % 10;
        //Get thousands
        int q = a / 1000;
        //Flashback output
        System.out.print(g);
        System.out.print(s);
        System.out.print(b);
        System.out.print(q);
    }
}

Character "+" operation: take the value corresponding to the character at the bottom of the computer to calculate

                                                                                                                                                                    

When an arithmetic expression contains values of multiple basic data types, the type of the entire arithmetic expression will be automatically promoted. Promotion rules:

  • byte type, short type and char type will be promoted to int type
  • The type of the whole expression is automatically promoted to the same type as the highest level operand in the expression. The level order is shown in the following figure:

                                                                                                                                                         

Code example

public class VariableTest1 {
    public static void main(String[] args) {
        //Define two variables
        int i = 10;
        char c = 'A'; //The value of 'A' is 65
        c = 'a'; //The value of 'a' is 97
        System.out.println(i + c);//107
        
        c = '0'; //The value of '0' is 48
        //char ch = i + c;
        //char type is automatically promoted to int type
        int j = i + c;
        System.out.println(j);//58
    }
}

String "+" operation: in the "+" operation, if a string appears, it is a connection operator, otherwise it is an arithmetic operation. When the "+" operation is carried out continuously, it is carried out one by one from left to right.

/*
The plus sign "+" in the four operations has three common uses:
1. For numerical values, that is addition.
2. For character char type, char will be promoted to int before calculation.
char Comparison table between type characters and int type numbers: ASCII and Unicode
3. For the String string (capitalized, not keyword), the plus sign represents the String concatenation operation.
When any data type is connected with a string, the result will become a string
*/
public class Demo {
    public static void main(String[] args) {
        // Basic use of string type variables
        // Data type variable name = data value;
        String str1 = "Hello";
        System.out.println(str1); // Hello
 
        System.out.println("Hello" + "World"); // HelloWorld
 
        String str2 = "Java";
        // String + int --> String
        System.out.println(str2 + 20); // Java20
 
        // Priority issues
        // String + int + int
        // String        + int
        // String
        System.out.println(str2 + 20 + 30); // Java2030
 
        System.out.println(str2 + (20 + 30)); // Java50
    }
}

Self increasing and self decreasing operator (belonging to arithmetic operator)

                                                                                         

Explain in detail

  • Basic meaning: let a variable increase by a number 1, or let a variable decrease by a number 1
  • Use format: write before or after the variable name. For example, + + i, or i++

Usage:

  • Use alone: it is not mixed with any other operation and becomes a step independently.
  • Mixed use: mixed with other operations, such as assignment, printing, etc.

Use difference:

  • When used alone, there is no difference between pre + + and post + +. That is: + + i; And i + +; It's exactly the same.
  • When mixing, there are [significant differences]
    • If it is [first + +], the variable [immediately + 1], and then use it with the result.
    • If it is [post + +], first use the original value of the variable, [and then let the variable + 1].

matters needing attention:

  • Only variables can use self increasing and self decreasing operators. Constants cannot be changed, so they cannot be used.
  • Whether it is before + + / - - or after + + / - -, as long as the execution of + + / -, the final result will make the variable increase by - 1 / decrease by 1.

Code example

package demo;
 
public class Demo {
    public static void main(String[] args) {
        int num1 = 10;
        System.out.println(num1); // 10
        ++num1; // Used alone, before++
        System.out.println(num1); // 11
        num1++; // Used alone, after++
        System.out.println(num1); // 12
 
 
        // When mixed with printing operation
        int num2 = 20;
        // Mixed use, first + +, the variable immediately becomes 21, and then print the result 21
        System.out.println(++num2); // 21
        System.out.println(num2); // 21
 
 
        int num3 = 30;
        // After mixed use, + +, first use the original 30 of the variable, and then let the variable + 1 get 31
        System.out.println(num3++); // 30
        System.out.println(num3); // 31
 
 
        int num4 = 40;
        // Mixed with assignment operation
        int result1 = --num4; // Mixed use, before --, the variable immediately - 1 becomes 39, and then give the result 39 to the result1 variable
        System.out.println(result1); // 39
        System.out.println(num4); // 39
 
 
        int num5 = 50;
        // After mixed use --, first give the original number 50 to result2, and then - 1 becomes 49 myself
        int result2 = num5--;
        System.out.println(result2); // 50
        System.out.println(num5); // 49
 
 
        int x = 10;
        int y = 20;
        // 11 + 20 = 31
        int result3 = ++x + y--;
        System.out.println(result3); // 31
        System.out.println(x); // 11
        System.out.println(y); // 19
 
        // 30++; //  Wrong writing! Constants cannot use + + or--
    }
}

Relational operator

Relational operators are mainly used to complete the comparison between data. For example, if 5 > 3, the result is true, if 5 > 10, the result is false.

                                                                                                          

be careful:

  • The result of the comparison operator must be a boolean value. If it is true, it is false. Never mistake "= =" for "=".  
  • If you make multiple judgments, you can't write in succession. The writing method in mathematics, for example, 1 < x < 3 [not allowed] in the program

Code example

/*
        One rule to remember:
            The results of all relational operators are Boolean,
            Either true or false. It can't be any other value.
        
        In the java language:
            = :  Assignment Operators 
            == : Relational operators to determine whether they are equal.
        
        Note: if there are two symbols in a relational operator, there can be no space between the two symbols.
            >= This is right, > = this is wrong.
            == This is right, = = this is wrong.
*/
 
public class Demo {
    public static void main(String[] args) {
        System.out.println(10 > 5); // true
        int num1 = 10;
        int num2 = 12;
        System.out.println(num1 < num2); // true
        System.out.println(num2 >= 100); // false
        System.out.println(num2 <= 100); // true
        System.out.println(num2 <= 12); // true
        System.out.println("===============");
        
        System.out.println(10 == 10); // true
        System.out.println(20 != 25); // true
        System.out.println(20 != 20); // false
        
        int x = 2;
        // System. out. println(1 < x < 3); //  Wrong writing! Compilation error! You can't write in succession.
    }
}

Assignment Operators

The operators of assignment class include basic assignment operators (=) and extended assignment operators (+ =, - =, * =, / =,% =).

                                                                                                      

matters needing attention:

  • Only variables can use assignment operators, and constants cannot be assigned.
  • The assignment operator operates directly on the original variable, so it will not change the data type of the variable. The compound assignment operator implies a forced type conversion.  
  • When the assignment operator is written, there must be no space between two symbols. When using this operator, you must ensure that the result of data operation cannot exceed the maximum value range of the data type on the left, otherwise unpredictable results will appear
  • =Assign the value on the right to the variable on the left. Be sure to assign the value after all the code operations on the right are completed
  • When the data types on both sides of "=" are inconsistent, you can use automatic type conversion or mandatory type conversion principle for processing. Continuous assignment is supported. Not recommended

Code example

/*
Assignment operators are divided into:
Basic assignment operator: it is an equal sign "=", which means to give the data on the right to the variable on the left.
The right side of the assignment operator "=" has higher priority, and the expression on the right side shall be executed first
    int a = 30;
Compound assignment operator:
    +=        a += 3        Equivalent to a = a + 3
    -=        b -= 4        Equivalent to b = b - 4
    *=        c *= 5        Equivalent to c = c * 5
    /=        d /= 6        Equivalent to d = d / 6
    %=        e %= 7        E = 7%
*/
public class Demo03Operator {
    public static void main(String[] args) {
        int i = 10;
        // Translate according to the formula: a = a + 5
        // a = 10 + 5;
        // a = 15;
        // a was originally 10, but now it is reassigned to 15
        i += 5;
        System.out.println(i); // 15

        int x = 10;
        // x = x % 3;
        // x = 10 % 3;
        // x = 1;
        // x was originally 10, but now it is reassigned to 1
        x %= 3;
        System.out.println(x); // 1

        // 50 = 30; //  Constants cannot be assigned and cannot be written to the left of the assignment operator. Wrong writing!

        byte num = 30;
        // num = num + 5;
        // num = byte + int
        // num = int + int
        // num = int
        // num = (byte) int
        num += 5;
        System.out.println(num); // 35

        //Variable exchange
        int a = 30;
        int b = 40;
        int temp;
        //Use intermediate variables
        temp = a;
        a = b;
        b = temp;
        System.out.println(a);//40
        System.out.println(b);//30
        int c = 11;
        int d = 21;
        //Variable exchange does not use intermediate variables
        c = c + d;
        d = c - d;
        c = c - d;
        System.out.println(c);//21
        System.out.println(d);//11

    }
}

Logical operator

It mainly includes logic and (&), logic or (|), logic XOR (^), short circuit and (& &), short circuit or (|). The characteristic of all logical operators is that the operands are Boolean, and the final operation result is also Boolean.

be careful:

  • Logical operators are used to connect Boolean expressions. They cannot be written as 3 < x < 6 in Java, but should be written as x > 3 & x < 6.
  • Logic and &, whether true or false on the left, must be executed on the right.
  • Short circuit and &, if the left is true, execute on the right; If the left is false, the right is not executed.
  • Logic or |, whether true or false on the left, must be executed on the right.
  • Short circuit or 𞓜 if the left is false, execute on the right; If the left is true, the right is not executed.

Common logical operators

Code example

/*
And (and) & & are all true, is true; Otherwise, it is false
 Or (or) | at least one is true, which is true; It's all false. It's false
 Not (reverse)! Originally true, it becomes false; It used to be false, but it became true
 And "& &", or "|", with short circuit effect:
If the final result can be judged from the left, the code on the right will no longer be executed, thus saving some performance.
matters needing attention:
1. Logical operators can only be used with boolean values.
2. And, or need to have a boolean value on the left and right respectively, but the reverse can only have a unique boolean value.
3. And, or two operators. If there are multiple conditions, they can be written continuously.
Two conditions: condition a & & condition B
 Multiple conditions: condition a & & condition B & & condition C
TIPS: 
For the case of 1 < x < 3, it should be split into two parts and then connected with the and operator:
int x = 2;
1 < x && x < 3
*/
public class Demo {
    public static void main(String[] args) {
        System.out.println(true && false); // false
        // true && true --> true
        System.out.println(3 < 4 && 10 > 5); // true
        System.out.println("============");
        
        System.out.println(true || false); // true
        System.out.println(true || true); // true
        System.out.println(false || false); // false
        System.out.println("============");
        
        System.out.println(true); // true
        System.out.println(!true); // false    
        System.out.println("============");
        
        int a = 10;
        // false && ...
        System.out.println(3 > 4 && ++a < 100); // false
        System.out.println(a); // 10
        System.out.println("============");
        
        int b = 20;
        // true || ...
        System.out.println(3 < 4 || ++b < 100); // true
        System.out.println(b); // 20
    }
}

ternary operator

          

Execution process:

  • First, evaluate the value of the relationship expression
  • If the value is true, the value of expression 1 is the result of the operation
  • If the value is false, the value of expression 2 is the result of the operation

Code example

/*
Format:
Data type variable name = condition judgment? Expression A: expression B;
technological process:
First, judge whether the conditions are true:
    If true, assign the value of expression A to the variable on the left;
    If it is not false, assign the value of expression B to the variable on the left;
Choose one of the two.
*/
public class Demo{
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        
        // Data type variable name = condition judgment? Expression A: expression B;
        // Judge whether a > b is true. If it is true, assign the value of a to max; If not, assign the value of B to max. Choose between the two
        int max = a > b ? a : b; // Maximum variable
        System.out.println("Maximum:" + max); // 20
        
        // int result = 3 > 4 ?  2.5 : 10; //  Wrong writing!
        
        System.out.println(a > b ? a : b); // Write correctly!
        
        // a > b ?  a : b; //  Wrong writing!
    }
}

Note: the data type of expression A and B must meet the requirements at the same time. The results of ternary operators must be used if they are not saved with variables.

Bitwise Operators

Bit operation is an operation directly on the binary of an integer, and the operation of the {bit operator is integer data.

                                                                                         ​

Code example

/*
Conclusion:
1. Bitwise operators operate on integer data
2. << : Within a certain range, every 1 bit to the left is equivalent to * 2
   >> :Within a certain range, each shift to the right is 1 bit, which is equivalent to / 2
 Interview question: the most efficient way to calculate 2 * 8? 2 < < 3 or 8 < < 1
*/
class BitTest {
    public static void main(String[] args) {
        int i = 21;
        i = -21;
        System.out.println("i << 2 :" + (i << 2));
        System.out.println("i << 3 :" + (i << 3));
        System.out.println("i << 27 :" + (i << 27));
 
        int m = 12;
        int n = 5;
        System.out.println("m & n :" + (m & n));
        System.out.println("m | n :" + (m | n));
        System.out.println("m ^ n :" + (m ^ n));
 
        //Exercise: exchanging the values of two variables
        int num1 = 10;
        int num2 = 20;
        System.out.println("num1 = " + num1 + ",num2 = " + num2);
 
        //Method 1: how to define temporary variables
        //Recommended way
        int temp = num1;
        num1 = num2;
        num2 = temp;
 
        //Method 2: benefits: no need to define temporary variables  
        //Disadvantages: ① addition operation may exceed the storage range ② limitations: it can only be applied to numerical types
        //num1 = num1 + num2;
        //num2 = num1 - num2;
        //num1 = num1 - num2;
 
        //Method 3: use bitwise operators
        //Limitations: can only be applied to numeric types
        //num1 = num1 ^ num2;
        //num2 = num1 ^ num2;
        //num1 = num1 ^ num2;
 
        System.out.println("num1 = " + num1 + ",num2 = " + num2);
 
    }
}

                                                                          

About hexadecimal

All numbers exist in binary form at the bottom of the computer.

For integers, there are four representations:

  • Binary: 0,1, full 2 into 1 Start with 0b or 0b.
  • Decimal: 0-9, full 10 into 1.
  • Octal: 0-7, full 8 into 1 Start with the number 0.
  • Hexadecimal (hex): 0-9 and A-F, full 16 into 1 It starts with 0x or 0x. A-F here is not case sensitive. For example: 0x21AF +1= 0X21B0

Binary

Java integer constant is of type int by default. When an integer is defined in binary, its 32nd bit is the sign bit; When it is a long type, binary occupies 64 bits by default, and the 64th bit is the sign bit

Binary integers have the following three forms:

  • Original code: directly change a numerical value into a binary number. The highest bit is the sign bit
  • Inverse code of negative number: it reverses the original code by bit, but the highest bit (sign bit) is determined as 1.