current position:Home>Collection of interview questions for java development in 2022

Collection of interview questions for java development in 2022

2022-06-24 09:22:23m0_ sixty-one million eighty-three thousand four hundred and ni

List of articles

java Basic knowledge interview questions

1. What are the features of object-oriented ?

Object - oriented features have abstractions 、 Inherit 、 Encapsulation and polymorphism .

abstract : Abstract is the process of summing up the common characteristics of a class of objects to construct a class , Including data abstraction and behavior abstraction . Abstractions only focus on the properties and behaviors of objects , Not paying attention to the details of these behaviors .
Inherit : Inheritance is the process of getting inheritance information from an existing class to create a new class , Classes that provide inheritance information are called superclasses , A class that gets inheritance information is called a subclass .
encapsulation : Encapsulation is the binding of data and methods of manipulating data , Access to data can only be through defined interfaces .
polymorphism : Polymorphism allows objects of different subtypes to respond differently to the same message , It can be divided into compile time polymorphism and runtime polymorphism .

2. What is? JDK,JDK and JRE What's the difference ?

JDK yes Java Development ToolKit For short , That is to say Java Development kit .

JRE yes Java The runtime environment and what will be executed Java The virtual machine of the program , It also contains the browser plug-ins needed to execute the program .
JDK Is a full Java Software development kit , Contains JRE, Allows developers to develop 、 compile 、 perform Java Applications .

3.== and equals() Differences in methods ?

== The role of

Basic types : The comparison is whether the values are the same
Reference type : The comparison is whether the address values are the same

equals The role of

Reference type : By default , The comparison is the address value .
, :String、Integer、Date In these class libraries equals Be rewritten , Compare the content, not the address !

==: Compare two string memory addresses ( Heap memory ) Whether the values of are equal , It belongs to numerical comparison ; equals(): Compare the contents of two strings , It belongs to content comparison .

4.Java What are the basic data types ?

Integer type byte、short、int、long, Floating point types have float、double, The character types are char、 Boolean type :boolean

5. Access modifier public,private,protected And not to write (defualt) The difference of time ?

Java in , You can use the access modifier to protect the class 、 Variable 、 Access to methods and constructors , Support 4 Different access rights .

1.private : Visible in the same category , Use object : Variable 、 Method , Cannot decorate external classes
2.default : Visible in the same package , Don't use any modifiers , Use object : class 、 Interface 、 Variable 、 Method .
3.protected : Visible to classes and all subclasses in the same package , Use object : Variable 、 Method , Cannot decorate external classes .
4.public : Visible to all classes , Use object : class 、 Interface 、 Variable 、 Method

6. The difference between overloading and rewriting ?

heavy load : Occurs in the same class , Method name must be the same , Different parameter types . The number is different. . Different order , Method return values and access modifiers can be different , Occurs at compile time .

rewrite : Occurs in a parent-child class , Method name . The parameter list must be the same , The return value range is less than or equal to the parent class , Thrown difference The constant range is less than or equal to the parent class , The access modifier range is greater than or equal to the parent class ; If the parent method access modifier is private Then the subclass cannot override the method .

7.this and super What's the difference? ?

this: Represents the current object itself ,super: Represents the parent class of the current object .

8.String and StringBuffer、StringBuilder The difference between ?

String String constant
StringBuffer String variable ( Thread safety )
StringBuilder String variable ( Non-thread safety )

String Medium String Class final Keywords modify character arrays to hold strings ,private final char value[] ,String Object is immutable , It can be understood as a constant , Thread safety .
StringBuffer Add a synchronization lock to the method or a synchronization lock to the called method , So it's thread safe .
StringBuilder Method is not locked synchronously , So it's non thread safe .

9. What is the difference between an interface and an abstract class ?

