Interview: Java Basics

Table of contents

1. The underlying structure and principle of HashMap

1、JDK7

2、JDK8

3. Capacity expansion problem

2. Tell me about your understanding of dynamic agents.

1. JDK dynamic proxy

2. CGLIB dynamic proxy

3. Division of Java collection system, differences between List, Set, and Map

4. The difference between ArrayList and LinkedList

1. Data structure implementation:

2. Random access:

3. Insertion and deletion operations:

4. For query operations:

5. The difference between equals and ==

6. Do you know the several IO streams in Java?

7. Why should we rewrite equals() and hashCode() at the same time?

8. What are the methods to resolve Hash conflicts?

9. The function, principle, advantages and disadvantages, and applicable scenarios of reflection

1. Function

2. Principle

3. Advantages and Disadvantages

4. Usage scenarios

10. What is packaging? Why do you need wrapper classes?

11. Let’s talk about the put method of HashMap

12. What is the expansion mechanism of HashMap? Is there any difference between JDK7 and JDK8?

1、JDK7

2、JDK8

3. Capacity expansion problem

13. Introduction to Java’s exception system

14. Why is String said to be immutable? Why should String be designed to be immutable? Is String really immutable?

15. How does ArrayList expand the underlying array?

16. The difference between HashMap and Hashtable

1. Is the thread safe?

2. Support for Null key and Null value:

3. The difference between the initial capacity size and each expansion capacity size:

4. Underlying data structure:

17. Detailed explanation of the bottom layer of HashTable

1. In single-threaded environment

 2. In a multi-threaded environment

18. What is the Object class and what methods does it have?

18. How to ensure HashMap thread safety?

1, HashTable set

2. Call the Collections.synchronizedMap() method

3. Use ConcurrentHashMap collection

19. Generics and their implementation principles

20. What are the symptoms of HashMap thread insecurity (under what circumstances will HashMap have a CPU 100% problem)

21. Do you know iterators? What is the difference between ordinary for loop and iterator traversal?

1. Different traversal methods

2. Different ways to access the current element

3. Modifications to the iterator will affect the collection itself

22. What is LinkedHashMap and what scenarios can it be used in?

1. Schematic diagram of data structure

2. Execution process of put() method

3. The usage scenarios of LinkedHashMap include but are not limited to:

23. Introduce deep copy and shallow copy in Java

1. Shallow copy

2. Deep copy

24. Caching mechanism of packaging classes

25. Tell me about your understanding of “object-oriented”

1. Understand

2. Basic characteristics of object-oriented

26. Differences between String, StringBuffer and StringBuilder

27. Why does HashMap use red-black trees instead of balanced binary trees or B/B+ trees?

28. Why is the time complexity of HashMap get elements O(1)?

29. What is the underlying sorting algorithm of Arrays.sort? What optimizations have been done?

30. What are the characteristics of the Java language? (Why can Java code be written once and run anywhere?)

31. What is the execution order of static code blocks, non-static code blocks, and constructor methods of parent classes and subclasses in Java?


1. The underlying structure and principle of HashMap

1、JDK7

        HashMap in JDK7 is implemented based on array + linked list , and its bottom layer maintains an Entry array. It will store the corresponding Key and Value pair into the array based on the calculated hashCode. Once a hashCode conflict occurs, the Key and Value pair will be placed behind the corresponding existing element. At this time, A linked list storage structure is formed. However, the implementation of HashMap in JDK7 has an obvious shortcoming, that is, when the Hash conflict is serious, the linked list formed on the bucket will become longer and longer, so the efficiency of the query will become lower and lower, and its time is complex. The degree is O(N).

2、JDK8

        HashMap in JDK8 is implemented based on array + linked list + red-black tree . Its bottom layer maintains a Node array. When the number of data stored in the linked list is greater than or equal to 8, linked list storage is no longer used, but the red-black tree storage structure is used. This is mainly done to optimize the time complexity of the query. The linked list is O(N), while the red-black tree is always O(logN), which can greatly improve the search performance.

