java learning notes operators

Posted by danbot26 on Sat, 08 Feb 2020 12:32:47 +0100

java learning notes (4) - operators

Article directory

operator

Operators are special symbols that perform specific operations on one, two, or three operands and return results.

As we explore operators in the Java programming language, it may help you to know in advance which operators have the highest priority. The operators in the following table are listed in order of precedence. The closer the operator is to the top of the table, the higher the priority. Operators with a higher priority are evaluated before operators with a relatively lower priority. Operators on the same line have the same priority. When operators of the same priority appear in the same expression, you must control a rule, and then evaluate which rule first. All binary operators are evaluated from left to right except assignment operators, which are evaluated from right to left.

Operator name Operator
Suffix *expr*++ *expr*--
One yuan ++*expr* --*expr* +*expr* -*expr* ~ !
Multiplication and division * / %
Addition and subtraction + -
By displacement << >> >>>
relationship < > <= >= instanceof
equality == !=
Bitwise &
Bitwise XOR ^
Bitwise OR |
Logic and &&
Logic or ||
Logic or ||
distribution = += -= *= /= %= &= ^== <<= >>= >>>=

Some operators tend to appear more frequently than others. For example:
Assignment operator "=" is more than unsigned shift right operator "> >

Assignment, arithmetic and unary operators

Simple assignment operator

One of the most common operators you will encounter is the simple assignment operator "="

int cadence = 0;
 int speed = 0;
 int gear = 1;

As described in creating objects, this operator can also be used with objects to assign object references.

Arithmetic operator

The Java programming language provides operators for addition, subtraction, multiplication, and division.

Operator describe
+ Addition operator (also used for string concatenation)
- Subtraction operator
* Multiplication operator
/ Department operators
% Remainder operator

The following program, ArithmeticDemo, tests the arithmetic operators.

class ArithmeticDemo {

    public static void main (String[] args) {

        int result = 1 + 2;
        // result is now 3
        System.out.println("1 + 2 = " + result);
        int original_result = result;

        result = result - 1;
        // result is now 2
        System.out.println(original_result + " - 1 = " + result);
        original_result = result;

        result = result * 2;
        // result is now 4
        System.out.println(original_result + " * 2 = " + result);
        original_result = result;

        result = result / 2;
        // result is now 2
        System.out.println(original_result + " / 2 = " + result);
        original_result = result;

        result = result + 8;
        // result is now 10
        System.out.println(original_result + " + 8 = " + result);
        original_result = result;

        result = result % 7;
        // result is now 3
        System.out.println(original_result + " % 7 = " + result);
    }
}
1 + 2 = 3 
3-1 = 2 
2 * 2 = 4 
4/2 = 2 
2 + 8 = 10 
107 = 3

You can also combine arithmetic operators with simple assignment operators to create composite assignments.

class ConcatDemo {
    public static void main(String[] args){
        String firstString = "This is";
        String secondString = " a concatenated string.";
        String thirdString = firstString+secondString;
        System.out.println(thirdString);
    }
}

The use method is similar to c/c + +, which will not be explained here

Unary operator

A unary operator requires only one operand.

operator describe
+ Unary plus sign operator; indicates a positive value (but without this, the number is positive)
- Unary subtraction operator
++ Increment operator; increment value by 1
-- Decrement operator; decrement value by 1
! Logical complement operator; reverse Boolean

The following program UnaryDemo tests the unary operator:

class UnaryDemo {

    public static void main(String[] args) {

        int result = +1;
        // result is now 1
        System.out.println(result);

        result--;
        // result is now 0
        System.out.println(result);

        result++;
        // result is now 1
        System.out.println(result);

        result = -result;
        // result is now -1
        System.out.println(result);

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

You can apply the increment / decrement operator before or after the operand (prefix) (suffix).

Both code result + +; and + + result; will end with a result increment of 1. The only difference is that the prefix Version (+ + result) is evaluated as the increased value, while the suffix Version (result + +) is evaluated as the original value. If you are only performing a simple increment / decrement, it doesn't matter which version you choose. However, if you use this operator as part of a larger expression, the operator you choose can make a big difference.

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;			   
        // prints 5
        System.out.println(i);
        // prints 6
        System.out.println(++i);
        // prints 6
        System.out.println(i++);
        // prints 7
        System.out.println(i);
    }
}

In summary, + + before, add before use, + + after, use before add.

Equality, relation and conditional operators

Equivalence and relational operators

Equality and relation operators determine whether an operand is greater than, less than, equal to, or not equal to another operand.

operator explain
== Be equal to
!= Unequal and
> greater than
< less than
>= Greater than or equal to
<= Less than or equal to

The following program, ComparisonDemo, tests the comparison operator:

class ComparisonDemo {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if(value1 == value2)
            System.out.println("value1 == value2");
        if(value1 != value2)
            System.out.println("value1 != value2");
        if(value1 > value2)
            System.out.println("value1 > value2");
        if(value1 < value2)
            System.out.println("value1 < value2");
        if(value1 <= value2)
            System.out.println("value1 <= value2");
    }
}