Realization : A subclass of an abstract class extends To inherit ; Interface must be used implements To implement the interface .
Constructors : Abstract classes can have constructors ; Interface cannot be .
main Method : Abstract classes can have main Method , And we can run it ; Interface cannot be main Method .
To achieve the number : Classes can implement many interfaces ; But you can only inherit from one abstract class .
Access modifier : Methods in the interface are used by default public modification ; Methods in an abstract class can be arbitrary access modifiers、finally、finalize What's the difference? ? Modifiable class 、 Variable 、 Method , Modifying a class means that it cannot be inherited 、 Decorating a method means that the method cannot be overridden 、 When decorating a variable, it means that the variable is a constant and cannot be re assigned .
2.finally The general effect is try-catch Block of code , When handling exceptions , Usually, the code that must be executed is placed in finally Block of code . Indicates whether or not an exception has occurred , This code block will execute , It is usually used to store some code for closing resources .
3.finalize yes Object class , It is used to realize garbage collection . The finalize() Method , You can override this method to recycle other resources .

11. What is singleton mode ? There are several kinds of ?

The singleton pattern : The instance of a class is in In a multithreaded environment, it will only be created once .

The singleton mode has hungry Chinese singleton mode 、 There are three modes: lazy single case mode and double check lock single case mode .

Hungry Chinese style : Thread safety , Initialize from the beginning .
Slacker type : Non-thread safety , Delay initialization .
Double check lock : Thread safety , Delay initialization .

12.List and Map、Set The difference between

List and Set Is a collection of data that stores a single column ,Map Is a collection of double column data that stores key value pairs .

List The data stored in is sequential , And the value can be repeated ;
Map The data stored in is out of order , Its keys are not allowed to be repeated , But values are allowed to be repeated ;
Set The data stored in is out of order , And no repetition is allowed , But the position of the element in the collection is determined by the hashcode decision , That is, the position is fixed (Set Set is based on hashcode To store data , So the position is fixed , But this location is not user controllable , So for users set The elements in are still out of order ).

13.List、Map、Set When three interface access elements , What are the characteristics of each ?

List There is a put order when accessing elements , Elements can be repeated
Map Key value pairs are stored when accessing elements , There is no insertion order
Set Element has no put order when accessing element , Elements cannot be repeated

14. Let's talk about common collections ?

1.Collection The sub interfaces of the interface include :Set Interface and List Interface ;
2.Map Interface implementation classes mainly include :

As Map The main implementation class of , Thread unsafe , Efficient , Can be stored null Of key and value.
HashMap Bottom : Arrays and linked lists (jdk7) Array , Chain list and red black tree (jdk8)
yes HashMap Subclasses of , Make sure to traverse map Element time , The traversal can be implemented in the order of addition , For frequent traversal operations , Its execution efficiency is higher than HashMap.
reason : In the original HashMap Based on the underlying structure , Added a pair of pointers , Points to the previous and subsequent elements .
Make sure to follow the added key-value To sort , Implement sort traversal , Consider... At this time key Natural sort or custom sort . Use black and red trees at the bottom
towards TreeMap Add key-value Yes , requirement key Must be an object created by the same class , Because it's based on key sorted .
Hashtable As an ancient implementation class , Thread safety , Low efficiency , Can't store null Of key and value. The bottom layer uses hash table structure , Fast query speed .
And HashMap similar , The difference is :key and value None of the values of are allowed to be null; It supports thread synchronization , That is, only one thread can write at any time Hashtable, So it also led to Hashtale It's slower to write , Only hashtable It is inherited from Dictionary The abstract class ,hashMap and treeMap Inherit from AbstractMap abstract class ,LinkedHashMap Inherited from hashMap.

3.Set Interface implementation classes mainly include :

The underlying data structure is the hash table .( disorder , only )
How to ensure element uniqueness
Rely on two methods :hashCode() and equals()
The underlying data structure is linked list and hash table .(FIFO Insert in order , only )
1. The elements are ordered by the linked list
2. The hash table ensures that the elements are unique
The underlying data structure is a red-black tree .( only , Orderly )
1. How to ensure that elements are sorted
Natural ordering
Comparator sort
2. How to ensure the uniqueness of elements
According to whether the return value of the comparison is 0 To decide

4.List Interface implementation classes mainly include :

advantage : The underlying data structure is an array , Quick query , Add or delete slowly .
shortcoming : Thread unsafe , Efficient
advantage : The underlying data structure is an array , Quick query , Add or delete slowly .
shortcoming : Thread safety , Low efficiency , Have given up
advantage : The underlying data structure is a linked list , Slow query , Additions and deletions quickly .
shortcoming : Thread unsafe , Efficient

15.BIO、NIO、AIO What's the difference? ?

BIO:Block IO Synchronous blocking type IO, It's the tradition that we use IO, It is characterized by the simple use of the pattern , Low concurrency .
NIO:New IO Synchronous nonblocking IO, It's tradition IO The upgrade , Client side and server side through Channel( passageway ) Communications , Multiplexing is realized .
AIO:Asynchronous IO yes NIO The upgrade , Also called NIO2, Asynchronous non - blocking is realized IO , asynchronous IO Is based on event and callback mechanisms .

16.Hashmap and hashtable ConcurrentHashMap difference

Difference and contrast (HashMap and HashTable difference )

1、HashMap It's not thread safe ,HashTable It's thread safe .
2、HashMap Both the key and the value of are allowed null The value is , and HashTable No way. .
3、 Because of thread safety ,HashMap Efficient than HashTable You have to be tall .
4、Hashtable It's synchronous , and HashMap No . therefore ,HashMap More suitable for single line
Process environment , and Hashtable Suitable for multithreaded environment . Generally, it is not recommended to use HashTable, ①
yes HashTable Is a legacy class , Many internal implementations are not optimized and redundant .② Even in a multithreaded environment ,
Now there are synchronous ones ConcurrentHashMap replace , There's no need to use... Because it's multithreaded

17. What is a thread pool ? Why use thread pool ?

Thread pool : It is to create multiple executable threads in advance and put them into a container , Get it from the container when you need it instead of creating it yourself . When the thread is used up, it does not need to destroy the thread but put it back into the container , This reduces the overhead of creating and destroying Thread objects .

Using thread pools can avoid frequent creation and destruction of threads .
Using thread pool can flexibly control the number of concurrency according to the project .

18.Java in sleep() Methods and wait() What's the difference ?

sleep() Methods and wait() Methods can pause the execution of a thread , The difference lies in :

1. Class differences :sleep() The method is Thread Static methods of thread classes ,wait() The method is Object Class method .
2. Whether to release the lock :sleep() Method does not release the lock ;wait() Method release lock .
3. Different uses :wait() Methods are usually used for communication between threads ,sleep() Method is usually used to pause execution .
4. Use different :wait() After method is called , The thread will not wake up automatically before the timeout , Unless another thread calls... On the same object notify() Methods or notifyAll() Method .sleep() After method execution , Thread will wake up automatically .

19.ArrayList and LinkedList What's the difference ?

ArrayList Random access is supported LinkedList I won't support it .
ArrayList It is implemented through arrays , Insertion and deletion will be affected by the position of the element and will cause displacement .
LinkeList Use a two-way linked list to store data , Inserts and deletions are not affected by element position .
ArrayLIst Some space will be reserved , The actual space of the array is smaller than the storage space .
linkedlist No space is reserved , Only when an element is added can the memory space corresponding to this element be applied .
ArrayList Performing frequent lookups is more efficient than LinkedList high .
LinkedList Performing frequent inserts and deletions is more efficient than Arraylist high

20.Java What are the common exceptions

java.lang.IllegalAccessError: Illegal access error . When an application attempts to access 、 Modify the domain of a class (Field) Or call its method , However, it violates the visibility declaration of the domain or method , Then throw the exception .

java.lang.InstantiationError: Instantiation error . When an app tries to pass Java Of new The exception is thrown when the operator constructs an abstract class or interface .

java.lang.OutOfMemoryError: Out of memory error . When available memory is not enough for Java This error is thrown when the virtual machine is assigned to an object .

java.lang.StackOverflowError: Stack overflow error . This error is thrown when an application's recursive call level is too deep to cause a stack overflow or a dead loop .

java.lang.ClassCastException: Class modeling exception . Suppose there are classes A and B(A No B The parent or subclass of ),O yes A Example , So when coercion will O Construct as a class B The exception is thrown when an instance of . This exception is often referred to as a cast exception .

java.lang.ClassNotFoundException: Class exception not found . When an application attempts to construct a class based on the class name in the form of a string , And traversing CLASSPAH After that, we can't find the corresponding name of class When you file , Throw the exception .

java.lang.ArithmeticException: The arithmetic condition is abnormal . for example : Divide integer by zero, etc .

java.lang.ArrayIndexOutOfBoundsException: Array index out of bounds exception . When the index value of the array is negative or greater than or equal to the size of the array .

java.lang.IndexOutOfBoundsException: Index out of range exception . When the index value of accessing a sequence is less than 0 Or greater than or equal to the sequence size , Throw the exception .

java.lang.InstantiationException: Instantiation exception . When trying to pass newInstance() Method to create an instance of a class , When the class is an abstract class or interface , Throw the exception .

java.lang.NoSuchFieldException: Property has no exception . Throw this exception when accessing a nonexistent property of a class .

java.lang.NoSuchMethodException: Method has no exception . This exception is thrown when accessing a nonexistent method of a class .

ava.lang.NullPointerException: Null pointer exception . When an application tries to use an object where it requires it null when , Throw the exception . for example : call null The instance method of the object 、 visit null Object properties 、 Calculation null Length of object 、 Use throw Statement throw null wait .

ava.lang.NumberFormatException: The number format is abnormal . When trying to put a String Convert to the specified number type , When the string does not meet the format required by the number type , Throw the exception .

java.lang.StringIndexOutOfBoundsException: String index out of bounds exception . When using index values to access characters in a string , The index value is less than 0 Or greater than or equal to the sequence size , Throw the exception .

21.Java in IO There are several kinds of streams

  • according to IO Flow direction of flow , It can be divided into input flow and output flow
  • according to IO Division of operation unit of flow , It can be divided into byte stream and character stream
  • according to IO Implementation function division of flow , It can be divided into node flow and processing flow

22.Java There are several ways to create multithreads in ?

  • Inherit Thread Class and rewrite run Method to create a thread , The implementation is simple, but you can't inherit other classes
  • Realization Runnable Interface and override run Method . Avoid the limitations of single inheritance , Programming is more flexible , Realize decoupling .
  • Realization Callable Interface and override call Method , Create thread . You can get the return value of the thread execution result , And you can throw out exceptions
    often .
  • Use thread pool to create ( Use java.util.concurrent.Executor Interface )

23. Runnable Interface and Callable Interface differences ?

Runnable Interface run() Method has no return value , Only runtime exceptions can be thrown , And can't capture processing .
Callable Interface call() Method has a return value , Allow exceptions to be thrown , You can get exception information .

24. How to start a new thread 、 call start and run Differences in methods ?

Thread object calls run Method does not open the thread . It's just objects calling methods .
Thread object calls start Open thread , And let jvm call run Method is executed in the open thread

call start Method to start a thread , And put the thread into a ready state , and run It's just thread A common way to , Or execute in the main thread .

25. What kinds of states do threads have and the transitions between them ?

  1. The first is the new-> New state . Generating Thread objects , There is no call to start Method , This is the thread in the creation state .
  2. The second is Runnable-> Ready state . When the thread object is called start After method , The thread is in a ready state , But at this time, the thread scheduler has not set the thread as the current thread , It's in a ready state .
  3. The third is Running-> Running state . The thread scheduler sets the ready thread to the current thread , At this point, the thread enters the running state , Began to run run The code in the function .
  4. The fourth is the blocking state . Blocking is when the thread gives up for some reason CPU Right to use , Stop running temporarily . Until the thread is ready , To have a chance to go to run state . There are three types of obstruction :
    (1) wait for – By calling the thread's wait() Method , Let a thread wait for the completion of a task .
    (2) Overtime waiting – By calling the thread's sleep() or join() Or send out I/O When asked , The thread will enter a blocked state . When sleep() Status timeout 、join() Wait for the thread to terminate or timeout 、 perhaps I/O When it's done , Thread is ready again .
    (3) Synchronous blocking – The thread is getting synchronized Synchronization lock failed ( Because the lock is occupied by other threads ), It will enter the synchronous blocking state .
  5. The fifth is dead-> Death state : The thread executes or exits due to an exception run() Method , The thread ends its life cycle
     Insert picture description here

26.Java The flow of classloader

Class starts from being loaded into virtual machine memory , Until the memory is unloaded , Its entire life cycle includes : load (Loading)、 verification (Verification)、 Get ready (Preparation)、 analysis (Resolution)、 initialization (Initialization)、 Use (Using) And uninstall (Unloading)7 Stages . Which verifies 、 Get ready 、 analysis 3 The parts are collectively called connections (Linking).

7 The sequence of phases is shown in the following figure :
 Insert picture description here

27. Tell me about you ioc Container understanding (Inverse of Control Inversion of control )

Spring There are two types of containers

  • BeanFactory
  • ApplicationContext


The base type IoC Containers , Provide complete IoC Service support , If there is no special designation , By default, the delayed initialization strategy is adopted . Only when the client object needs to access a managed object in the container , The managed object is initialized and dependency injected . So relatively speaking , The initial start-up speed of the container is faster ( Because the delay initializes ), The resources needed are limited . For limited resources , And the functional requirements are not very strict ,BeanFactory Is more suitable for . But then again ,Bean Factories are often too low level for most applications , So I don't use


ApplicationContext Is in BeanFactory On the basis of construction , Is a relatively advanced container implementation , Except for Bean All factory support ,ApplicationContext Other advanced uses are also available , Such as event release

ApplicationContext Indirectly inherited from BeanFactory

28.Redis What are the storage structures of

String, character string , yes redis The most basic type of , One key Corresponding to one value. It's binary safe , Maximum energy storage 512MB.

Hash, hash , It's a key value (key=>value) The collection .string Type of field and value Mapping table , Ideal for storing objects . Every hash Can be stored 232 -1 Key value pair (40 More than )

List, list , Is a simple list of strings , Sort by insertion order . You can add an element to the side or end of the column ( On the right ). Up to 232 - 1 Elements (4294967295, Each list can be stored 40 Billion )

Set, aggregate , yes string Unordered collection of type , The maximum number of members is 232 -1(4294967295, Each collection can store 40 More than 100 million members ).

Sorted set, Ordered set , and set The same is true. string Collection of type elements , And duplicate members are not allowed . The difference is that each element is associated with a double Score of type .redis It's the scores that sort the members of a collection from small to large .zset Members of are unique , But fractions (score) But it can be repeated .

29.SpirngBoot The benefits of

(1) Simplified configuration , You don't need to write too many xml The configuration file
(2) be based on Spring structure , Get developers up to speed , The threshold is very low
(3)SpringBoot You can create applications that run independently without relying on containers
(4) built-in tomcat The server , It doesn't need to be packed into war package , You can put it directly into tomcat Run in
(5) Provide maven Minimalist configuration , And visual related monitoring functions , For example, performance monitoring , The health of the application, etc
(6) Service for micro SpringCloud Laid the foundation , Make the construction of microservices simple
(7)Spring It can integrate many and various frameworks , And can be well integrated
(8) Active communities and forums , And rich development documents

30. Have you ever encountered circular dependency ? How to solve

What is circular dependence

When one ClassA Depend on ClassB, then ClassB In turn, it depends on ClassA, This creates a circular dependency :
ClassA -> ClassB -> ClassA

① The cyclic dependence of constructors : This dependence spring It can't be dealt with , straight Then throw out BeanCurrentlylnCreationException abnormal .
② In singleton mode setter Cyclic dependence : adopt “ Three level cache ” Deal with circular dependencies .
③ Non singleton cyclic dependence : Unable to deal with .

copyright notice
author[m0_ sixty-one million eighty-three thousand four hundred and ni],Please bring the original link to reprint, thank you.

Random recommended