3. Capacity expansion problem

        The initial capacity of the HashMap array is 16. When the current number of elements reaches 0.75 of the array capacity, the array will be expanded. Before checking the length of the linked list and converting it into a red-black tree, it will also first check whether the current array reaches a threshold (64). If it does not reach this capacity, the conversion will be given up and the array will be expanded first.

2. Tell me about your understanding of dynamic agents.

        Dynamic proxy is a technology that creates a proxy object of the target object during the running of the program and functionally enhances the methods in the target object. Dynamic proxy is implemented based on the reflection mechanism, which can dynamically create a new class that implements a given set of interfaces at runtime. There are two common dynamic proxy methods in Java: JDK native dynamic proxy and CGLIB dynamic proxy.

1. JDK dynamic proxy

 
        JDK native dynamic proxy uses the reflection mechanism to generate a proxy class that implements the interface implemented by the target object, and then uses this proxy class to implement the call to the target object.

2. CGLIB dynamic proxy

        CGLIB dynamic proxy generates a proxy class by inheriting the target object, and then uses this proxy class to implement the call to the target object.

3. Division of Java collection system, differences between List, Set, and Map

        List: An ordered, repeatable collection whose elements can be accessed by index. Commonly used implementation classes include ArrayList and LinkedList.

        Set: An unordered, non-repeatable collection whose elements cannot be accessed through indexes. Commonly used implementation classes include HashSet and TreeSet.

        Map: An unordered collection of key-value pairs. The keys cannot be repeated and the values ​​can be repeated. Commonly used implementation classes include HashMap and TreeMap.

4. The difference between ArrayList and LinkedList

1. Data structure implementation:

        ArrayList is the data structure implementation of dynamic array, and LinkedList is the data structure implementation of doubly linked list.

2. Random access:

        Since ArrayList is implemented based on arrays, it supports random access to elements. LinkedList does not support random access, only sequential access.

3. Insertion and deletion operations:

        For tail insertion and tail deletion, ArrayList performance is better than LinkedList because other elements do not need to be moved frequently, and because the addresses are continuous, the indexing speed is very fast.

        LinkedList performs better than ArrayList for random insertion and deletion. Because only the pointer needs to be updated when inserting and deleting elements in a LinkedList, while other elements need to be moved to occupy memory when inserting and deleting elements in an ArrayList. Therefore, when inserting and deleting operations are performed frequently, the performance of the ArrayList will be relatively low, and may causing memory waste

4. For query operations:

        ArrayList performs better than LinkedList

5. The difference between equals and ==

        == compares whether the values ​​of two variables are equal, while equals() compares whether the contents of two objects are equal.

        When using == to compare two objects, it compares whether the reference addresses of the two objects are equal, that is, whether they point to the same memory address.

        When using the equals() method to compare two objects, it compares whether the contents of the two objects are equal. Therefore, if you want to compare two strings for equality, you should use the equals() method instead of the == operator.

6. Do you know the several IO streams in Java?

        IO streams in Java are mainly divided into two types: byte streams and character streams , and each stream is divided into input streams and output streams . Among them, the byte stream is mainly InputStream and OutputStream, while the character stream is mainly Reader and Writer.

        There are many specific implementation classes of these streams, such as FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream, FileReader, FileWriter, etc.

7. Why should we rewrite equals() and hashCode() at the same time?

        Because the equals method is used to determine whether two objects are equal, and the hashCode method is used to calculate the hash value of the object. If two objects are compared equal through the equals method, their hashCode values ​​must be equal. Therefore, if you only override the equals method without overriding the hashCode method, problems will occur when using data structures such as hash tables and the accurate location cannot be found. If you only write the hashCode method without overriding the equals method, you will find the location and cannot determine whether it is equal.

