JAVA basic syntax

Posted by gorskyLTD on Thu, 24 Feb 2022 01:49:20 +0100

1.JAVA escape characters -- common escape characters

  • \t: A tab stop to realize the alignment function

  • \n: Line feed

  • \: one\

  • \: one

  • \': one'

  • \r: A carriage return

    System.out.println("Digital and efficient office\r information"); \\Information efficient office
    System.out.println("Digital and efficient office\r\n information"); \\Digital and efficient office  \\information
    

2. Comment

The text used to annotate the interpreter is annotation, which improves the readability (readability) of the code; Annotation is a good programming habit that a program source must have. First sort out your ideas through annotation, and then reflect them in code

1. Annotation type in Java
  • Single-Line Comments

    \\notes
    
  • multiline comment

    /*
      notes
     */
    
  • Document comments: the comments can be parsed by the javadoc provided by JDK to generate a set of description documents of the program in the form of web files

    javadoc -d Document storage location -xx -yy .java program        (xx\yy   need javadoc Label, e.g version,author etc.)
    
    /**
     *notes
     *
     */
    
  • Use details

    • The annotated text will not be interpreted and executed by the JVM
    • Many comments are not allowed to be nested in multi line comments

3.JAVA code specification

  • The annotations of classes and methods should be written in the form of javadoc

  • Non javadoc comments are often given to code maintainers, focusing on telling readers why to write like this, how to modify it, and what problems to pay attention to

  • Use the tab operation to indent. By default, the whole moves to the right, and the whole moves to the left with shift+tab

  • Operators and = habitually add a space on both sides

  • The source file is encoded with utf-8

  • The line width should not exceed 80 characters

  • Code writing second line style and end of line style

4. Operator

1. General
  • Operator is a special symbol used to represent the operation, assignment and comparison of data
2. Arithmetic operators
  • Arithmetic operators operate on numeric variables and are used very often in JAVA programs

    It is suggested to save the picture directly from the external link (if there is a common picture transfer mechanism, it may fail to save the picture to the external link) (g51574g-57msg)

int num = 10;
int nums = num++;
System.out.println(++num);//12
System.out.println(nums);//10
System.out.println(num++);//12
3. Relational operators
  • The results of relational operators are boolean, that is, either true or false
4. Logical operators
  • It is used to connect multiple conditions (multiple relational expressions), and the final result is also a boolean value

  • Logical operator description
    • && &: & all comparisons will be made. If it is true, it will be true&& As long as there is false, stop the comparison and output false directly
    • ^: negative. When the two are different, the result is true and the same is false
    • |||: ||will judge all conditions|| As long as one condition is true, terminate the judgment and directly output true, which is efficient
5. Assignment operator
  • Assignment operator is to assign the value of an operation to a specified variable

  • classification

    • Basic assignment operator=

    • Match assignment operators + = - = * = / = * *% = * * etc

      int num = 123;
      int numa = 123;
      num += nums;//num = num+nums
      num -= nums;//num = num-nums
      
  • Characteristics of assignment operator

    • The operation order is from right to left

    • Left side of assignment operator - only variables; Right - can be variables, expressions, constant values

    • The compound assignment operator performs type conversion (implicit)

      byte c = 5;
      c += 3;
      System.out.println(c);//88
      System.out.println(c++);//88
      
6. Ternary operator
  • Basic grammar
    • Conditional expression? Expression 1: expression 2;
    • If the conditional expression is true, the result of the operation is expression 1
    • If the conditional expression is false, the result of the operation is expression 2
7. Operator priority
  • Operators have different priorities. The so-called priority is the operation order in expression operation

  • Only monocular operators and assignment operators operate from right to left

8. Binary
  • Introduction to hexadecimal - for integers, there are four representations
    • Binary: 0,1 full 2 into 1, starting with 0b or 0b
    • Octal: 0-7 full 8 into 1, starting with 0
    • Decimal: 0-9 full 10 in 1
    • Hexadecimal: 0-9 and A-F, full 16 into 1, starting with 0x or 0x
  • Conversion rules between hexadecimals
    • Other base to decimal systems start from the lowest bit (right), extract the number on each bit and multiply it by the power of the current base (digit - 1)
    • Convert decimal system to other base systems, divide the number by the required base system until the quotient is 0, and then reverse the remainder obtained in each step, which is the corresponding octal system
    • Convert binary to octal or hexadecimal. Starting from the low order, set the binary number every three or four digits (into decimal) to form the corresponding octal or hexadecimal number
