Fundamentals of Java -- details of operators and their skills

This article refers to the fourth edition of Java programming ideas, and makes some summaries combined with their existing knowledge.

At the bottom, data in Java is manipulated by using operators.

The use of most operators in Java is consistent with that in C, but Java has also made some improvements and optimizations. In this article, I will combine what I read in the book to share with you what I think are the precautions and skills of using operators in Java.

1. Priority

When there are multiple operators in an expression, the priority of operators determines the calculation order of each part. There are many complete operator priority rules in Java. We only need to remember the simplest and most commonly used - multiplication and division before addition and subtraction, arithmetic operation before bitwise operation, logic and (& &) > logic or (|). When the operator priority is the same, first left and then right. When you are unsure who should calculate first, don't save the use of parentheses. Enclose the expression you want to calculate first with parentheses. Remember () is the first priority.

2. Assignment symbol

The assignment symbol "=" assigns the value on the right to the value on the left.

As follows:

int a = 4;
int b = a;
float c = 3.0f;
float d = c;

This is the most common and correct way of writing. It will not bring any relevant impact (for example, changing the value of a in the following statements will not affect b, and changing the value of c will not affect d), because the value of basic data type also exists in the stack. When assigning value, just copy the value content on the right side and store it in the value on the left, The two will not have relevant effects in the following statements.

However, when "assigning" to an object, the result is very different from the basic data type.

public class A{
   int id;
    public static void main(String[] args){
        A a1 = new A();
        A a2 = new A();
        a1.id = 1;
        a2.id = 2;
        System.out.println(a1.id + " " + a2.id);
        a1 = a2;
        System.out.println(a1.id);
        a1.id = 1;
        System.out.println(a2.id);
    }
}

Output:

1 2
2
1

In Java, when we operate on an object, we actually operate on the reference to the object. At this time, if the reference of one object is assigned to the reference of another object, such as a1 = a2; in the above code;, Two different object references point to the same actual object. At this time, no matter which object reference is used to operate the actual object, when another object reference operates the actual object, the actual object has changed.

Therefore, in the actual coding, we need to minimize the assignment between the displayed object references. Because you may accidentally change the value of the actual object somewhere, you will feel very strange when you access it with other object references pointing to the actual object (you don't realize that there are other object references pointing to it, and the operation will be synchronized to the actual object).

3. Relational operators

Relational operators include: > < > = < = =! =, The generated value is a boolean data. If the relationship between operands is true, it returns true; otherwise, it returns false.

All relational operators can act on basic data types (boolean can only be used by = = and! =), which is basically consistent with what we have learned in C language. Note that = = and= It can act on two objects and produce answers that make you feel incorrect.

public class test2 {
    public static void main(String[] args) {
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1 == i2);
    }
}

You can guess what the above code will output. According to our previous knowledge and common sense, it should output true (because their actual values are equal), but in fact it outputs false. Why?

Relational operators and= When working on two objects, you are actually comparing whether the references of the two objects are the same. How do you know that the references of two objects are different. Remember what we said in the previous article, the object reference is stored in the stack, declaring two different object references, and not one object reference points to another object reference, they are naturally different. If Integer i2 = i1 is declared; Then i1i2 will return true.

If we want to compare whether the real contents of two objects are equal, we can override and call the equals method (from the Object class). The equals method has been overridden in Integer.

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

It can be seen that the equals method overridden by the Integer class is to compare whether the real values of two Integer objects are equal.

public class test2 {
    public static void main(String[] args) {
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1.equals(i2));
    }
}

Output:

true

**Note: * * the equals method of our own defined class inherits from the Object class. By default, it still compares the reference of the Object. If we want to compare whether the two objects are equal by other means, we need to override the equals method.

4. Logical operators

Logical operators: & & (and), | (or),! (non)

Note: logical operators can only act on boolean values!!!

In C language

while(2){
    
}

It can be compiled. At the same time, 0 can represent false and 1 can represent true in c language. At the same time! 0 = 1, which is not allowed in Java. The compiler will directly report errors during compilation.

Here are some operations allowed by logical operators in Java:

if(true || false)
if(true && false)
if((2 > 1) || (1 > 2))   
if((2 > 1) || (1 > 2)) 
if(!true)
if(!false)
.......

"Short circuit" phenomenon:

Expression 1 | expression 2 | expression 3 | expression 4

