JAVA basic review

Title: basic Java review
date: 2020/8/10

1. Data type

1.1 basic data type

Byte: 1 byte

(byte num1 = 10)

Short: 2 bytes

(short num2 = 20)

int: 4 bytes

(int num3 = 30)

long: 8 bytes

(long num4 = 30L)

float: 4 bytes

(float num5 = 50.1f)

double: 8 bytes

(double num6 = 3.1415926)

Char: 2 bytes

(char name = 'Zhang')

Boolean: 1 bit (false by default)

Note: 1 Byte = 8 bit s

1.2 reference data type

Class, interface and array. The default initialization is null

1.3 data type conversion

From low to high

byte=short=char<int<long<float<double

Low to high: automatic conversion

High to low: Cast

2. Variable scope

2.1 local variables

Exists in a method and must declare and assign an initial value

2.2 instance variables

In addition to methods, initialization values can be omitted in classes. Except for 8 basic types (such as String type), the default value is null, the default value of int type is 0, and the default value of boolean type is false

Class 3.3 variables

Add static, which exists outside the method and inside the class, and can be output directly in the method, such as

static int allClicks=0;

3. Constant

final double PI = 3.14

4. Naming specification of variables

See the name and know the meaning

Local variables and class member variables: the first letter is lowercase and the hump principle, such as monthSalary. Except for the first word, the following words are capitalized

Constants: all letters are capitalized and underlined

Class name: initial capitalization and hump principle

Method name: initial lowercase and hump principle

5. Operator

5.1 arithmetic operators

+, -, /,% (remainder), + + (self increasing), – (self decreasing)

5.2 assignment operator

=

5.3 relational operation method

<,>,>=,<=,==,!=instanceof

5.4 logical operators

&&,||,!

5.5 self increasing and self decreasing

int a = 3;

int b = a++; //After executing this line of code, assign a value to b first, and then increase it automatically

//a = a+1; 

System.out.println(a);

//a = a+1;

int c =++a; //Before this line of code is executed, it is self incremented, and then b is assigned a value
System.out.println(a);
System.out.println(b);
System.out.println(c);
//Results: 5,3,5

5.6 bit operators

A = 0011 1100
B = 0000 1101
-------------
A&B = 0000 1100
A|B = 0011 1101
A^B(XOR: the same is equal to 0 and the difference is equal to 1) = 0011 0001
~B = 1111 0010

Shift right(>>)amount to /2
 Shift left(<<)amount to *2
2<<3 Equivalent to 2*(2*2*2)=16

6. User interaction Scanner

public class test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter data:");
        String str = scanner.nextLine(); //Print the entire line of input
        System.out.println("The output contents are:"+str);
        scanner.close();
    }
}
public class test {
    public static void main(String[] args) {

        //Enter multiple numbers and calculate their sum and average. Press enter to confirm each number. Enter a non number to end the input and output the execution result
        Scanner scanner = new Scanner(System.in);
        int s = 10;
        int count = 0;
        System.out.println("Please enter a number:");
        while(scanner.hasNextInt()){
            int i = scanner.nextInt();
            count = count+1;
            s = s+i;
            System.out.println("Entered"+count+"Number");
        }
        System.out.println("The sum is:"+s);
        System.out.println("The average is:"+(s/count));
        scanner.close();
    }
}
  1. switch multiple selection structure

    switch (expression){
        case value :
            //sentence
            break;
        case value :
            //sentence
            break;
        default:
            //sentence
    }
    

Note: the variable type in the switch statement can be String, byte, short, int or char, and the case label must be a String constant or literal

7. Overloading of methods

7.1 definitions

Overloading is a function with the same function name but different parameters in a class;

7.2 rules for method overloading:

  • The name of the method must be the same;
  • The parameter list must be different (different number, different type or different parameter arrangement order, etc.)
  • The return types of methods can be the same or different
  • Just different return types are not enough to overload methods

8. Command line window execution

1. Compile and generate test Class file

javac test.java

2. Operation

java test

9. Variable length parameter

In the method declaration, an ellipsis (...) is added after the specified parameter type. Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it:

public void test(int... i);

10. Recursion

Recursion is to call yourself and define an infinite set of objects with limited statements:

Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle;

Recursion question: when do I need to call my own method.

11. Array

int[] nums; //1. Declare an array
nums = new int[10]; //2. Create an array int [] num = New Int [10];
nums[0] = 1;  //3. Assign value to array
nums[0] = 2;
nums[0] = 3;
...
nums[10] = 10;
//If an element in the array is not assigned a value, it defaults to 0
//The array length is fixed and cannot be changed once it is determined