9. Bitwise operator
  • Original code, inverse code and complement code
    • The highest bit of binary is the sign bit: 0 is a positive number and 1 is a negative number
    • The original code, inverse code and complement of positive numbers are the same
    • The inverse code of a negative number is equal to its original code, the sign bit remains unchanged, and other bits are reversed
    • The complement of a negative number is equal to its inverse code + 1, and the inverse code of a negative number = the complement of a negative number - 1
    • The inverse and complement of 0 are all 0
    • Java does not have unsigned numbers. In other words, all numbers in Java are signed
    • In computer operation, it is calculated in the way of complement
    • When we see the result of the operation, we should look at its original code
  • 7-bit operation (&, |, ^, ~, > >, < < and > >)
    • Operation rules
      • Bitwise AND &: both bits are 1, the result is 1, otherwise it is 0
      • Bitwise or |: one of the two bits is 1, and the result is 1, otherwise it is 0
      • Bitwise XOR ^: two bits, one is 0, the other is 1, the result is 1, otherwise it is 0
      • Bitwise inversion ~: 0 – > 1,1 – > 0
        /**
         * 1.First get the complement of 2 00000000 00000000 00000000 00000010
         * 2.3 Complement of 00000000 00000000 00000000 00000011
         * 3.Bitwise&
         *  00000000 00000000 00000000 00000010
         *  00000000 00000000 00000000 00000011
         *  00000000 00000000 00000000 00000010   (&(complement after operation)
         *  Original code after operation: 00000000 00000000 00000000 00000010 2
         */
        System.out.println(2&3);//2

        /**
         * 1.First get the original code of - 2 10000000 0000000 0000000 000000 10
         * 2.Get the inverse code of - 2 11111111111111111111111111111101
         * 3.Get the complement of - 2 11111111111111111111111111111111110
         * 4.Bitwise~
         *      00000000 00000000 00000000 00000001   Complement after operation
         * 5.The original code after operation is 00000000 00000000 00000000 00000001 1
         */
        System.out.println(~-2);//1
        /**
         * 1.First get the original code of 2 00000000 00000000 000000000 00000010
         * 2.Get the complement of 2 00000000 00000000 000000000 00000010
         * 3.Bitwise inversion
         *      11111111 11111111 11111111 11111101    Complement after operation
         * 4.Inverse code after operation 11111111111111111111111111100
         * 5.Original code after operation 10000000 00000000 00000000 00000011 - 3
         */
        System.out.println(~2);//-3
	

​ ▫ Shift arithmetic right > >: the low bit overflows, the sign bit remains unchanged, and the sign bit is used to fill the overflow high bit

​ ▫ Arithmetic shift left < <: the sign bit remains unchanged, and the low bit is supplemented by 0

​ ▫>>> Logical shift right is also called unsigned shift right. The operation rule is: low overflow, high complement 0

		/**
         * -2 Original code 1 00000010
         * -2 Inverse code 1 11111101
         * -2 Complement 1 11111110
         * >> 2
         *  1 11111111  Complement after operation
         *  Inverse code 1 11111110
         *  Original code 1 00000001
         */
        System.out.println(-2 >> 2);//-1

        /**
         * -2 Original code 1 00000010
         * -2 Inverse code 1 11111101
         * -2 Complement 1 1110
         *
         * << 3
         *  1 11110000 Complement after operation
         *  Inverse code 1 11101111
         *  Original code: 1 00010000
         *
         */
        System.out.println(-2 << 3);