When the expression x is true, the expression x+1 to the last expression will not be evaluated, because the final result must be true

Expression 1 & & expression 2 & & expression 3 & & expression 4

When the expression x is false, the expression x+1 to the last expression will not be evaluated, because the final result must be false

public class shorttest {
    static boolean test1(int val){
        System.out.println("test1");
        return val > 1;
    }
    static boolean test2(int val){
        System.out.println("test2");
        return val > 2;
    }
    static boolean test3(int val){
        System.out.println("test3");
        return val > 3;
    }
    public static void main(String[] args) {
        boolean b = test1(2) && test2(1) && test3(4);
    }
}

If there is no short circuit, the output value should be

test1
test2
test3

However, due to the existence of short circuit, and test2 returns false, which are all & & logical operators, method test3 will not be executed in the end.

5. Direct constants

Some direct constants in the program are ambiguous. At this time, we need to give appropriate "guidance" to the compiler to add some additional information to the direct quantity.

long: 2324l,2324L

float: 2.0f,2.0F

double: 2.0d,2.0D

Octal: a number starting with 0 followed by 0-7

Hex: 0x223abc 0X223ABC

// short takes two bytes
short a = 0x1;

The above code can be compiled. Imagine that the constant 0x1 will be recognized. Why is the data type short or int and then truncated as short (lose the high 24 bits)? We can't get the answer here.

char a = 0xffff;
short b = 0xffff;

At this time, a can be compiled, but b can't. why? Both are clearly two bytes. This involves whether 0xffff is recognized as char or short or int before interception.

  1. If it is recognized as char or short, it is just two bytes. In the computer, the constant exists with complement, and the corresponding value of 0xffff is - 1. Therefore, both are compiled. But it's not right. The code supported by char in Java is Unicode. Therefore, char is an unsigned number and there is no negative sign. Then the result should be that a cannot be compiled and b can. Contrary to the actual result, all 0xffff are not recognized as two bytes.
  2. In fact, it will be recognized as int. at this time, 0xffff is first recognized as 0x0000ffff (the corresponding value is 255), and then automatically converted into two bytes (the value is still 255. Since char is an unsigned number, 255 is just its maximum value, but short is not OK (255 is greater than the maximum value of short). The compiler requires you to 0xffff and force conversion (short b = (short) 0xffff;). This is just in line with the actual results.

The default value of floating point number in Java is double

float = 1.0; It cannot be compiled because the data type of 1.0 is double by default. Double - > float needs to be displayed and transformed, or we can write it as float = 1.0f;

When arithmetic operators act on byte, short and char, their data types will be automatically raised to int. if the final value is still desired and indeed byte, short and char, the displayed data types need to be converted, as follows:

byte c = 1;
byte d = 1;
byte e = (byte) (c + d);
byte e = (byte) (c - d);
byte e = (byte) (c * d);
byte e = (byte) (c / d);
byte e = (byte) (c << d);
byte e = (byte) (c >> d);
byte e = (byte) (c & 1);
byte e = (byte) (c | 1);
byte e = (byte) (~c);

6. Bitwise operator

Bitwise AND:

If both are 1, it is 1, otherwise it is 0
00000011    3
	&
00000010    2
	=
00000010	2

Bitwise OR:

It is 0 when it is the same as 0, otherwise it is 1
00000011    3
	&
00000010    2
	=
00000011	3

Bitwise non:

0 Change from 1 to 0
~1
~00000001
 11111110(Negative number, complement)
 In order to get the source code, subtract 1 and take the opposite
 -1=
 11111101
 Reverse=
 10000010
 result=-2

Move left:

Low complement 0
1 << 2;
00000001 << 2;
00000100
 Equal to 4

Shift right with symbol:

Value of high complement sign bit
4 >> 1;
00000100 >> 1;
00000010
 Equal to 2
-4 >> 1;
11111100 >> 1;
11111110
 be equal to
 Minus one takes the opposite ->11111101->10000010
-2

Move right without symbol:

No matter what the sign bit is, the high bit is supplemented by 0
 use byte Data of type will be converted to int Type, then shift,
If you want to assign a value to byte Data of type needs to be truncated. (when moving, the symbol bit will also move).

Keywords: Java Back-end

Added by powaz on Tue, 01 Feb 2022 13:00:19 +0200