Summary of JavaSE core knowledge points

1. Method definition with parameters

Format: public static void method name ( parameter ) {...}

Format (single parameter): public static void method name ( data type variable name ) {...} 

public static void isEvenNumber (int number) {......}

2. Features of the interface

1) The interface uses the keyword interface to modify the public interface interface name {} 

2) The class implements the interface with implements to represent the public class class name implements interface name {}

3) The interface cannot be instantiated

How to instantiate the interface? Referring to the way of polymorphism, by realizing the instantiation of class objects, this is called interface polymorphism.

The form of polymorphism: concrete class polymorphism, abstract class polymorphism , interface polymorphism .

Prerequisites of polymorphism: inheritance or implementation relationship; method rewriting; parent (class/interface) reference pointing to (child/implementation) class object

4) The implementation class of the interface

Either override all abstract methods in the interface

either an abstract class

5) The member variables in the interface can only be constants, and are statically modified, (generally, static final is modified by default) , there is no non-abstract method in the interface (generally, public abstract is modified by default) , and the interface has no construction method, because the interface is mainly What abstracts behavior has no concrete existence.

6) If a class has no parent class, it inherits from the Object class by default

7) When an interface uses a member method, it cannot have a method body : Interface abstract methods cannot have body y

3. The relationship between classes and interfaces

1) The relationship between classes and classes

Inheritance relationship, only single inheritance, but multi-layer inheritance

2) The relationship between classes and interfaces

The implementation relationship can be single-implemented or multi-implemented, and multiple interfaces can be implemented while inheriting a class

3) The relationship between interface and interface

Inheritance relationship can be single inheritance or multiple inheritance

4. String line = sc.nextLine(); used to obtain keyboard input string data

5. String construction method

public String(): Creates a blank string object without any content

public String(char[] chs): Create a string object based on the contents of the character array

public String( byte [] by s): Create a string object based on the content of the byte array

String s= " abc " ;Create a string object by direct assignment, the content is abc (recommended)

6. Set collection characteristics

1) The set collection does not contain a collection of duplicate elements

2) There is no method with an index, so ordinary for loop variables cannot be used

3) Hashset: does not make any guarantees about the iteration order of the collection

7. Traversal of the Map collection (method 1)

1) Get the set of all keys and implement it with the keySet() method

2) Traverse the collection of keys, get each key, and use the enhanced for loop to achieve

3) Find the value according to the key, and use the get (Object key) method to achieve

8. Access characteristics of internal classes

1) The inner class can directly access the members of the outer class, including private

2) To access the members of the inner class, the outer class must create an object

9. The Math class has no construction method. If you want to use the members of the class, check whether the members of the class are static. If so, you can call them directly through the class name

10. Methods of setting and obtaining thread priority in the Thread class

1) public final int getPriority(): returns the priority of this thread

2) public final void getPriority(int newPriority): Change the priority of this thread

The default thread priority is 5; the thread priority range is 1-10;

A high thread priority only means that the thread has a high probability of obtaining CPU time slices, but you can see the effect you want only when the number of times is relatively large, or when you run it multiple times.

11. Compared with inheriting the Thread class, the benefits of implementing the Runnable interface

1) Avoid the limitations of Java single inheritance

2) It is suitable for multiple identical program codes to process the same resource, and effectively separates threads from program code and data, which better reflects the object-oriented design idea.

12. Synchronized code block

Lock multiple statements to operate shared data, which can be realized by using synchronized code blocks

1) format: synchronized(arbitrary object) {

    Code for multiple statements to manipulate shared data

}

2) synchronized (any object) : it is equivalent to locking the code, and any object can be regarded as a lock.

Advantages and Disadvantages of Synchronization

3) Benefits: Solve the data security problem of multi-threading

4) Disadvantages: When there are many threads, because each thread will judge the lock on the synchronization, this is very resource-intensive, and it will reduce the efficiency of the program invisibly.

13. Three elements of network programming

