Thinking in Java - Operator

Posted by robot43298 on Thu, 25 Jul 2019 04:21:58 +0200

3. Operator

3.1 Static Import

  • Static import: Method calls static methods in other classes of static import

<! - Classes and static methods - >

package com.one;
public class Print {
    public static void print(String s){
        System.out.println(s);
    }
}

<! - Method of testing static imports

package com.one;
// Static Import Method
import static com.one.Print.*;
public class TestPrint {
    public static void main(String[] args) {
        System.out.println("Nomal Print");
        // Method output of static import
        print("Simple Print");
    }
}

3.2 Use Java operators

  • Side effects: Operators change the value of the operand itself <! - such as ++, - such operators - -->.

String classes support "+" and "+="

3.3 Priority

  • priority order

    • Multiplication, division, addition and subtraction
    • Use parentheses to specify the order of calculation

3.4 Assignment

  • Assignment: Use the operator "="
  • Assignment classification

    • Basic Type Assignment: Copy content directly to another location
    • Object Type Assignment: Copy "reference" from one place to another (one object corresponds to multiple references, one reference may have 0 or 1 object). Similar to pointer, since the original pointer points to a new object, the original object will be cleaned up by garbage collector. The following implementation can be seen in detail.

      class Tank{
        int level;
      }
      public class Assignment{
        public static void main(String[] args){
          // Before assignment
          Tank t1 = new Tank();
          Tank t2 = new Tank();
          t1.level = 9;
          t2.level = 47;
          print(t1+","+t2);
          // First assignment
          t1 = t2; 
          print(t1+","+t2);
          // Second assignment
          t1.level = 22;
          print(t1+","+t2);
        }
      }
      /*
      output:
      9,47
      47,47
      22,22
      */
  • Analysis of Alias Phenomenon

    • Code snippets (see Object Type Assignment for Assignment Category)
    • Principle analysis

      • The first assignment is to change the point of t2 to be the same as t1, and to point to the same object, because both T1 and t2 are references.
      • The second assignment modifies the level value in the same object that t1 and t2 point to.

3.5 Arithmetic Operator

  • Operator types

    • Plus +, minus -, division /, multiplication *, modulus%
    • Integer division removes decimal digits directly from the result and does not round it.
  • Random method

    • Random is a class that generates pseudo-random numbers. nextInt()/nextFloat() method is used to obtain random numbers.
    • Method of generating random lowercase letters: Random.nextInt(26)+'a'
    • If the seed parameters are the same, the random numbers generated are the same, as shown below.

      package com.four;
      import java.util.Random;
      public class TestRandom {
          public static void main(String[] args) {
                      // Same number of seeds      
              Random random1 = new Random(10);
              Random random2 = new Random(10);
              int i = random1.nextInt();
              int j = random2.nextInt();
              System.out.println("i="+i);
              System.out.println("j="+j);
          }
      }
      /* output:
      i=-1157793070
      j=-1157793070
      */

3.5.2 unary addition and subtraction operators

  • Monadic minus sign: change the symbol of data, or modify the data type
  • Univariate plus sign: Modify the data type to int type <! - for example, the original type is char, add the plus sign output, the resu lt is the corresponding value of ASCII code - >.

    package com.four;
    public class TestAdd {
        public static void main(String[] args) {
            int i = 1;
            char j = 'c';
            short k = 5;
            System.out.println(i);
            System.out.println(j);
            System.out.println(k);
            System.out.println("Add a plus sign");
            System.out.println(+i);
            System.out.println(+j);
            System.out.println(+k);
            System.out.println("Add minus sign");
            System.out.println(-i);
            System.out.println(-j);
            System.out.println(-k);
        }
    }
    /* output
    1
    c
    5
     Add a plus sign
    1
    99
    5
     Add minus sign
    -1
    -99
    -5
    */
    // /Users/toyz/Package/Note/Thinking in Java/Practice/Operators/src/com/four/TestAdd.java