10. Calculation
  • Parameter transfer

    public class Dog {
        public static void main(String[] args) {
            PassByValueExample passByValueExample = new PassByValueExample();
            passByValueExample.main();
            PassByValueExample2 passByValueExample2 = new PassByValueExample2();
            passByValueExample2.main2();
        }
    }
    
    /**
     *  passByValueExample.main();  Method to change the field value of the object will change the value of the field of the original object, so it refers to the same object
     *  passByValueExample2.main2();    If the pointer in the method refers to other objects, then the pointers inside and outside the method point to different objects,
     *      Changing the content of the object pointed to by one pointer has no effect on the object pointed to by another pointer
     */
    class Cat{
        public Cat(String name) {
            this.name = name;
        }
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Cat{" +
                    "name='" + name + '\'' +
                    '}';
        }
        String getObjectAddress(){
            return super.toString();
        }
    }
    class PassByValueExample{
        public void main(){
            Cat cat = new Cat("A");
            func(cat);
            System.out.println(cat.getName());//B
    
        }
        public void func(Cat cat){
            System.out.println(cat.getName()+"\t func");//A
            cat.setName("B");
        }
    }
    class PassByValueExample2{
        public void main2(){
            Cat c = new Cat("C");
            System.out.println(c.getObjectAddress());
            func2(c);
            System.out.println(c.getObjectAddress());
            System.out.println(c.getName());//C
    
        }
        public void func2(Cat cat){
            System.out.println(cat.getObjectAddress());
            cat = new Cat("D");
            System.out.println(cat.getObjectAddress());
            System.out.println(cat.getName()+"\t func2");//D
        }
    }
    

5. Control structure

1. Sequence
  • The program is executed line by line from top to bottom without any judgment and jump
2. Branch (if else \ switch)
  • Let the program execute selectively. There are three kinds of branch control

    • If (conditional expression) {...}
    • If (conditional expression) {...} else {...}
    • If (conditional expression 1) {...} else if (conditional expression 2) {...} else {...}
  • switch

    //Starting with java 7, you can use String objects in switch conditional judgment statements. long\float\double is not supported.
     switch structure:
      switch (expression) {
          case Constant 1:
              Execute code block;
              break;
          case Constant 2:
              Execute code block;
              break;
          ...
          default:
              Execute code block;
      }
    
    • If the judgment condition executes the subsequent code, if there is no break, jump out of the current branch; The following statement will continue to be executed without judging the condition

    • The return value of the expression in the switch (expression) must be – (byte\short\int\char\enum\String)

    • The value in the case clause must be a constant, not a variable

    • When the conditions are different and the execution statements are consistent, puncture can be used to complete, which is relatively simple

      switch(month) {
          case 3:
          case 4:
          case 5:
            System.out.println("");
            break;
              
          ...
      }
      
3. Loop (for \ while(){} \ do{}while() \ multiple loop)
  • for basic syntax

    for(Loop variable initialization;Cycle condition;Cyclic variable iteration){
        Circular statement(operation);
    }
    
    • for keyword, indicating loop control
    • for has four elements:
      • Loop variable initialization
      • Cycle condition
      • Cyclic operation
      • Cyclic variable iteration
    • Loop operation, there can be multiple statements here, that is, the code we want to execute in a loop
    • If the loop operation (statement) has only one statement, {} can be omitted, which is not recommended
  • while basic syntax

    Loop variable initialization;
    while(Cycle condition){
        Circulatory body(sentence);
        Cyclic variable iteration;
    }
    
    • while loop elements
    • It's just that the positions of the four elements are different
  • do {...} while() basic syntax

Loop variable initialization;
do{
    Circulatory body(sentence);
    Cyclic variable iteration;
}while(Cycle condition);
  • explain
    • do... while is the keyword
    • There are also four elements of circulation, but the positions are different
    • Execute first and then judge, that is, it will be executed once
    • There is a semicolon at the end
    • The difference between while and do... While: do... While must be executed once
4. Keywords
  • break

    • Jump to the control statement. After the conditions are met, terminate the statement block of a loop
  • Continue (use the same as above, with different functions)

    • The continue statement is used to end this cycle and continue to execute the next cycle

    • When the continue statement appears in the body of a multi-layer nested loop statement, you can use the label to indicate which layer of loop to skip. This is the same as the previous label use rule

      label1: for(int i = 0;i < 100;i++){
          Statement block;
          label2: for(int k = 0;k < 10;k++){
              Statement block;
              break label1;
          }
      }
      
    • Basic grammar

      {
          ...
          continue;
          ...
      }
      
  • return

    • return is used in a method to indicate the method in which you want to jump out
    • If there is a return value, the return value; If there is no return value, the program ends

Topics: Java Back-end