Output:

value1 != value2
value1 <  value2
value1 <= value2

Conditional operator

In & & AND and OR with the operator in two Boolean expressions. These operators exhibit a "short circuit" behavior, which means that the second operand is evaluated only when it is needed.

operator explain
&& Conditions and (a leave must be a leave)
|| Condition or (a truth must be true)
class ConditionalDemo1 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}

When * *?: *, we can think of it as a shorthand for the if then else statement. This operator is also called the * ternary operator, * because it uses three operands.

Example: if someCondition is true, the value result of value1to is assigned. Otherwise, assign the value result of value2to.

class ConditionalDemo2 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}

Because someCondition is true, this program prints "1" on the screen. If it makes your code more readable, use the?: operator instead of the if then else statement. For example, when the expression is compact and has no side effects (such as assignment).

Type comparison operator instanceof (and whether the object inherits from the parent class)

The object of the instanceof operator is compared to specify the type. You can use it to test whether an object is an instance of a class that implements a specific interface, an instance of a subclass, or an instance of a class.

The following program * * InstanceofDemo * * defines a Parent class (named Parent), a simple interface (named MyInterface) and a Child class (named Child) that inherits and implements the interface from the Parent class.

class InstanceofDemo {
    public static void main(String[] args) {

        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

The results are as follows:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

When using the instanceof operator, remember that null is not any instance.

Bitwise and shift operators

  • The Java programming language also provides operators that perform bitwise and shift operations on integer types. The operators discussed in this section are less common. As a result, their coverage is short; the purpose is just to let you know that these operators exist.

    The unary bitwise complement operator "~" reverses the transpose mode; it can be applied to any integer type, with each "0" as "1" and each "1" as "0". For example, a byte contains 8 bits; applying this operator to a value with a bit pattern of "00000000" changes its pattern to "11111111.".

  • The signed left shift operator "<" shifts bit patterns to the left, while the signed right shift operator ">" shifts bit patterns to the right. The bit mode is specified by the left operand and the number of shift positions is specified by the right operand. The unsigned shift right operator "> >" shifts zero to the leftmost position, and the leftmost position after "> > depends on the symbol extension.

  • Bitwise operations & operators perform bitwise and operations.

  • Bitwise exclusive or is performed by the bitwise ^ character.

  • Bitwise operation the caret performs a bitwise OR operation.

The following program BitDemo prints the number "2" to standard output using the bitwise AND operator.

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}

Operator summary

Simple assignment operator

=Simple assignment operators

Arithmetic operator

+Addition operator (also used for string concatenation)
-Subtraction operator
 *Multiplication operator
 /Partition operator, remainder operator

Unary operator

+Unary plus operator; indicates a positive value (the number is positive, but there is no such)
-Unary subtraction operator
 ++Increment operator; value of increment 1
 --Decrement operator; decrement 1 value
 ! Logical complement operator, reversing Boolean

Equals and relational operators

= = equal
 ! = not equal to
 > greater than
 >=Greater than or equal to
 < less than
 < is less than or equal to

Conditional operator

&&Conditions and
 ||Condition or
 ? : ternary (short for if then else declaration)

Type comparison operator

instanceof sets the object to the specified type 

Bitwise and shift operators

~ one yuan per bit complement
 < sign move left
 >>Sign move right
 >>>Unsigned shift right
 & bitwise AND
 ^Bitwise XOR
 |Bitwise OR

Questions and exercises: operators

problem

  • Consider the following code snippet. What operators does the code contain?

    >+
    
arrayOfInts [j]> arrayOfInts [j + 1]
  • Consider the following code snippet.

    • What are the values after i and n after code execution?

      i is 11, n is 0.

    • What are the final values of i and n, if not using the suffix increment operator (i + +), you can use the prefix Version (+ + i))?

      i is 11, n is 0.

int i = 10;
int n = i ++5;
  • To reverse the value of, boolean which operator would you use?

    Logical complement operator '!'.

  • Which operator is used to compare two values, = or = =?

    The = = operation is used for comparison and = for allocation.

  • Explain the following code example:

    The code should read: "if someCondition is true, assign a value of value1to result. Otherwise, assign the value of value2to result. "

    result = someCondition ? value1 : value2;
    

What are the values after i and n after code execution?

>`I 'is 11 and' n 'is 0.
  • What are the final values of i and n, if not using the suffix increment operator (i + +), you can use the prefix Version (+ + i))?

    i is 11, n is 0.

int i = 10;
int n = i ++5;
  • To reverse the value of, boolean which operator would you use?

    Logical complement operator '!'.

  • Which operator is used to compare two values, = or = =?

    The = = operation is used for comparison and = for allocation.

  • Explain the following code example:

    The code should read: "if someCondition is true, assign a value of value1to result. Otherwise, assign the value of value2to result. "

    result = someCondition ? value1 : value2;
    
Published 27 original articles, won praise 1, visited 1064
Private letter follow

Topics: less Java Programming