3.6 Automatically Increasing and Decreasing

  • classification

    • Prefix increment and prefix decrement: first perform operations, then generate values
    • Suffix Incremental and Suffix Decreasing: Mr. Value, then Operate

      <! - The test code is as follows - >.

      package com.four;
      import static util.Print.*;
      public class TestIncreasing {
          public static void main(String[] args) {
              int i = 1;
              int j = i;
              print("i = "+i);
              // Prefix increment
              j = ++i;
              print("Incremental prefix");
              print("i = "+i);
              print("j = "+j);
              i = 1;
              j = i;
              // Decreasing prefix
              j = --i;
              print("After the prefix decreases");
              print("i = "+i);
              print("j = "+j);
              i = 1;
              j = i;
              // Suffix increment
              j = i++;
              print("Suffix Incremental Suffix");
              print("i = "+i);
              print("j = "+j);
              i = 1;
              j = i;
              // Suffix decrement
              j = i--;
              print("After the suffix decreases");
              print("i = "+i);
              print("j = "+j);
              i = 1;
              j = i;
          }
      }
      /* output
      i = 1
       Incremental prefix
      i = 2
      j = 2
       After the prefix decreases
      i = 0
      j = 0
       Suffix Incremental Suffix
      i = 2
      j = 1
       After the suffix decreases
      i = 0
      j = 1
      */
      // /Users/toyz/Package/Note/Thinking in Java/Practice/Operators/src/com/four/TestIncreasing.java

3.7 Relational Operator

  • classification

    • Greater than, less than, greater than or equal to, less than or equal to, equal to (==), not equal to (!=)
    • Equivalent to and not equal to all basic data types, other comparators do not use boolean types

Equivalence of 3.7.1 Objects

  • == And!= Compare the reference of the object <! -- even if the content of the object is the same, the reference of the two objects is different - >

    package com.five;
    
    public class TestEquals {
        public static void main(String[] args) {
            // Use == to compare different objects with the same content of the basic data class
            Integer n1 = new Integer(47);
            Integer n2 = new Integer(47);
            System.out.print("Use==Compare different objects with the same content:");
            System.out.println(n1 == n2);
    
            // Using equals to compare different objects with the same content of basic data classes
            System.out.print("Use equals Compare different objects with the same content:");
            System.out.println(n1.equals(n2));
    
            // Use == to compare different objects with the same content of a custom class
            Dog dog1 = new Dog();
            dog1.setName("spot");
            dog1.setSays("Ruff!");
            Dog dog2 = new Dog();
            dog2.setName("spot");
            dog2.setSays("Ruff!");
            System.out.print("Use==Compare different objects with the same content of a custom class:");
            System.out.println(dog1 == dog2);
    
            // Using equals to compare different objects with the same content of a custom class
            System.out.print("Use equals Compare different objects with the same content:");
            System.out.println(dog1.equals(dog2));
        }
    }
    /* output
     Use=== to compare different objects with the same content: false
     Use equals to compare different objects with the same content:
    Use == to compare different objects with the same content of a custom class: false
     Use equals to compare different objects with the same content: false
    */
    // /Users/toyz/Package/Note/Thinking in Java/Practice/Operators/src/com/five/TestEquals.java
  • summary

    • == For basic data types, it is a comparison value; for reference data types, it is a comparison address.
    • equals is effective for comparing the basic data types referenced, and is suitable for comparing object content, rather than for comparing object references <!--default-->.

3.8 Logic Operator

  • classification

    • And (&), or (| |), non (!)
    • The above three can only be applied to Boolean values
    • Using Boolean values where String values are used, Boolean values are automatically converted into appropriate text

3.8.1 Short Circuit

  • Definition: When the value of an expression can be determined, the rest of the expression is not computed.
  • Demonstration process: When judging (j < 2) as false, the program will not perform subsequent judgments and output false directly.

    package com.seven;
    import static util.Print.*;
    public class ShortCircuit {
        public static void main(String[] args) {
            int i = 1;
            int j = 2;
            int k = 3;
            print("res:"+((i<2)&&(j<2)&&(k<2)));
        }
    }    

