Home >Java >JavaInterview questions >Summary of the most common JAVA interview questions in 2020 (Collection)

Summary of the most common JAVA interview questions in 2020 (Collection)

angryTom
angryTomforward
2019-11-11 17:47:172173browse

Summary of the most common JAVA interview questions in 2020 (Collection)

java basics and multiple "comparisons"


1.Collections.sort sorting Internal Principle

In Java 6, Arrays.sort() and Collections.sort() use MergeSort, but in Java 7, the internal implementation is replaced by TimSort, which compares objects Implementation requirements are more stringent

2. HashMap principle, changes made by java8

In terms of structural implementation, HashMap is an array linked list red-black tree (JDK1.8 added Red-black tree part) implemented. HashMap only allows the key of one record to be null, and allows the value of multiple records to be null.

HashMap is not thread-safe. ConcurrentHashMap is thread-safe. Resolve collisions: When a conflict occurs, use the zipper method to link nodes with keywords that are synonyms in a single linked list. If the hash table is long m, define a pointer array T composed of m head pointers, and the node address is i. The point is inserted into a singly linked list with T(i) as the head pointer. In Java 8, the conflicting elements exceed the limit (8), and the linked list is replaced with a red-black tree.

3. The difference between String and StringBuilder

1) Variable and immutable: String is immutable, and a new object will be generated every time " " is executed, so String is not used when changing strings frequently to save memory.

2) Is it multi-thread safe: StringBuilder does not add synchronization locks to the method, so it is not thread safe. Both StringBuffer and String are thread-safe.

4. The difference between Vector and Array

1) ArrayList is expanded by 50% by default when the memory is insufficient, and Vector is expanded by 1 times by default.

2) Vector is thread-safe, but Vector is not used in most cases because thread safety requires greater system overhead.

5. The difference between HashMap and Hashtable

1) Historical reasons: Hashtable inherits the Dictonary class, HashMap inherits from abstractMap

2) HashMap allows nulls key-value pairs, but there can be at most one empty object, which HashTable does not allow.

3) HashTable is synchronized, while HashMap is asynchronous, and is more efficient than HashTable

6. Comparison between ConncurrentHashMap and hashtable (Two threads concurrently access the same entry in the map Chain, one thread deletes at the end, and one thread traverses and searches at the front, asking why the previous thread can still correctly find the node deleted by another thread later)

ConcurrentHashMap combines hashtable and hashmap Advantage. Hashtable is synchronized, that is, thread-safe, while hashmap does not consider synchronization. Therefore, hashmap is more efficient in single-threaded situations. In the case of hashtable's multi-threading, synchronization operations can ensure the correctness of program execution. But hashtable is blocking, and the entire structure must be locked every time it is executed synchronously. ConcurrentHashMap was born to solve this problem.

ConcurrentHashMap allows multiple modification operations to be performed concurrently. The key is to use Lock separation technology (an Array saves multiple Objects, uses the locks of these objects as separate locks, and randomly uses any one during get/put). It uses multiple locks to control modifications to different parts of the hash table. In JDK 1.6, there is a HashEntry structure. Each time a newly added node is inserted, it will be used as the head node of the chain (implemented the same as HashMap), and every time a node is deleted, all nodes before the deleted node will be copied to form a new one. chain, and point the next node of the previous node of the current node to the next node of the current node, so that two chains exist after deletion, thus ensuring that even in the same chain, one thread is deleting, and the other They all work fine when the thread is traversing, because the traversing thread can continue to use the original chain.

In Java8, volatile HashEntry is used to save data, and the table element is used as a lock; a red-black tree is added from the table array to the one-way linked list. A red-black tree is a special binary search tree with the following characteristics: 1. The node is red or black 2. The root node is black 3. The leaf node is black 4. If one node is red, the leaf node is black 5. The number of black nodes on all paths from a node to its descendant nodes is the same.

7. What is the difference between ArrayList and LinkedList?

The most obvious difference is that

The underlying data structure of ArrrayList is an array and supports random access, while the underlying data structure of LinkedList is a linked list and does not support random access. To access an element using a subscript, the time complexity of ArrayList is O(1), while that of LinkedList is O(n). LinkedList is a doubly linked list

8. In Java, what is the difference between Comparator and Comparable?

The Comparable interface is used to define the natural order of objects and is a sorting interface, while comparator is usually used to define user-customized order and is a comparison interface. If we need to control the order of a certain class, and the class itself does not support sorting (that is, it does not implement the Comparable interface), then we can create a "comparator of this class" to perform sorting. There is always only one Comparable, but there can be multiple comparators to define the order of objects.

