Define variable + modifier all

Definition and use of variables

package stu.aistar.day02;

import java.util.Date;

/**
 * This class is used to demonstrate the definition and use of variables
 */
public class VarInitDemo {
    public static void main(String[] args) {
        byte b = 127;

        short s = 100;//It is used infrequently

        //Integer type commonly used in development - int,long
        //What values can int type initialize
        int a = 100;

        //Store a binary, as long as 0b binary, 1010 corresponds to decimal
        //The int type in java represents decimal data
        //1010 = 1*2^3+1+2^1 = 10
        int a1 = 0b1010;
        System.out.println(a1);

        //java uses single quotation marks to represent a character
        //'a' - > char type - > int type
        //ascii code 97 corresponding to 'a'
        //The ascii code corresponding to 'A' is 65
        //The ascii code corresponding to '0' is 48
        int a2 = 'a';
        System.out.println(a2);

        //The symbol starting with 0 in java is octal
        //Octal conversion decimal 032 = 3 * 8 ^ 1 + 2 * 8 ^ 0 = 26
        int a3 = 032;
        System.out.println(a3);//26

        //Long integer - long

        //int type - > long type
        long x1 = 100;

        //It is recommended to define long by implicit conversion
        long x2 = 200L;

        //jdk7.x provides - just to enhance the readability of numbers
        long x3 = 3_14_15_926L;

        System.out.println(x3);

//        Date date = new Date(3L*24*60*60*100*1000*1000*2000);
//        System.out.println(date);

        //Floating point numbers - are not used for accurate calculations
        //The following java.math.Decimal class solves the problem of precision loss during decimal calculation
        double d = 1.75;

        //double is recommended
        double d2 = 5.67D;

        //The accuracy of float is 7 or 8
        //The precision of double is 16

        //Cast double type to float type
        float f = (float) 3.14;

        //Implicit conversion
        float f2 = 3.14F;
        System.out.println(f2);

        //supplement
        //When numbers are calculated, they will be converted into binary for calculation
        //When calculating decimals, they are still irreversible
        //0.8999999999999999
        System.out.println(2.0-1.1);

        //0.9
        System.out.println(2.0f - 1.1f);

        //int->float  ×
        //int->double √
        int n = 123456789;
        float ft = n;
        System.out.println(ft);//1.23456792E8

        double db = n;
        System.out.println(db);//1.23456789E8

        float f3 = 1.234567565f;
        System.out.println(f3);//1.2345675

        //Define boolean type
        boolean flag = true;

        System.out.println(flag);

        //The most special is the char type

        char c = 65;
        System.out.println(c);
    }
}

char type

java uses single quotation marks to represent char type and double quotation marks to represent string

The underlying coding of java is unicode coding, and the char type is also unicode coding

unicode code is double byte [16 bit], so it stores a Chinese character

What is the relationship between ascii code and unicode code?

Different countries have different symbolic representations, so ascii code [0127] is not enough. Therefore, unicode[065535] code was born, almost

Contains symbols of all countries. unicode code contains ascii code. char type will be converted into ascii code for calculation

code

package tech.aistar.day02;

/**
 * This class is used to demonstrate: char type
 *
 * @author: success
 * @date: 2021/7/16 9:14 morning
 */
public class CharDemo {
    public static void main(String[] args) {
        //java uses single quotation marks to represent char type
        //The space size of char is also determined
        char c = 'a';
        System.out.println(c);

        //hexadecimal
        //By the numbers 0-9 or the letters a-f/A-F, the letter a represents the number 10

        //cmd - enter native2ascii - > enter Chinese
        char c2 = '\u34af';
        System.out.println(c2);

        //The bottom layer of char uses unicode coding, so it stores a Chinese character
        char c3 = 'Star';
        System.out.println(c3);

        char c4 = 48;
        System.out.println(c4);

        int m = 48;
        char c5 = (char) m;
        System.out.println(c5);

        //char type will be converted into ascii code for calculation
        //'a' = 97,'A' = 65,'0' = 48
        //Calculation of char type - advanced part
        char n1 = 'a' + 1;//ok
        System.out.println(n1);// 'b'

        char cc = 'a';
        char nn = (char) (cc + 1);
        System.out.println(cc);

        //char->int
        int result = 'a' + 'b';//ok
        System.out.println(result);//195
    }
}