3.9 Direct Constant

The suffix character of the direct constant labels the type

  • Common types

    • L stands for long.
    • F stands for Float
    • D stands for Double
    • Hexadecimal digits: denoted by prefix 0x followed by 0-9 or lowercase a-f
    • Octal digits: denoted by prefix 0 followed by 0-7 digits

3.9.1 Index Counting Method

E is used to represent the power of 10 in programming, but in science and engineering, e represents the cardinal number of natural logarithms.

3.10 bitwise operator

  • Operational mode

    • &,|,^,~
    • With, or, exclusive or counter-productive
    • XOR: The same is zero, the difference is 1 <! - For example, two switches control a lamp, one is on and 0 is off. When both switches are turned off, they are turned off, both switches are turned on and off, and two switches are turned on and off when one is turned on - >
  • Operational Rules

    1. &: 1&1=1 , 1&0=0 , 0&1=0 , 0&0=0
    2. |: 1|1=1 , 1|0=1 , 0|1=1 , 0|0=0
    3. ^: 1^1=0 , 1^0=1 , 0^1=1 , 0^0=1
    4. ~: ~1=0 , ~0=1
  • Binary operation

    1. Binary to hexadecimal: decimal point left to start left, right to start, each take four bits, insufficient left (right) zero

      1. Binary: 010101 - Hexadecimal: 15
      2. Step 1: Binary is divided into: 01, 0101
      3. Step 2: Completion: 0001, 0101
      4. Step 3: 0001 is 1, 0101 is 5 (when calculating, the order should be reversed, 0101 is regarded as 1010).
  • Use binary to represent negative numbers

    1. Get the original code: 00101111
    2. Get the inverse code: 11010000
    3. Get the complement (inverse plus one): 11010001

      <! - The end of the original code is zero, and the addition of inverse code requires forward carriage - >

3.11 Shift Operator

  • Left shift operator (<<): Operator moves to the left, low zero
  • Right Shift Operator (*): Operator moves to the right, when the symbol is positive, high-bit zero-filling; when the symbol is negative, high-bit zero-filling 1.
  • Unsigned Right Shift Operator (>): Insert zeros at high places, positive or negative.

When byte and short types use displacement operations, they are first converted to int classes.

3.12 ternary operator

  • if-else operator, boolean-eep? Value1: Value2

    value1 is calculated when the result is true; value2 is calculated when the result is false.

  • Pay attention to readability when using

3.13 String operators + and+=

  • Priority of calculation needs to be considered
package com.thirteen;

import static util.Print.*;

public class PrintString {
    public static void main(String[] args) {
        int x = 0 , y = 1 , z = 2;
        String s = "x,y,z";
        System.out.println(s+x+y+z);
        System.out.println(s+(x+y+z));
        System.out.println(x+y+z+s);
        System.out.println(x+""+s);
        System.out.println(""+x);
        System.out.println(x+y+z);
    }
}/* output
x,y,z012
x,y,z3
3x,y,z
0x,y,z
0
3
*/

3.15 Type Conversion Operator

  • Narrow Conversion: There is a risk in converting data types that can hold more information into data types that cannot hold so much information.
  • Extended Conversion: The new type can accommodate more information, is secure, and does not cause any loss of information.

Java allows any basic data type to be converted to other basic data types, but Boolean type does not allow any conversion.

Class data types do not allow type conversion unless special methods are used

3.15.1 Truncation and Rounding

  • Truncation

    1. Converting float and double to integer
  • Rounding off

    1. Use the round() method in java.lang.Math

3.15.2 Upgrade

The maximum data type in an expression determines the data type of the final result of the expression <! -- for example, double times float, and the result is double - >.

3.16 Java does not have sizeof

All data types are the same size in all machines

Topics: Java less ascii REST