9. What is an abstract class? How is it different from an interface? Why would you ever use abstract classes?

Abstract classes refer to classes that are not allowed to be instantiated; a class can only use the inheritance relationship once. However, a class can implement multiple interfaces.

Abstract class and interface reflect different design concepts. In fact, abstract class represents the "is-a" relationship, and interface represents the "like-a" relationship.

Classes that implement abstract classes and interfaces must implement all methods in them. Abstract classes can have non-abstract methods. There cannot be implementation methods in the interface. But in Java8, static default methods are allowed in interfaces.

The variables defined in the interface are public static final by default, and their initial value must be given, so they cannot be redefined in the implementation class, nor can their values ​​be changed. Variables in abstract classes are friendly by default, and their values ​​can be redefined in subclasses or reassigned.

When a subclass implements an abstract method in the parent class, the visibility can be greater than or equal to that in the parent class; while the visibility of the interface method in the interface implementation class can only be the same as that in the interface (public).

Use abstract classes for reuse. Reduce the amount of coding and reduce coupling.

10.Describe overloading and rewriting in Java?

Both overloading and rewriting allow you to use the same name to implement different functions, but overloading is a compile-time activity, while rewriting is a run-time activity. You can override methods in the same class, but you can only override methods in subclasses. Rewriting must have inheritance

Rewriting: 1. In subclasses, methods inherited from the base class can be rewritten as needed. 2. The overridden method and the overridden method must have the same method name, parameter list, and return type. 3. Overriding methods cannot use more restrictive access permissions than the overridden method.

When overloading, the method name should be the same, but the parameter type and number are different, and the return value type can be the same or different. The return type cannot be used as a criterion for distinguishing overloaded functions.

11.What is the difference between Collection and Collections?

Collection is the basic interface in the Java collection framework;

Collections is a tool class provided by the Java collection framework, which contains a large number of static methods for operating or returning collections.

12. The implementation principle of polymorphism in Java

The so-called polymorphism refers to the parent class reference pointing to the subclass object, and when calling the method, the subclass will be called. Implementation rather than the implementation of the parent class. The key to the implementation of polymorphism lies in "dynamic binding".

13.What methods are defined in object?

clone(), equals(), hashCode(), toString(), notify(), notifyAll(),

wait(), finalize(), getClass()

14.Java generics and type erasure?

Generics are parameterized types. When creating a collection, specify the type of collection elements. This collection can only pass in parameters of this type. Type erasure: The bytecode generated by the Java compiler does not contain generic information, so it is erased at compile time: 1. Generics are replaced with the top-level parent class; 2. Removed.

15. Name 5 new features introduced in JDK 1.8?

Java 8 is a groundbreaking version in the history of Java. The following are the 5 main features of JDK 8:

Lambda expression; allows anonymous function Stream to be passed like an object API, taking full advantage of modern multi-core CPUs, allows you to write very concise code; Date and Time API, finally, there is a stable and simple date and time library for you to use extension methods. Now, you can have static and default methods in the interface ; Repeat annotations, now you can use the same annotation multiple times on the same type.

16. Access scope of public, private, protected and default keywords in java:

Protected can be accessed within the package and subclasses outside the package, default can only Access within the same package, prvate can only be of the same class

17. Commonly used data structures:

sets, linear structures (arrays, queues, linked lists and stacks), tree shapes Structure, graph structure

18. What tree is used to implement TreeMap in Java? (Answer)

TreeMap in Java is implemented using red-black trees.

19. What is an anonymous inner class? How to access variables defined outside it?

Anonymous inner classes are inner classes without names. Anonymous inner classes can only be used once. They are usually used to simplify code writing.

Anonymous inner classes can only access the Final variables of the outer class. Java 8 is smarter: if a local variable is accessed by an anonymous inner class, then the local variable is equivalent to automatically using the final modification.

20. How to create a singleton pattern? Talking about double checking, he said it is not thread safe. How to efficiently create a thread-safe singleton?

One is through enumeration, and the other is through static inner class.

21. What is the difference between the poll() method and the remove() method?

poll() and

remove() both take out an element from the queue, but poll() will return empty when it fails to obtain the element, but remove() fails. An exception will be thrown when.

22. Write a code to remove an element when traversing the ArrayList

Use an iterator.

Iterator itr = list.iterator();