Assignment method of variable

  1. Single assignment int a = 10;

  2. Assignment by expression

    int a = 10;
    int b = 20;
    //Expression: a legal statement consisting of literal quantities or variables and operation symbols
    int result = a + b;
    
  3. Chained assignment

    int a=10,b=20,c=30;//Three variables are declared and initialized at the same time
    
    int a,b,c = 100;//Here is only the assignment of c. If a local variable is not assigned, it cannot be used
    
  4. Variables can be defined before assignment

    int a;
    a = 10;
    a = 20;
    System.out.println(a);
    
  5. Assignment by method - temporary understanding

    int result = getResult();
                   
    /**
         * Customize a method - never put it in the main method
         * java Syntax - methods cannot be defined internally
         * @return integer
         */
    public static int getResult(){
      return 100;
    }
    

Classification of variables

  1. Local variable - defined inside the method body

    The scope of use is in the nearest {} where it is located

  2. Global variable - a variable defined outside the method body

    Lifecycle - object oriented

constant

Variables decorated with final - constants - immutable quantities

grammar

final Data type variable [= Initial value];
package tech.aistar.day02;

/**
 * This class is used to demonstrate: local variables and global variables
 *
 * @author: success
 * @date: 2021/7/16 10:04 morning
 */
public class LocalVarAndGlobalDemo {
    //Define all variables
    static int c = 100;//Static variable - Unknown

    public static void main(String[] args) {

        //Code block
        //Local variable - defined inside the method body
        int a= 10;
        {
//            The scope of use is in the nearest {} where it is located
            int b = 20;

            System.out.println(a);//ok

            System.out.println(b);//ok
        }

        //The scope of use is in the nearest {} where it is located

        //System.out.println(b);//error

        //Accessing global variables
        System.out.println(c);

        //Define a constant - an immutable quantity
        final int s = 100;
        //s = 200;


        //final - b must be immutable
        final byte b = 100;

        byte result = b + 1;//ok

    }
}

operator

Arithmetic operator

1. + 
   java Unique overload in language[It has multiple meanings]Operator of
   An addition operation between values,If it does"character string",Indicates splicing[Later you will know that the splicing efficiency is very low]
  
2. - subtraction   * multiplication
  
3. / division[It is only the type of results that need to be paid attention to in the process of coordination calculation] - Rounding
  
4. % Surplus/model
   /and%Combined use,You can get the value in any bit of a number.
  
5. += -= *= /= %=
   Future know:Try not to use it in development,Not an atomic operation,Causing unsafe multithreading.
   The bottom layer will judge whether a type of narrowing operation is required[Cast operation of type]
     
6. ++and--
   front++/after++ - The variable itself will increase by 1
   front--/after-- - The variable itself subtracts by 1
   Future know:Try not to use it in development,Not an atomic operation,Causing unsafe multithreading.
   The bottom layer will judge whether a type of narrowing operation is required[Cast operation of type]

Comparison operator

> <= >= < !=
The result of comparison is a boolean Type is enough

Logical operator

  1. &&- logical and, short circuit and. Functions are not used for calculation, but for connecting conditions [multiple conditional expressions (including comparison operators)]

    True - all conditional expressions return true

    Short circuit characteristic: when the conditional expression on the left can determine the whole result, the subsequent conditional expression will not be executed

    Recommendation: put the conditional expression result most likely to be false on the far left - improve the execution efficiency of the code

  2. ||- logical or, short circuit or. Functions are not used for calculation, but for connecting conditions [multiple conditional expressions (including comparison operators)]

    True - as long as one expression is true, the result is true

    Short circuit characteristic: when the conditional expression on the left can determine the whole result, the subsequent conditional expression will not be executed

    Recommendation: put the conditional expression that is most likely to be true on the left - improve the execution efficiency of the code

  3. ! - Logical non, true becomes false,false becomes true