11.1 three initialization methods

1. Static initialization

int[] a = {1,2,3};
Man[] mans = {new Man(1,1),new Man(2,2)};

2. Dynamic initialization

int[] a = new int[2];
a[0] = 1;
a[1] = 2;

3. Default initialization of array

Array is a reference type. Its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element is implicitly initialized in the same way as the instance variables

11.2 basic characteristics of array

  • Its length is fixed. Once the array is created, its size cannot be changed
  • Its elements must be of the same type, and mixed types are not allowed
  • The elements of an array can be any data type, including basic and reference types
  • Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object
  • The array itself is an object. In Java, the object is in the heap. Therefore, whether the array saves the original type or other object types, the array object itself is in the heap

11.3 enhanced for loop

public void test1(){

    int[] arrays = {1,2,3,4,5};
    for(int array : arrays){
        System.out.println(array);
    }
}

12. Arrays class

Array tool class java util. Arrays and the methods in the arrays class are static methods decorated with static. When used, they can be called directly using the class name instead of using objects

Common functions;

Assign value to array: fill method

Sort array: sort method, in ascending order

Compare arrays: the equals method compares whether the element values in the array are equal

Find array elements: binary search can be performed on the sorted array through the binarySearch method

13. Bubble sorting

public static int[] sort(int[] array){
    int temp = 0;
    //Outer circle, determine the total number of rounds to judge
    for(int i = 0;i<array.length-1;i++){
        //Inner circle, compare and judge two numbers, and exchange the large number and the small number
        for(int j = 0;j<array.length-1-i;j++){
            if(array[j]<array[j+1]){
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
    return array;
}   

14. Static method call

Static exists in the static method area and is loaded with

public class test {

    public static void main(String[] args) {
        //Static method calls are loaded with the class and called directly
        test.add(10, 20);

        //A non static method call requires a new object to be called
        test test1 = new test();
        test1.de(40, 30); 
    }
   //Static method
    public static int add(int a,int b){
        return a+b;
    }
    //Non static method
    public int de(int a,int b){
        return a-b;
    }
}

15. Constructor

It is the same as the class name and has no return value

Even if a class writes nothing, it will have a method

Once a parameterized construct is defined, if you want to use a parameterless construct, you must display the defined parameterless construct

Using the new keyword is essentially calling the constructor

16. Packaging

16.1 concept

Encapsulation, that is, data hiding. Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding. Property private, accessed through the get/set method.

16.2 function

  • Improve program security and protect data
  • Implementation details of hidden code
  • Unified interface
  • Increased system maintainability

17. Succession

  • In Java, all classes inherit Object directly or indirectly by default
  • The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the real world
  • Classes in Java only have single inheritance, not multiple inheritance (a son can only have one father, and a father can have multiple sons)
  • Inheritance is a relationship between classes. In addition, the relationship between classes includes dependency, composition, aggregation and so on
  • Two classes of inheritance relationship, one is a child class (derived class) and the other is a parent class (base class). The child class inherits the parent class and is represented by the keyword extends
  • The private property method of the parent class cannot be inherited
  • By default, the subclass calls the parameterless constructor of the parent class through super(); And super () must be in the first line of the subclass constructor
  • Cannot inherit a class decorated by final

18. Super and this keywords

18.1 super precautions:

  • super calls the constructor of the parent class, which must be in the first line of the constructor
  • super must only appear in subclass methods or constructor methods
  • super and this cannot call constructor at the same time

18.2 comparison between super and this:

The objects represented are different:

  • this: the object itself is the caller
  • super: represents the application of the parent object

Premise:

  • this: can be used without inheritance
  • super: can only be used in inheritance conditions

Construction method:

  • this(): the construction of this class
  • super(): Construction of parent class

19. Method rewriting

  1. Override: inheritance relationship is required. The subclass overrides the method of the parent class

  2. The name of the overriding method must be the same, the method overridden by the child class and the parent class must be the same, and the method body must be different

  3. The parameter list must be the same

  4. Modifier: the scope can be expanded but not reduced: public > tested > Default > private

  5. Exception thrown: the scope can be reduced, but not expanded

  6. Why to rewrite: the function of the parent class and the subclass are not necessarily required or satisfied

  7. Which methods cannot be overridden:

    static method, which belongs to class, does not belong to instance

    final constant

    private method

20. Polymorphism

  • That is, the same method can adopt many different behavior modes according to different sending objects
  • The actual type of an object is determined, but there are many types of references that can point to the object
  • Conditions for polymorphism: there is inheritance relationship, the subclass overrides the parent method, and the parent reference points to the subclass object
  • When a reference points to a subclass, the methods that the subclass can call are its own or inherit from the parent class
Student s1 = new Student();
  • A parent class can point to a subclass, but cannot call methods unique to a subclass
Person s1 = new Student();   //Where Person is the parent class of Student
  • If the subclass overrides the method of the parent class, the method of the subclass is executed

Precautions:

  • Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
  • Parent and child classes, relation, type conversion exception, ClassCastException
  • Existence conditions: inheritance relationship, method needs to be overridden, and parent class reference points to child class object

21. instanceof keyword

(type conversion) reference type to judge what type an object is

System.out.println(x instanceof y);

If there is a parent-child relationship between x and y, the compilation passes

If the instance type pointed to by x is a subtype of y, the result is true

22. Type conversion

Low to high, direct conversion

//Parent (high) < - rotor (low)
Person obj = new Student();//Where Person is the parent class of Student

High turn low, strong turn

Student student = (Student)obj;

Note:

The parent class refers to an object that points to a child class

Convert a child class to a parent class and transform upward (directly)

Convert a parent class to a child class and transform down (CAST)

Convenient method call, reduce repeated code and be more concise

23. Abstract class

  • The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method. If you modify a class, the class is an abstract class
  • Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes
  • Abstract classes cannot use the new keyword to create objects. It is used to let subclasses inherit
  • If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class

24. Interface

The interface cannot be instantiated because there is no constructor in the interface. All interfaces need to have implementation classes

In fact, all defined methods in the interface are abstract public abstract, and constants are public static final

public abstract void add(String name);

The implementation class can inherit multiple interfaces at the same time through implements, and the methods in the interface must be rewritten

25. Internal class

public class test {

    private int id = 10;
    public void out(){
        System.out.println("This is the method of an external class");
    }

    //Inner class
   public class Inner{
        //Methods of inner classes
        public void in(){
            System.out.println("This is the method of the inner class");
        }

        //Get the private properties of the external class
        public void getID(){
            System.out.println(id);
        }
    }

}

public class Application {
    public static void main(String[] args) {
        //Create an object of an external class
        test t1= new test();
        //Instantiate the inner class through the outer class
        test.Inner inner = t1.new Inner();
        //Use its method
        inner.in();  //The print result is "this is the method of the inner class"
        inner.getID();  //The print result is "10"
    }
}

Local inner class

public class test {

    //Local inner class
   public void method(){

       class Inner{
           public void in(){
               
           }
       }
   }
}

Anonymous Inner Class

public class test {

    public static void main(String[] args) {
        //There is no name to initialize the class, so there is no need to save the instance to the variable
        new Apple().eat();
    }
}


class Apple{
    public void eat(){
        System.out.println("1");
    }
}

26. Exception

Java handles the object in the exception and defines a base class java Lang. trowable is the superclass of all exceptions

Many Exception classes have been defined in the Java API. These Exception classes are divided into two categories: Error and Exception

26.1 Error

The Error class object is generated and thrown by the Java virtual machine. Most errors have nothing to do with the operation performed by the coder

Java virtual machine running error. When the JVM does not continue to execute the memory resources required by the operation, OutOfMemoryError will appear. The JVM will generally choose thread termination

In addition, when the application is executed in the virtual machine view, such as class definition error (NoClassDefFoundError) and connection error (LinkageError).

26.2 runtimeException (runtime exception)

These exceptions are not checked. The program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions from a logical point of view:

ArrayIndexOutOfBoundException (array subscript out of bounds)

NullPointerException (control exception)

Arithmeticexception (arithmetic exception)

Missingresourceexception (missing resource)

Classnotfoundexception (class not found)

26.3 difference between error and Exception

Error s are usually catastrophic and fatal errors that cannot be controlled and handled by the program. When these exceptions occur, the java virtual machine (JVM) will generally choose to terminate the thread; exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program

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

        int a = 1;
        int b = 0;

        //Suppose you want to catch multiple exceptions: throwable > exception from small to large, and the shortcut key ctrl+alt+T
        try{//try monitoring area
            System.out.println(a/b);
        }catch (Error e){ //Catch (the type of exception you want to catch)
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        } finally{//The aftercare work will be executed anyway. It is generally used to close IO resources
            System.out.println("finally");
        }
    }
}

Keywords: Java

Added by phpScott on Fri, 17 Dec 2021 07:49:57 +0200