while(itr.hasNext()) {if(…) { itr.remove();} }

JVM


1. How does the JVM load a class? What are the methods in the parent delegation model

Class loading Process: loading, verification (the purpose of the verification phase is to ensure that the information contained in the byte stream of the Class file complies with JVM specifications and will not cause harm to the JVM), preparation (the preparation phase allocates memory for variables and sets the initialization of class variables), parsing ( The parsing process is to replace the symbol reference in the constant pool with a direct reference) and initialize.

Methods in the parent delegation model: Parental delegation means that if a class receives a class loading request, it will not try to load it by itself first, but will first find the parent class loader to complete it. When the top-level startup class loader indicates that it cannot load the class, the subclass will try to load it by itself. When the original initiator loader cannot be loaded, it will not look down, but will throw a ClassNotFound exception.

Method: Start (Bootstrap) class loader, standard extension (Extension) class loader, application class loader (Application), context (Custom) class loader. The meaning is to prevent multiple copies of the same bytecode from appearing in memory.

2.GC algorithm (what kind of objects are considered recyclable objects, reachability analysis), CMS collector

How does jvm determine that an object has become To identify recyclable "garbage", there are generally two methods: reference notation and root search algorithm. Reference notation cannot solve the problem of circular references, so root search is used. Starting from a series of "GC Roots" objects and searching downward, the path traveled by the search is called a reference chain. When there is no reference chain between an object and "GC Roots", it is said to be reference unreachable. Objects that cannot be referenced are considered recyclable objects.

Several kinds of garbage collectors: 1, Serial New/Serial Old (serial), 2, Parrallel New (parallel), 3, Parrallel Scavenge, 4, Parrallel Old, 5, CMS (CMS collector is A collector that aims to obtain the shortest recovery pause time. It is a concurrent collector that uses the Mark-sweep algorithm.), 6. G1 (is a parallel and concurrent collector, and can establish a predictable The pause time model is generally based on mark cleaning and partially uses replication)

3. What areas is the JVM divided into and what does each area do?

1) Method area (method): shared by all threads. The method area contains all class information and static variables.

2) Heap: Shared by all threads, it stores object instances and arrays. The Java heap is the main area of ​​GC.

3) Stack: Each thread contains a stack area, which stores some local variables, etc.

4) Program counter: It is a line indicator of the bytecode executed by the current thread.

4. What things are stored in the JVM new generation, old generation, and persistent generation?

The persistent generation mainly stores class information of Java classes and has little to do with the Java objects to be collected by garbage collection. All newly generated objects are first placed in the young generation, and the old generation stores objects with long life cycles.

5. Memory overflow and memory leak:

Memory overflow: When the program applies for memory, there is not enough memory, out of memory; the memory leak value garbage object cannot be recycled , you can use the memory analyzer tool to view leaks.

6. Processes and threads:

A process refers to a running program (independence, dynamics, concurrency), and a thread refers to the sequential execution flow in a process. The difference is: 1. No memory is shared between processes. 2. The cost of creating a process for resource allocation is much higher, so multi-threading is more efficient in a high-concurrency environment.

7. Serialization and deserialization:

Serialization refers to converting java objects into byte sequences, and deserialization is the opposite. Mainly for communication between Java threads and object transfer. Only class objects that implement the Serializable or Externalizable interface can be serialized.

In 8.64-bit JVM, what is the majority of the length of int?

In Java, the length of an int type variable is a fixed value, regardless of the platform, and is always 32 bits. This means that the length of the int type is the same in 32-bit and 64-bit Java virtual machines.

9. What is the difference between WeakReference and SoftReference in Java?

There are four types of references in Java. StrongReference, SoftReference, WeakReference and PhantomReference.

StrongReference is Java's default reference implementation. It will survive in the JVM as long as possible. When no object points to it, it will be recycled by GC.

WeakReference, as the name suggests, is a Weak reference, when the referenced object no longer has a strong reference in the

JVM, will be recycled by GC

Although WeakReference and SoftReference are beneficial to improving GC and memory efficiency, WeakReference, Once the last strong reference is lost, it will be recycled by GC, and SoftReference will keep the reference as long as possible until the JVM runs out of memory (virtual machine guarantee). This feature makes

SoftReference very suitable Caching application

10.Explain Java heap space and GC?

When started via Java command

When the Java process starts, memory will be allocated for it. Part of the memory is used to create heap space. When an object is created in the program, memory is allocated from the heap space. GC is a process inside the JVM that reclaims the memory of invalid objects for future allocation.