Bitwise Operators

  1. &- bitwise &, non short circuit and, are mainly used for calculation, but can be used to connect conditional expressions

    Calculation: all are 1, the result is 1. As long as there is 1 0, the result is 0

    Connection condition: true - all conditional expressions return true

    10 & 8 = 8
                        
    Decimal numbers are constantly divided by two,Until quotient is 0,Then reverse the remainder - 1010
    10 / 2 = Quotient 5......Yu 0
    5 /  2 = Quotient 2 ...... 1
    2/  2 =  1 ........ 0
    1/2  =   0 .........1
                        
      1    0    1   0
                        
    & 1    0    0   0
    ------------------
      1    0    0   0  -> Corresponding decimal 8
    
  2. |- bitwise OR, non short circuit or, is mainly used for calculation, but can be used to connect conditional expressions

    Calculation: as long as there is a 1, the result is 1

    Connection condition: true - as long as there is a condition expression that is true

    10 | 8 = ?
    
      1    0    1   0
    
    | 1    0    0   0
    ------------------
      1    0    1   0  -> Corresponding decimal 10
    
  3. XOR^

    Function: for calculation - the same is 0 and the difference is 1

    10 ^ 8 = 2 
    1    0    1   0
                   
    | 1    0    0   0
    ------------------
      0    0    1   0  -> 2
    

10 ^ 8 ^ 8 = 10

0    0    1   0 
1    0   0    0
-----------------
      1   0    1    0    -> 10

Conclusion: a number consecutively exclusive or the same number twice results in itself
Encryption and decryption can be performed

Written test questions: Exchange the values of two variables,Third party variables are not allowed
package tech.aistar.day02;

   /**
 * This class is used to demonstrate: written test questions: exchange the values of two variables, and third-party variables are not allowed
 *
 * @author: success
 * @date: 2021/7/16 11:09 morning
 */
public class ChangeVarValue {
    public static void main(String[] args) {
        //1. Use third party variables
        int a = 10;
        int b = 20;
        int temp = a;
        a = b;
        b = temp;
        System.out.println("a:"+a);
        System.out.println("b:"+b);

           //A number is exclusive or the same number twice, and the result is itself
        int m = 100;
        int n = 200;
        m = m ^ n;//m = 100 ^ 200
        n = m ^ n;//n = 100 ^ 200 ^ 200 = 100
        m = m ^ n;//m = 100 ^ 200 ^ 100 = 200

           System.out.println("m:"+m);
        System.out.println("n:"+n);

           //Self created writing (success exclusive) - not recommended - to prevent novices from not understanding
        int x = 100;
        int y = 200;

           //y = 100 ^ 200 ^ 200 = 100
        y = x ^ (x = y) ^ y;

           System.out.println("x:"+x);
        System.out.println("y:"+y);
    }
}

4. Take the inverse ~, 1 becomes 0, and 0 becomes 1

5. Complement negative numbers exist in the form of complement in the computer

Complement = Inverse code + 1;
Inverse code = Original code symbol bit unchanged,The other bits are reversed in turn
 Sign bit - The highest bit represents the sign bit.1 Represents a negative number,0 It represents a positive number.
The inverse code itself is meaningless,It exists to calculate the complement

Complement of positive numbers,Inverse code,The original code is itself.

Calculate it:-10 What is the binary of?-10 What's your complement?

computational procedure:
1. -10 Original code
   10000000 00000000 00000000 00001010

2. -10 Inverse code of
   10000000 00000000 00000000 00001010
   11111111 11111111 11111111 11110101

3. -10 Complement of = Inverse code+1
   11111111 11111111 11111111 11110101
 +                                   1
  -------------------------------------
   11111111 11111111 11111111 11110110    ->  -10 Binary

calculation~9
00000000 00000000 00000000 00001001
11111111 11111111 11111111 11110110  -> ~9 Negative result

-10 = ~9

conclusion:-(x+1) = ~x

6. Shift operation

Written test questions - the operation with the highest computational performance. Many of the jdk source code are shift operations

<< Move left
2<<2 => 0010 << 2 = 1000 = 8
 Original title:Please calculate the third power of 2 in the way of maximum performance.
>> Move right with symbol,How many bits to the right,Then fill the sign bit in the highest bit
-10 >> 2 = -3
11111111 11111111 11111111 11110110 >> 2
11111111 11111111 11111111 11111101 -> Negative binary,The highest bit is 1

00000000 00000000 00000000 00000010 Reverse ~2=-3

>>> Move right without symbol,How many bits to the right,Fill 0 at the top
 -10 >>> 2
 11111111 11111111 11111111 11110110 >> 2

 00111111 11111111 11111111 11111101 -> Calculate decimal
 01000000 00000000 00000000 00000000
   -                                  3
-----------------------------------------
     1073741821

Exercise - 15 > > 2 - 15 > > > 2

-15 = ~14

11111111...... 0001 >>> 2

00111111 11111111 11111111 11111101

00111111 11111111 11111111 1111100 = 1073741820

Method - Method

It's very important. If you don't keep up, you'll be out

Equivalent to function in other languages, function is used to encapsulate the logic of code

A piece of code is encapsulated in the method, which is convenient for reuse and improves the maintainability of the code

grammar

Modifier return type method name([parameter list]) [throws List of exceptions that can be thrown]{..Method body...}

At this stage:
Modifier return type method name([parameter list]){..Method body...}

Modifier

Access modifier

Function: determines the scope of this method that can be called

  1. Public - public. If a method is modified by public, it means that the method can be called elsewhere
  2. Private - private, which can only be called inside the current class - reflecting "encapsulation" - not public
  3. default
  4. Protected

Special modifier [content of superoutline]

  1. Static - static

    If you use static modified methods - static methods

    If there is no static modified method - non static method

  2. Whether the method is static or not determines how the method is called

Return type

  1. There is a return type

    It can be eight basic data types or object types [built-in object types or user-defined object types]

    The final exit of the method body must have a return value

    return Action 1 - Returns the final execution result of the method
           Action 2 - Used to end the entire method
    
    What is the return type of a normal method,What should be the result type of the return value
     Abnormal conditions - Supports automatic conversion of types and forced type conversion.
    
    When called - You need to use data types and variables to accept the results of this method call.
               What is the return type of the method,Just use what type to define.Of course, it also supports type conversion
    
  2. No return type - void

    No need to use return  + Return value;
    
  1. How to choose?

If the execution result of a method may be used in another place, it must be defined as having a return type

If a method is only for output, just define void

public static int test01(int m,int n){
    //code...
  return m and n Maximum common divisor of
                    
 //System.out.println (common divisor)

}
//int m = test01(20,12);//m->4

public static int test02(int m,int n){
int common divisor = test01(m,n);
return mn / common divisor;} int n = test02(20,12);// n->60=2012/4=60

Method name

Refer to as like as two peas.

Identifier - the name given to a class, package, variable, or method

parameter list

  1. No parameter list
  2. With parameter list
  3. Variable length list

How to define methods

  1. Methods can no longer be defined in the method body
  2. The main method is still the main entry of the program
  3. If a custom method wants to be called, it must eventually be called in the main method

Method

Depends on whether the method is static or non static - static

package tech.aistar.day02.method;

/**
 * This class is used to demonstrate the definition of methods
 *
 * @author: success
 * @date: 2021/7/16 2:20 afternoon
 */
public class MethodHelloDemo {
    /**
     * main - It is still the main entrance of the program
     * @param args
     */
    public static void main(String[] args) {
        //Methods in a class - members in a class
        //Static - when static members are initialized
        //When are static methods initialized- When the JVM loads classes into memory, it immediately allocates space and initializes all static members
        //At this stage, there is no concept of object at all, only class
        //Conclusion - static members belong to class and are initialized once
        //Who belongs to, who calls!

        //1. Call a static method directly through the class. Method name ([parameter])
        //Class - the current class in which the static method resides
        MethodHelloDemo.sub();

        //Non static - > when non static members are initialized?
        //When you encounter the syntax of creating objects, each time you create an object, you will allocate space and initialize to their non static members
        //If the object is not created, these non - static members will not be initialized
        //Conclusion: non - static members belong to objects. To whom and by whom

        //2. Non static method - call through object
        //The method in which class is called will create the object of which class
        //The following OO knowledge points - > class name variable = new class name ();

        //Created a MethodHelloDemo object, m is the object name
        MethodHelloDemo m = new MethodHelloDemo();
        m.add();
    }

    /**
     * Defines an exposed non static method with no return type
     */
    public void add(){
        System.out.println("add...");
    }

    /**
     * Defines an exposed static method with no return type
     */
    public static void sub(){
        System.out.println("sub...");
    }
}
  1. Static methods can only be called directly

  2. In non static methods, non static methods and static methods can be called directly

  3. General principles - class names. Static methods or objects. Non static methods

  4. Static methods are owned by classes, while non static methods are owned by objects

  5. The static method is that when the jvm loads the class into memory, it will be allocated space and initialized immediately, and the chance is only once

    Non static methods must wait until the object is created before they can be allocated space and initialized

>package tech.aistar.day02.method;

>/**
>* This class is used to demonstrate:
>*
>* @author: success
>* @date: 2021/7/16 2:43 afternoon
>*/
>public class StaticDetailDemo {

  //Global variables are defined
  //Attribute, method = > member
  //Non static properties
  int n = 10;//Space will be allocated and initialized only when the object is created

  //Static properties - initialization takes precedence over static methods
  static int m = 100;

  public static void main(String[] args) {
      //At this time, n has not been initialized
      //System.out.println(n);// Compilation error

      //System.out.println(m);

      //Call test03 - non static
      StaticDetailDemo s = new StaticDetailDemo();
      s.test03();

      System.out.println(s);
  }
  //Non static
  public void test01(){
      System.out.println("test01..");
  }

  //Static
  public static void test02(){
      int n = 10;
      System.out.println("test02...");

      //You can call your own custom methods in the custom methods
      //1. Another static method test04
      StaticDetailDemo.test04();
      //Static methods can be called directly in static methods
      test04();

      //2. Another non static method test03
      StaticDetailDemo s1 = new StaticDetailDemo();
      s1.test03();
  }

  public void test03(){
      //static int n = 20;// Static local variables are not allowed in non static methods
      System.out.println("test03..");

      //A static method called class name is called in a non static method.
      //StaticDetailDemo.test04();//ok

      test04();//ok

      //How about directly calling another non static method in a non static method- You must need an object to call
      test01();//ok

      //In fact, a keyword this is omitted

      //this represents the current object
      //Current object - the object that calls the method [test03]
      //this.test01();
      System.out.println(this);
  }

  public static void test04(){
      System.out.println("test04..");
  }
>}

Method call supplement

  1. The caller of a method and the definer of a method are in the same class

  2. The caller of the method and the definer of the method are not in the same class, but they are still in the same package

    Only general principle class names. Static methods or objects. Non static methods can be used

  3. Method callers and method definers exist in different classes under different packages

    You must first import the package through the import keyword

    When using classes in the jdk, except those under the java.lang package, which do not need to be imported manually, all other packages need to be imported first

  4. Recursive algorithm - wrong writing - directly call yourself inside the method

private and public this option is used

public class Tool class of ox fork{
   
  public static void Method of ox fork 01(){
    
    //It must be called by someone outside
    //The business logic of the internal code is very responsible and consists of many small functions
    Small ox fork method 01();
    //...
    //..
    //...
  }
  
  private static void Small ox fork method 01(){
    //It specially encapsulates small functions
  }
  
   public static void Ox fork method 02(){
    
    //It must be called by someone outside
     //The business logic of the internal code is very responsible and consists of many small functions
     Small ox fork method 01();
     //...
     //...
     
     //...
  }
}

Tags: Java

Posted on Tue, 09 Nov 2021 02:49:12 -0500 by mushroom