8. What are the methods to resolve Hash conflicts?

        Open addressing method: Also called linear detection method, starting from the position where the conflict occurs, find a free position in the hash table in a certain order, and then store the conflicting element in this position.

        Chain address method: Hang elements with the same hash value under the same bucket. Each bucket can be a storage structure such as a linked list or an array.

        Rehash method: When a collision occurs, the hash value of the element is recalculated using another hash function and then inserted into the corresponding bucket.

        Establish a public overflow area: divide the hash table into a basic table and an overflow table, and store all conflicting elements in the overflow table

9. The function, principle, advantages and disadvantages, and applicable scenarios of reflection

1. Function

        Reflection allows the program to dynamically obtain class information at runtime and can call class methods or access class properties. The reflection mechanism improves the flexibility and scalability of Java programs, reduces coupling, and improves adaptive capabilities. Through reflection, the program code can access the internal information of the class loaded into the JVM, such as obtaining the attribute information, methods, constructor information, etc. of the loaded class.

2. Principle

        The principle of reflection is to dynamically obtain class information at runtime and be able to call class methods or access class properties. The Java reflection mechanism mainly provides the following three classes: Class, Method and Field. Among them, the Class class represents a class or interface, the Method class represents the methods in the class, and the Field class represents the member variables in the class.

3. Advantages and Disadvantages

        The advantage of the reflection mechanism is that it improves the flexibility and scalability of Java programs, reduces coupling, and improves adaptive capabilities. It allows programs to create and control objects of any class without having to hardcode the target class in advance .

        The disadvantage of the reflection mechanism is that using reflection is basically an interpretation operation, which is much slower than direct code for field and method access. Therefore, there may be performance issues.

4. Usage scenarios

        The reflection mechanism is suitable for scenarios such as modular development and dynamic proxy design patterns.

10. What is packaging? Why do you need wrapper classes?

        A wrapper class is a corresponding class provided for each basic data type in Java, making it object-oriented. The eight basic data types in Java are not object-oriented. In order to facilitate use and solve this shortcoming, a corresponding class is designed for each basic data type to represent it when designing the class. In this way, the classes corresponding to the eight basic data types Collectively called packaging categories.
        In addition to objects (reference types), there are eight basic types in Java, which are not objects. In order to convert a basic type into an object, the simplest way is to save the basic type as an attribute of a class, that is, to wrap the basic data type. This is the origin of the wrapper class.
        The reason why you need to use a wrapper class is that all operations in Java require to be described in the form of objects. But in Java, in addition to objects (reference types), there are eight basic types, which are not objects. So, in order to convert the basic type into an object, the simplest way is to save the basic type as an attribute of a class, that is, to wrap the basic data type. For example, collections and generics need to operate on wrapper classes instead of basic types.

11. Let’s talk about the put method of HashMap

1. First expansion:

First determine whether the array is empty. If the array is empty, perform the first expansion (resize);

2. Calculate the index:

Calculate the index of the key-value pair in the array through the hash algorithm

  • Insert data:

    • If the element at the current position is empty, insert data directly;

    • If the element at the current position is not empty and the key already exists, its value will be overwritten directly;

    • If the element at the current position is not empty and the key does not exist, link the data to the end of the linked list;

    • If the length of the linked list reaches 8, convert the linked list into a red-black tree and insert the data into the tree;

  • Expand again
    • If the number of elements (size) in the array exceeds the threshold, the expansion operation is performed again.

12. What is the expansion mechanism of HashMap? Is there any difference between JDK7 and JDK8?

1、JDK7

        HashMap in JDK7 is implemented based on array + linked list , and its bottom layer maintains an Entry array. It will store the corresponding Key and Value pair into the array based on the calculated hashCode. Once a hashCode conflict occurs, the Key and Value pair will be placed behind the corresponding existing element. At this time, A linked list storage structure is formed. However, the implementation of HashMap in JDK7 has an obvious shortcoming, that is, when the Hash conflict is serious, the linked list formed on the bucket will become longer and longer, so the efficiency of the query will become lower and lower, and its time is complex. The degree is O(N).