11.What is the difference between heap and stack in Java?

The heap and stack in JVM belong to different memory areas and are used for different purposes. The stack is often used to store method frames and local variables, while objects are always allocated on the heap. The stack is usually smaller than the heap and is not shared among multiple threads, whereas the heap is shared by all threads in the entire JVM.

Concurrency, lock


1.volatile keyword, Lock

In concurrent programming: atomicity issues , visibility issues, ordering issues.

The volatile keyword can ensure visibility, and the word can prohibit instruction reordering, but it cannot guarantee atomicity. Visibility can only ensure that the latest value is read every time, but volatile cannot guarantee the atomicity of operations on variables. Add the Lock keyword and memory barrier to the generated variable statement.

The Lock implementation provides a wider range of locking operations than are available using synchronized methods and statements, and it handles thread synchronization issues in a more elegant manner. Using sychronized modified methods or statement blocks will automatically release the lock after the code is executed, while using Lock requires us to manually release the lock

2. MYSQL common optimization (sql optimization, table structure optimization, etc.)

SQL optimization, table structure optimization, index optimization, cache parameter optimization

3. Every time java is changed, it needs to be recompiled, packaged and deployed. Is there a better way

Hot reloading can be used

4. What are the methods of inter-process communication?

1) Pipe, 2) Named pipe, 3) Signal, 4) Message queue, 5) Shared memory, 6) Memory mapping ( mapped memory), 7) semaphore, 8) socket (Socket)

5.Sychronized modifies static methods, locks the class itself instead of the instance, and non-static methods lock the instance.

6. Under what circumstances will the operating system deadlock?

The so-called deadlock: refers to a deadlock caused by multiple processes competing for resources during operation. Cause: Competition for resources: When multiple processes in the system use shared resources, and the resources are not enough to meet needs, it will cause processes to compete for resources and cause deadlock. The order of advancement between processes is illegal: the order of requesting and releasing resources is inappropriate, which will also lead to process deadlock

7. Four conditions for deadlock:

1. Mutual exclusion conditions (process exclusive resources) 2. Request and retention (when the process is blocked due to requesting resources, the obtained resources will be kept) 3. Non-deprivation conditions (the resources obtained by the process will be used up at the end Before, it cannot be forcibly deprived) 4. Cyclic waiting (a head-to-tail cyclic waiting resource relationship is formed between several processes)

8. How to understand distributed locks?

Since in daily work, online servers are deployed on multiple distributed servers, we often face the problem of data consistency in distributed scenarios, so we must use distributed locks to solve it. these questions.

9. What is the relationship between thread synchronization and blocking? Does synchronization necessarily block? Does blocking have to be synchronous?

Whether threads are synchronized or not has nothing to do with blocking or non-blocking. Synchronization is a process, and blocking is a state of a thread. Competition may occur when multiple threads operate on shared variables. At this time, synchronization is needed to prevent more than two threads from entering the critical area at the same time. During this process, the thread that enters the critical area later will be blocked, waiting for the thread that entered first to exit the critical area.

10. What is the difference between synchronous and asynchronous?

The biggest difference between synchronous and asynchronous is. One needs to wait, the other does not. Synchronization can avoid deadlocks and dirty data reading. It is generally used when sharing a certain resource. If everyone has modification permissions and modifies a file at the same time, it is possible for one person to read the content that another person has deleted. An error will occur, and the synchronization will be modified in order.

11. Thread pool

According to the system's own environmental conditions, it effectively limits the number of execution threads to achieve the best operating results. Threads mainly control the number of executing threads. Threads that exceed the number wait in line, wait for a task to be executed, and then take out the task from the front of the queue for execution

12. How to call the wait() method? Use if block or loop? Why?

wait() method should be called in a loop, because when the thread gets the CPU and starts execution, other conditions may not be met yet, so it is better to loop to check whether the conditions are met before processing.

wait(), notify() and notifyall() methods are synchronization control methods provided by the java.lang.Object class for threads to implement inter-thread communication. Waiting or waking up

13. Several ways to implement threads

(1) Inherit the Thread class and rewrite the run function

(2) Implement Runnable interface, rewrite the run function

(3) Implement the Callable interface, rewrite the call function

14. What is false sharing in a multi-threaded environment?