1) IP address: uniquely identifies the device in the network

2) Port number: uniquely identifies the application in the device

3) Protocol: Both communication parties must follow the corresponding protocol at the same time to complete data exchange. Common protocols include UDP protocol and TCP protocol

14. UDP send data

1) Create a Socket object (DatagramSocket) at the sending end

2) Create data and package the data

3) Call the DatagramSocket object method to send data

4) Close the sender

15. UDP receiving data

1) Create a Socket object (DatagramSocket) at the receiving end

2) Create a packet for receiving data

3) Call the DatagramSocket object method to receive data

4) Parse the data packet and display the data on the console

5) Close the receiver

17. Three situations where objects cannot be created

1) The first type: a private object modified by private

The constructor is private and cannot create objects

Reason: Because the subclass wants to create an object and inherit the parent class. You have to call the constructor of the parent class. At this time, the constructor of the parent class is private , and objects cannot be created.

2) The second type: abstract class

Reason: The method in the abstract class (parent class) is likely to be an abstract method. If the abstract class can also create objects, after the object is created, it calls its own method, but the method at this time has no method body, and the object created at this time is meaningless, so the abstract class cannot create objects .

Take the example of animal, an animal is an abstract class, and an abstract class is not a concrete thing. If you create an animal object, it may be a cat or a dog, so it is not sure.

3) The third type: interface

Reason: The interface cannot create objects, because member variables are constants by default. The construction method is used to initialize and assign values ​​​​to member variables. At this time, member variables are constants, so they are meaningless. Therefore, the interface has no constructor and cannot create objects.

16. The steps of TCP sending data

1) Create the client's Socket object (Socket)

2) Get the output stream and write data

3) Release resources

17. The steps of TCP receiving data

1) Create a server-side Socket object (ServerSocket)

2) Listen to the client connection and return a Socket object

3) Get the input stream, read the data, and display the data on the console

4) Release resources

18. Problems in network programming

Client: The data comes from a text file and receives server feedback

Server: Write the received data to a text file and give feedback

A problem occurred: the program has been waiting

Reason: The method of reading data is blocking

Solution: Customize the end tag; use the shutdownOutput() method (recommended)

19. The benefits of generics

1) Advance the runtime problem to the compilation period

2) Avoiding mandatory type conversion

20. Member variables: variables outside the method in the class, local variables: variables in the method

21. Points to note when using the static keyword

1) The this keyword cannot be used in static methods

2) Non-static methods cannot be called directly in static methods

3) Local variables cannot be declared using the static keyword

4) The main method must use static declaration

5) Only inner classes can be declared using the static keyword

22. final keyword

1) Modified method: Declare that the method is the final method and cannot be overridden

2) Modified variable: Indicates that the variable is a constant and cannot be reassigned

3) Modified class: Indicates that the class is the final class and cannot be inherited

4) The variable is a basic type: the final modification means that the data value of the basic type cannot be changed

5) The variable is a reference type: final modification means that the address value of the reference type cannot be changed, but the content in the address can be changed

23. The difference between abstract class and interface

An abstract class is an abstraction of things (including behavior and attributes), while an interface is an abstraction of behavior.

Examples of doors and alarms

Door: There are two actions of open() and close(). At this time, we can use abstract classes and interfaces to define this abstract concept

//抽象类

public abstract class door{

      public abstract void open();

      public abstract void close();

      public abstract void alarm();

All subclasses that inherit this abstract class have the alarm function, and some doors do not need the alarm function at all

//接口

public interface Door{

    void open();

    void close();

    void alarm();

}

The two methods of open and close must also be implemented. Maybe this class does not have the two functions of open and close at all, so open and close should be placed in the abstract class, and alarm should be placed in the interface.

24. All the constructors in the subclass will access the parameterless constructor in the parent class by default, why?

1) Because the subclass will inherit the data in the parent class, it may also use the data of the parent class. Therefore, before the subclass is initialized, the initialization of the parent class data must be completed first.

2) The first statement of each subclass constructor defaults to: super()

25. The difference between String, StringBuffer and StringBuilder

1) The String class is an immutable class, that is, once a String object is created, the sequence of characters contained in the object cannot be changed until the object is destroyed . For example, when assigning a value to a again, instead of reassigning the instance object in the original heap, a new instance object is generated and points to the string "456", and a points to the newly generated instance object, the previous instance The object still exists and will be garbage collected if not referenced again.

2) The StringBuffer object represents a variable character string. When a StringBuffer is created, it can be changed through methods such as append(), insert(), reverse(), setCharAt(), and setLength() provided by StringBuffer. A sequence of characters for a string object. The StringBuffer object is a variable character string, it does not regenerate an object, and a new string can be connected to the original object.

3) The StringBuilder class also represents mutable string objects. In fact, StringBuilder and StringBuffer are basically similar, and the constructors and methods of the two classes are basically the same. The difference is: StringBuffer is thread-safe, but StringBuilder does not implement the thread-safe function, so the performance is slightly higher.

26. When using the wrapper type, if you do an operation, it is best to judge whether it is null

27. Two conventional Map performances

1) HashMap: Suitable for inserting, deleting and locating elements in the Map.

2) Treemap: suitable for traversing keys in natural order or custom order .

3) HashMap is usually faster than TreeMap (due to the data structure of the tree and hash table), it is recommended to use HashMap more, and use TreeMap when the Map that needs to be sorted.

28. Anonymous inner class

Premise: There is a class or interface, where the class can be a concrete class or an abstract class

Format: new class name or interface () {

override method;

};

Essence: It is an anonymous object of a subclass that inherits this class or implements this interface

29. Polymorphism problem: What does it mean to look at the left side when compiling and look at the right side when running?

Polymorphism: People  p = new Children();

For member methods: compile to the left, and run to the right.

For member variables: look at the left when compiling and running. That is, member variables do not have polymorphic characteristics.

Static methods and variables: Look at the left side when compiling and running, the same as member variables.

When compiling, check whether the object on the left has this method, and when running, see who the new object is , and call whose method

30. The difference between object reference and object

Demo demo=new Demo();  

This sentence actually includes four actions:

1) "new Demo" on the right uses the Demo class as a template to create a Dem object in the heap space.

2) The () at the end means that after the object is created, the constructor of the Demo class is called immediately to initialize the newly generated object.

3) "Demo demo" on the left creates a Demo class reference variable, which is stored in the stack space. That is, the object reference used to point to the Demo object.

4) The "=" operator makes the object reference point to the Demo object just created.

31. Rewriting and overloading

Overriding means that the method of the subclass overrides the method of the parent class. The method name and parameters are required to be the same. Overloading is two or more methods in the same class that have the same method name but different parameters. The method body is also different

32. Several implementations of java multithreading:

1 ) Inherit the Thread class and rewrite the run method

2 ) Implement the Runnable interface, rewrite the run method, and implement the instance object of the implementation class of the Runnable interface as the target of the Thread constructor

3 ) Create threads through Callable and FutureTask

4 ) Create threads through the thread pool

33. The difference between beak, return, and continue

break: directly end a loop and jump out of the loop body. The statements in the loop body after break will not continue to execute, and the statements outside the loop body will be executed

continue: Abort this cycle and continue to the next cycle. The statements in the loop body after continue will not continue to execute, the next loop will continue to execute, and the statements outside the loop body will be executed

return: The function of return is to end a method. Once the return is executed in the loop body, the method will end, and the loop will naturally end. Unlike continue and break, return directly ends the entire method, no matter how many loops this return is in.

34. Variable assignment problem

public class Demo {
    //成员变量
     int a;
     Integer b;

    public static void main(String[] args) {
        Demo demo=new Demo();
        //基本数据类型
        System.out.println("-------成员变量--------");
        System.out.println("基本数据类型:"+demo.a);
        //引用数据类型
        System.out.println("引用数据类型:"+demo.b);
        System.out.println("-----------------");
        //局部变量
        int c=1,d=2,temp;
        temp=c>d?c:d;
        System.out.println("局部变量c的值为:"+c);
        System.out.println("局部变量d的值为:"+d);
        System.out.println("局部变量temp的值为:"+temp);
    }
}

1) Member variables do not need to be assigned an initial value. When creating a new object, the system will set an initial value by default. The basic data type is assigned 0, and if it is a reference type member variable, it will be assigned a value of null .  

 2) The local variable in the method (including the main method, the variable in the main method is also a local variable, but its life cycle is as long as the global variable) executes the stack operation, and must . c and d are involved in the calculation, so they must be initialized, and temp is only responsible for receiving the value of the expression, and does not need to be initialized.

Note: It is recommended that regardless of member variables or local variables, they should be assigned initial values ​​after definition

35. Constant assignment problem

public class Demo2 {
    final  int i;
    static final int j=40;

    public Demo2() {
        i=20;
    }

    public static void main(String[] args) {
        Demo2 demo2=new Demo2();
        System.out.println("无static修饰的常量:"+demo2.i);
        System.out.println("有static修饰的常量:"+demo2.j);
    }
}

1) A constant modified with the final keyword can be initialized when it is defined, or it can be initialized in the constructor of the class 

2) Constants modified with static and final keywords at the same time must be initialized when redefining

36. Can the values ​​of static constants, ordinary constants, static variables, and ordinary variables be changed?

public class Demo3 {
    //普通常量和静态常量,无论哪种常量,赋值之后,其值就不能被改变
    final int a =10;
    static final int b=20;
    //普通变量和静态变量
    static int c=30;
    int d=40;

    public static void main(String[] args) {
        Demo3 demo1=new Demo3();
        Demo3 demo2=new Demo3();
        demo1.d=45;
        demo2.c=35;
        System.out.println("第一实例调用普通变量的值"+demo1.d);
        System.out.println("第一实例调用静态变量的值"+demo1.c);
        System.out.println("第二实例调用普通变量的值"+demo2.d);
        System.out.println("第二实例调用静态变量的值"+demo2.c);
    }
}

 

1) Ordinary constants and global constants, no matter what kind of constant, once assigned, its value cannot be changed 

2) It can be seen that no matter how many instances of static variables (class variables) are created to change their values, their values ​​will remain in the last changed state (c value == 35). The ordinary variable (instance variable) first becomes the changed value (d==45), and finally returns to the value before the change (d==40).  The value of a static variable is unique (there is only one copy in memory, the JVM only allocates memory once for the static, and the memory allocation of the static variable is completed during the process of loading the class ), but it is not constant. Within its scope, only There is a value, no matter where it is called in the scope, no matter how many objects are instantiated, the same memory address is changed, which is shared by all instances of the class . For instance variables, every time an instance is created, memory will be allocated for instance variables. Instance variables can have multiple copies in memory, which are independent of each other and do not affect each other.

3) Generally, static variables are used when sharing values ​​​​between objects or when accessing variables is convenient. Static variables (static methods) are usually used to provide shared data (methods). For example: pi, in addition to the need for this value in the circle class, it also needs to be used in another ball class. At this time, there is no need to create π in the two classes at the same time, because the system will allocate the two static values ​​that are not defined in the same class to different memory spaces. To solve this problem, π can be made static, where it is shared in memory.

4) For static variables, you can use the class name. Variables to access directly (recommended), or through object instances (not recommended). Static variables (methods) should not be instantiated and called as much as possible, which will cause waste of memory space. For instance variables, they are generally accessed through object instances. Static variables (methods) belong to classes and non-static variables (methods) belong to instances of classes.

Note: The follow-up will continue to supplement and improve the content

Guess you like

Origin blog.csdn.net/qq_53860947/article/details/125204735