2、JDK8

        HashMap in JDK8 is implemented based on array + linked list + red-black tree . Its bottom layer maintains a Node array. When the number of data stored in the linked list is greater than or equal to 8, linked list storage is no longer used, but the red-black tree storage structure is used. This is mainly done to optimize the time complexity of the query. The linked list is O(N), while the red-black tree is always O(logN), which can greatly improve the search performance.

3. Capacity expansion problem

        The initial capacity of the HashMap array is 16. When the current number of elements reaches 0.75 of the array capacity, the array will be expanded. Before checking the length of the linked list and converting it into a red-black tree, it will also first check whether the current array reaches a threshold (64). If it does not reach this capacity, the conversion will be given up and the array will be expanded first.

13. Introduction to Java’s exception system

  • Java's exception architecture is based on the Throwable class and is divided into two major categories: Error and Exception.
    • Error represents a system-level error that the program cannot handle, such as OutOfMemoryError, ThreadDeath, etc.
    • Exception represents an exception that occurs when the program is running and can be caught and handled by the program.
      • Exception is divided into two types: Checked Exception and Unchecked Exception.
        • Checked Exception refers to an exception that can be checked at compile time and must be processed or thrown in the code.
        • Unchecked Exception refers to exceptions that cannot be checked out at compile time, such as NullPointerException, ArrayIndexOutOfBoundsException, etc.

14. Why is String said to be immutable? Why should String be designed to be immutable? Is String really immutable?

        In Java, String is a constant. Once a String object is created, its value cannot be changed, and its content cannot be changed. This is because the String class is designed to be immutable, which ensures the safety, thread safety, and efficiency of String objects.

        The String class is modified as final, which prevents it from being inherited, thus preventing subclasses from destroying the immutability of String. In addition, String objects are immutable, so they are multi-thread safe, and the same String instance can be shared by multiple threads.

15. How does ArrayList expand the underlying array?

        The principle of ArrayList expansion is: when the number of elements in the ArrayList reaches the capacity, the ArrayList will reallocate a larger array and copy all the elements in the original array to the new array. The expansion mechanism of ArrayList is performed when elements are added, not when the ArrayList is created. By default, the initial capacity of ArrayList is 10, and the capacity will increase to 1.5 times after each expansion.

        In jdk1.7, ArrayList will initialize a dynamic array with a default length of 10. In jdk1.8, the array initialized by ArrayList is empty, and the array length is initialized only when the add() method is called.

16. The difference between HashMap and Hashtable

1. Is the thread safe?

        HashMap is thread-unsafe, HashTable is thread-safe; the internal methods of HashTable are basically synchronized; if you want a thread-safe Map container, it is recommended to use ConcurrentHashMap, which has better performance.

2. Support for Null key and Null value:

        In HashMap, null can be used as a key. There is only one such key, and the value corresponding to one or more keys can be null; neither key nor value in HashTable can be null, otherwise a null pointer exception will be thrown;

3. The difference between the initial capacity size and each expansion capacity size:

        If the initial capacity value is not specified when creating, the default initial size of Hashtable is 11. After each expansion, the capacity becomes the original 2n+1. The default initialization size of HashMap is 16. Each subsequent expansion will double the capacity;

        If an initial value of capacity is given when creating, Hashtable will directly use the size you gave, and HashMap will expand it to a power of 2.

4. Underlying data structure:

        HashMap in JDK1.8 and later has undergone major changes in resolving hash conflicts. When the length of the linked list is greater than the threshold (default is 8), the linked list is converted into a red-black tree to reduce search time. Hashtable does not have such a mechanism. .

17. Detailed explanation of the bottom layer of HashTable

1. In single-threaded environment

Bottom layer: hash table structure (array + linked list) 

When creating an object using no-parameter construction, the default length of the array is 11, and the loading factor is 0.75.

Add first element

hashtable.put("键","值");

 Calculate the index that should be stored based on the hash value of the key. Example: 5
and then determine whether the 5 index is null. If it is null, store the element directly.

Add second element

Calculate the index that should be stored based on the hash value of the key. Example: 8
Then determine whether the index of 8 is null. If it is null, store the element directly.

Add third element

Calculate the index that should be stored based on the hash value of the key. Example: 5
and then determine whether the 5 index is null.
At this time, there is already an element on the 4 index that is not null, and the equals method will be called to compare the attribute values ​​​​of the key.
If they are the same , not stored. If they are different, they are stored in the array, and the old elements are hung under the new elements to form a linked list structure (hash bucket structure)

 2. In a multi-threaded environment

Using pessimistic locking

Add element

When multiple threads add elements, synchronized locks the entire array as soon as the thread enters. Other threads wait for the lock to be released and other operations remain unchanged.

18. What is the Object class and what methods does it have?

The java.lang.Object class is the root class in the Java language, that is, the parent class of all classes.

There are 11 methods included in the object class:

Need to rewrite toString(), equals(), hashCe();
thread-related wait(), notify(), notifyAll();
other getClass(), finalize(), clone();

1. Rewrite

  • toString(): Returns the string representation of the object.
  • equals(): Compares two objects for equality.
  • hashCode(): Returns the hash code value of the object.

2. Thread related

  • wait(): Makes the current thread wait until another thread calls the object's notify() or notifyAll() method.
  • notify(): Wakes up a single thread waiting on this object monitor.
  • notifyAll(): Wakes up all threads waiting on this object monitor.

3. Others

  • getClass(): Returns the runtime class of this Object.

18. How to ensure HashMap thread safety?

1, HashTable set

2. Call the Collections.synchronizedMap() method

3. Use ConcurrentHashMap collection

19. Generics and their implementation principles

        Generics are a new feature introduced in Java SE 5.0. It provides a compile-time type safety checking mechanism, allowing programmers to find type mismatch errors at compile time instead of only at runtime.

        The implementation principle of generics is achieved through type erasure. At compile time, all generic types are erased to their original types. For example, List<String> will be erased to List, and List<Integer> will also be erased to List. The advantage of this is that type checking can be performed at compile time, avoiding problems such as type conversion exceptions at runtime.

20. What are the symptoms of HashMap thread insecurity (under what circumstances will HashMap have a CPU 100% problem)

Concurrent expansion leads to an infinite loop and causes 100% CPU problems

The reasons why hashmap causes an infinite loop are as follows:

Detailed explanation of HashMap infinite loop_Liangshan Godfather's Blog-CSDN Blog

21. Do you know iterators? What is the difference between ordinary for loop and iterator traversal?

1. Different traversal methods

        The enhanced for loop traverses the elements in the collection through the for-each syntax, which is concise and clear. The iterator needs to explicitly call the next() method in the code to obtain each element, and the traversal method is relatively troublesome.

2. Different ways to access the current element

        The enhanced for loop can only access each element in sequence, cannot access elements at specific positions through indexes, and cannot delete elements. The iterator can delete elements in the collection through the remove() method, and can also access elements in the collection.

3. Modifications to the iterator will affect the collection itself

        When an iterator is used to traverse a collection and modify the elements in the collection, these modifications will directly affect the collection itself, and the enhanced for loop does not have this functionality.

Therefore, when you need to traverse the elements in the collection framework, if you only need to access each element sequentially, you can traverse through an enhanced for loop; if you need to access the elements at a specific position or modify the collection, you need to use an iterator

22. What is LinkedHashMap and what scenarios can it be used in?

LinkedHashMap inherits from HashMap. Based on HashMap, by maintaining a two-way linked list, it solves the problem that HashMap cannot keep the traversal order and insertion order consistent at any time.

1. Schematic diagram of data structure

 Red-black trees were introduced in jdk1.8

In the figure above, the light blue arrow indicates the predecessor reference, and the red arrow indicates the successor reference. Whenever a new key-value pair node is inserted, the new node will eventually follow the node pointed to by the tail reference. The tail reference will be moved to the new node, so a doubly linked list is established.

2. Execution process of put() method

The first is to add only one element Entry1, assuming the index is 0:

When adding another element Entry2, assume the index is 15

When adding another element Entry3, assume that the index is also 0:

When putting an element, it is not only added to the HashMap, but also added to the doubly linked list. Therefore, it can be seen that LinkedHashMap is HashMap + doubly linked list. The following diagram shows the process of gradually adding data to LinkedHashMap. The red part is Doubly linked list, the black part is the HashMap structure, the header is an Entry type doubly linked list header, which does not store data itself.

3. The usage scenarios of LinkedHashMap include but are not limited to:

  • Ordered storage of elements
  • LRU cache

23. Introduce deep copy and shallow copy in Java

1. Shallow copy

        For basic data types, shallow copy transfers the value directly and stores it in another space of the memory. Modifying this value will not affect the value of the copy source.
        A shallow copy of a reference data type transfers the address without re-opening a memory space for storage of the object. Therefore, a shallow copy of the reference data type is equivalent to two references pointing to the same memory address, so it is obvious. Modifying the copied value will affect the value of the copy source.

2. Deep copy

        Deep copy means that when copying an object, not only the object itself is copied, but also the objects pointed to by all references contained in the object are also copied.

There are several ways to implement deep copy in Java:

  • Override the clone() method
  • Serialization
  • Utilize third-party libraries

24. Caching mechanism of packaging classes

        The wrapper class caching mechanism in Java means that the basic types in Java have corresponding wrapper class caching mechanisms. For example, the caching mechanism of the Integer wrapper class is that Java will cache data between [-128,127].

        If the boxed data is within this range, it will first go to the constant pool to find whether a packaging class object corresponding to this value has been generated. If there is a boxing operation, a reference to the object will be returned directly. If not, a packaging class will be created. An object of the class is returned and this object is placed in the constant pool. If the data exceeds this range, a new object is created directly and a reference to the new object is returned.

for example:

25. Tell me about your understanding of “object-oriented”

1. Understand

        Object-Oriented Programming (OOP) is a programming way of thinking and coding architecture . It is a  method of understanding and abstracting the real world . It is the product of the development of computer programming technology to a certain stage.

        What is an object : An object is something that exists objectively. It can be said that anything that exists objectively can be an object. A computer, a pen, a person, a car, etc. can all be called objects.

2. Basic characteristics of object-oriented

  • Abstraction : Summarize the common attributes and behaviors of objects of the same type to form a class  . Classes are templates or blueprints for constructing objects. The process of constructing an object from a class is called creating an instance of the class.
  • Encapsulation : Encapsulate the abstracted data and code together, hide the properties and implementation details of the object, and only provide public access to the outside world, isolating changes, making it easier to use, and improving reusability and security.
  • Inheritance : On the basis of existing classes, extend them to form new classes to improve code reusability. Inheritance is a prerequisite for polymorphism.
  • Polymorphism : The so-called polymorphism means that the same function name has different function implementation methods.

26. Differences between String, StringBuffer and StringBuilder

  • String is a string constant, while StringBuilder and StringBuffer are both string variables, that is, once the String object is created, the object cannot be changed, but the objects of the latter two are variables and can be changed.
  • String and StringBuilder are not thread-safe, while StringBuffer is thread-safe.
  • The biggest difference between StringBuilder and StringBuffer is that StringBuilder is thread-unsafe.

27. Why does HashMap use red-black trees instead of balanced binary trees or B/B+ trees?

When the amount of data is small, the B/B+ tree is like a linked list, and the query performance is O(1) at best and O(N) at worst. So the performance is lower than the red-black tree.

28. Why is the time complexity of HashMap get elements O(1)?

        The time complexity of getting elements of HashMap is O(1) because in an ideal state, that is, no hash conflict occurs, and each linked list in the array has only one node, then the get method can directly locate the target element through hash. position in the array, the time complexity is O(1). But in extreme cases, if the array subscripts of all Keys conflict, then HashMap will degenerate into a linked list, and the query time complexity is O(N).

29. What is the underlying sorting algorithm of Arrays.sort? What optimizations have been done?

The underlying sorting algorithm of the Arrays.sort() method selects the sorting algorithm based on the size of the data.

  • When the amount of data is [0 - 47), insertion sort is used, when [47, 286), dual-axis quick sort is used, and when it is greater than or equal to 286, merge sort is used.
  • For primitive types, Arrays.sort() uses a tuned quick sort under the hood.
  • For object types, Arrays.sort() uses an improved merge sort underneath.

30. What are the characteristics of the Java language? (Why can Java code be written once and run anywhere?)

1. Object-oriented : Java is a purely object-oriented programming language, which means that all code in Java is based on objects. In Java, you create objects by defining classes, and these objects can have state (properties) and behavior (methods). Java supports object-oriented concepts such as inheritance, polymorphism, and encapsulation, making code clearer, easier to extend, and easier to maintain.

2. Platform independence : Java's platform independence benefits from the capabilities of its compiler and virtual machine. After the Java code is written, it needs to be compiled into a bytecode file through a compiler, and then the bytecode file is interpreted into executable code on a specific platform through the Java Virtual Machine (JVM). Because bytecode files are platform-independent, the same Java code can be run on different platforms.

3. Security : Java's security benefits from its built-in security mechanisms, such as security sandbox, class loader, security manager, etc. Java's security mechanism can limit code access rights to ensure the reliability and security of the code. Additionally, Java has a built-in exception handling mechanism that helps developers handle errors and exceptions more easily.

4. Efficiency : Java is an efficient programming language with high performance and low latency. Java can handle large amounts of data and complex tasks quickly, and also supports features such as garbage collection and memory management, which can automatically manage memory without significantly affecting performance.

5. Multi-thread support : Java provides support for multi-thread programming, making it easy to create concurrent programs. Java's threading mechanism allows multiple threads to execute simultaneously, allowing tasks to be completed faster. Multithreaded programming in Java is also very safe and avoids common concurrency problems such as deadlocks and race conditions.

6. Garbage collection : Java's garbage collection mechanism can automatically manage memory, reducing problems such as memory leaks and pointer errors.

7. Open source code : Java is an open source programming language (starting from Java 8, Oracle began to open source the Java SE platform in OpenJDK under the GPLv2 license), which can be used and distributed freely. Java's open source code allows developers to freely use, modify and distribute Java code and tools, thus promoting the development and growth of the Java community.

31. What is the execution order of static code blocks, non-static code blocks, and constructor methods of parent classes and subclasses in Java?

The specific execution sequence is:

1. Static code block of parent class

2. Static code blocks of subclasses (executed from top to bottom according to the inheritance hierarchy)

3. Non-static code block of parent class

4. Construction method of parent class

5. Non-static code blocks of subclasses (executed from top to bottom according to the inheritance hierarchy)

6. Construction method of subclass

Code example:

class Parent {
    static {
        System.out.println("父类静态代码块");
    }

    {
        System.out.println("父类非静态代码块");
    }

    public Parent() {
        System.out.println("父类构造方法");
    }
}

class Child extends Parent {
    static {
        System.out.println("子类静态代码块");
    }

    {
        System.out.println("子类非静态代码块");
    }

    public Child() {
        System.out.println("子类构造方法");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

Guess you like

Origin blog.csdn.net/weixin_55127182/article/details/131268932