False sharing is a well-known performance problem in multi-threaded systems (where each processor has its own local cache). The cache system stores data in cache line units. A cache line is an integer power of 2 consecutive bytes, typically 32-256 bytes. The most common cache line size is 64 bytes. When multiple threads modify independent variables, if these variables share the same cache line, they will inadvertently affect each other's performance. This is false sharing.

Network, database


1. How does TCP ensure reliable transmission? Three-way handshake process?

In a TCP connection, the data stream must be delivered to the other party in the correct order. The reliability of TCP is achieved through sequence numbering and acknowledgment (ACK). TCP connections are initialized with a three-way handshake. The purpose of the three-way handshake is to synchronize the sequence numbers and confirmation numbers of both parties and exchange TCP window size information. The first time is when the client initiates the connection; the second time means that the server has received the client's request; and the third time means that the client has received feedback from the server.

2. What are your commonly used commands under Linux?

1. The cd command is used to change the directory. cd / Go to the root directory cd ~ Go to the user directory

2. The ls command is used to view the contents of the directory.

3. The cp command is used to copy the file cp

4.mv command mv t.txt Document moves the file t.txt to the directory Document.

3. What are the commonly used hash algorithms?

1. Additive hash: The so-called additive hash is to add the input elements one by one to form the final result.

2. Bit operation hash: This type of Hash function fully mixes the input elements by using various bit operations (commonly shift and XOR)

3. Multiplication hash: 33 *hash key.charAt(i)

4. What is consistent hashing?

The design goal is to solve the hot spot problem in the Internet. The consistent hash algorithm proposes four definitions to determine the quality of the hash algorithm in the dynamically changing Cache environment: 1 , Balance (Balance) 2. Monotonicity (Monotonicity) 3. Dispersion (Spread) 4. Load (Load)

5. What are the paradigms in the database?

First normal form - tables in the database (all field values) are indivisible atomic data items.

Second Normal Form - Each column in the database table is related to the primary key, and cannot be related to only a certain part of the primary key.

Third normal form----Each column of data in the database table is directly related to the primary key and cannot be indirectly related. Normalization is to reduce data redundancy.

6. What is the structure of the index in the database? Under what circumstances is it appropriate to build an index?

The index structure in the database is a sorted data structure. The database index is implemented through B-trees and deformed B-trees. Under what circumstances is it not suitable to create an index: 1. For columns that are rarely used or referenced during queries; for columns with only few data values; for columns defined as image, text, and bit data types; when modifying performance Much greater than retrieval performance.

According to the system's own environmental conditions, the number of execution threads is effectively limited to achieve the best operating effect. Threads mainly control the number of threads executed. Threads that exceed the number wait in line, wait for a task to be executed, and then take out the task from the front of the queue for execution

7. Used below in the concurrent package What?

java.util.concurrent, java.util.concurrent.atomic and java.util.concurrent.lock

8. What are the commonly used databases? Have you ever used redis?

MySQL, SQL Server, Oracle database.

9. What open source protocols do you know?

GPL (GNU General Public License): GNU General Public License

LGPL (GNU Lesser General Public License): GNU Lesser General Public License

BSD

(Berkeley Software Distribution): Berkeley Software Distribution License Agreement

MIT (Massachusetts Institute of Technology): The name of MIT comes from the Massachusetts Institute of Technology

Apache (Apache License ): Apache License Agreement

MPL (Mozilla Public License): Mozilla Public License Agreement

10. In form submission, the difference between get and post

1. get obtains information from the server, and post transmits information to the server

2.get transmits a relatively small amount of data, while post can be larger

3.get has relatively low security

11. What is the difference between TCP protocol and UDP protocol? (answer answer)

The abbreviation of TCP (Tranfer Control Protocol) is a connection-oriented protocol that guarantees transmission. Before transmitting the data stream, both parties will first establish a virtual communication channel. Data can be transmitted with few errors.

The abbreviation of UDP (User DataGram Protocol) is a connectionless protocol. When using UDP to transmit data, each data segment is an independent piece of information, including the complete source address and destination. It is transmitted to the destination through any possible path on the network. Therefore, whether the destination can be reached, as well as the time to reach the destination and the integrity of the content cannot be guaranteed.

So TCP takes more time to establish a connection than UDP. Compared with UDP, TCP has higher security and reliability.

There is no limit to the size of TCP protocol transmission. Once the connection is established, both parties can transmit a large amount of data in a certain format, while UDP is an unreliable protocol with a size limit that cannot exceed 64K at a time

The above is the detailed content of Summary of the most common JAVA interview questions in 2020 (Collection). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete