samwellwang

samwellwang

coder
twitter

Java Interview Questions and Analysis

I want to learn Java systematically and comprehensively. After all, I haven't learned anything useful in school, so I thought I would start with interview questions since I will need to find a job later anyway.

I want to learn Java systematically and comprehensively. After all, I haven't learned anything useful in school, so I thought I would start with interview questions since I will need to find a job later anyway. LeetCode is still too difficult for me, but I will definitely write a blog to learn LeetCode in the future. Let's start with some simple interview questions (which are actually not that simple). I randomly found a list of the most common 200+ Java interview questions online for reference, to fill in the gaps, and tackle them one by one!

[](#Java Basics "Java Basics")Java Basics#

1. What is the difference between JDK and JRE?#

This is simple. JDK stands for Java Development Kit, which is a set of Java development tools aimed at developers. It includes JRE and Java tools (like javac) as well as the Java core libraries. JRE stands for Java Runtime Environment, which is aimed at users of Java. It includes the JVM (Java Virtual Machine) and the core libraries.

2. What is the difference between == and equals?#

First, == is a comparison operator, while equals is a method provided by the Object class. equals can be overridden and is often overridden. When not overridden, == and equals have the same effect. When equals is overridden, it needs to be analyzed specifically. The principle is that the == operator compares values when dealing with primitive types and compares the memory addresses of two variables when dealing with reference types. equals generally compares the values pointed to by the memory addresses. It cannot be used for comparisons of primitive types. A common example is that the equals method under String compares whether the strings are the same.
For Integer and int, you can refer to the following code to recall the difference:

 public static void main(String[] args) {
    //-128 ~ +127 range
    Integer a = 5;
    int b = 5;
    Integer c = new Integer(5);
    Integer d = 5;

    System.out.println(a.equals(b));
    System.out.println(a == b);
    System.out.println(a.equals(c));
    System.out.println(a == c);
    System.out.println(a == d);

    //-128 ~ +127 range
    a = 128;
    b = 128;
    c = new Integer(128);
    d = 128;

    System.out.println(a.equals(b));
    System.out.println(a == b);
    System.out.println(a.equals(c));
    System.out.println(a == c);
    System.out.println(a == d);
}

Answer:

//-128 ~ +127 range
True True True False True  
//-128 ~ +127 range
True True True False False

3. If two objects have the same hashCode(), does that mean equals() will also be true?#

First, the answer is definitely not necessarily true, because both methods can be overridden, and it completely depends on the implementation.
hashCode() returns the hash code value of the object; equals() returns whether two objects are equal. However, there are some general agreements regarding hashCode and equals in the Java official documentation:

    1. If two objects return true when compared with equals(), then their hashCode() methods must return the same result.
    1. If two objects return false when compared with equals(), it is not required that their hashCode() methods return different values, but it is better to return different values to improve hash table performance.
    1. If equals() is overridden, hashCode() must also be overridden to ensure that when equals returns true, the hash codes of the two objects return the same value.

4. What is the role of final in Java?#

  • A class modified with final cannot be inherited.

  • A method modified with final cannot be overridden.

  • A variable modified with final is a constant and cannot be assigned a new value.
    For primitive data types, the value cannot change; for reference data types, the address cannot change, but the data pointed to by the address can be modified. The essence of a variable modified with final: a variable modified with final will point to a fixed memory location, and the value in that memory cannot be changed.

[](#5-What-is-the-value-of-Math.round(-1.5) in Java? "5. What is the value of Math.round(-1.5) in Java?")5. What is the value of Math.round(-1.5) in Java?#

The answer is -1. The round function directly adds 0.5 and then rounds down: -1.5 + 0.5 = -1, rounded down to -1.

-1.4 + 0.5 = -0.9 rounded down to -1. -1.6 + 0.5 = -1.1 rounded down to -2.

6. Is String a basic data type?#

It is obviously not. String is an object, a reference type. The basic types in Java are only:
byte

  • 8-bit signed integer, represented in two's complement

  • Minimum is -128 (-2^7), maximum is 127 (2^7-1), default value is 0

  • The byte type is used in large arrays to save space, mainly replacing integers, as byte variables occupy only a quarter of the space of int variables.

  • Example: byte a = 100, byte b = -50
    short

  • 16-bit signed integer, represented in two's complement

  • Minimum value is -32768 (-2^15), maximum is 32767 (2^15-1), default value is 0

  • The short variable occupies half the space of int.

  • Example: short s = 1000, short r = -20000
    int

  • 32-bit signed integer, represented in two's complement

  • Minimum value is -2147483648 (-2^31), maximum value is 2147483647 (2^31-1)

  • Default value is 0, generally integer defaults to 0
    long

  • 64-bit signed integer, represented in two's complement

  • Minimum value is (-2^63), maximum value is (2^63-1), default value is 0L

  • Example: long a = 100000L, Long b = -200000L

  • This type is mainly used in systems that require large integers.
    float

  • float is single precision, 32-bit, floating-point number compliant with IEEE 754 standard

  • float can save memory when storing large floating-point arrays

  • Default value is 0.0f, floating-point numbers cannot represent precise values, such as currency.

  • Example: float f1 = 0.2f
    double

  • double is double precision, 64-bit floating-point number compliant with IEEE 754 standard

  • Floating-point numbers default to double, and also cannot represent precise values

  • Default value is 0.0d

  • Example: double d1 = 0.2d.
    boolean

  • boolean represents 1 bit of information

  • Only two values, true OR false

  • Default value is false

  • Example: boolean b = true
    char

  • char type is a single 16-bit Unicode character

  • Minimum value is \u0000 (which is 0) and maximum value is \uffff (65535)

  • char can store any character.

  • Example: char A = 'A';
    The above basic type information is organized from Rookie Tutorial

[](#7-What-classes-are-used-to-manipulate-strings-in-Java? What-are-their-differences? "7. What classes are used to manipulate strings in Java? What are their differences?")7. What classes are used to manipulate strings in Java? What are their differences?#

All three are strings stored in the form of char[].

  • String: Does not support modification; modifying it means creating a new object.

  • StringBuffer: Thread-safe, used in multi-threading. Not necessary to use.

  • StringBuilder: Not thread-safe, but fast, used in single-threading.

[](#8-Is-String-str-"i"-the-same-as-String-str-new-String-"i"? "8. Is String str="i" the same as String str=new String("i")?")8. Is String str="i" the same as String str=new String("i")?#

This goes back to question 2. equals() is equal, but the result of the == operation is false because when str="i", the Java Virtual Machine allocates "i" to the constant pool, and there are no duplicate elements in the constant pool. If there is another variable like str2="i", it will allocate the address of "i" in the constant pool to str2. If not, it will create a new one, while creating a new object allocates it to heap memory. Even if the values are the same, the addresses are different.

9. How to reverse a string?#

Using the reverse() method of StringBuffer and StringBuilder. Or convert to a char array and loop through it.

10. What are the common methods of the String class?#

  • int indexOf()

  • int length(String ch)

  • String subString(int beginIndex, int endIndex), inclusive of the beginning and exclusive of the end

  • String trim()

  • boolean equals()

  • toLowerCase(), toUpperCase()

  • char charAt(int index)

  • String[] split(String regex, int limit) The first parameter is the basis for splitting, and the second is the number of splits.

  • There are many more, but I am too lazy to write them…. Very rarely used.

11. Must an abstract class have abstract methods?#

No, an abstract class can be defined with the abstract modifier and may not contain abstract methods. If it contains one abstract method, it must be an abstract class. Even if there are no abstract methods, it cannot be instantiated.

12. What are the differences between a normal class and an abstract class?#

A normal class can be instantiated, while an abstract class cannot. Subclasses of an abstract class must implement all abstract methods of the abstract class unless the subclass is also an abstract class.

13. Can an abstract class be modified with final?#

Absolutely NO! A final modifier cannot be inherited, so what is the point of an abstract class? An abstract class is meant to be inherited… What a ridiculous question.

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

An interface can be understood as the abstraction of an abstract class, consisting entirely of abstract methods. A class can only inherit one abstract class but can implement multiple interfaces. This achieves multiple inheritance….

15. What are the types of IO streams in Java?#

Finally, we reach my knowledge blind spot…
Input streams and output streams are further divided into byte streams and character streams, which are further divided into node streams and processing streams.

  • Input streams

    • Input character stream Reader
      • Node streams FileReader, PipedReader, CharArrayReader
      • Processing streams BufferedReader, InputStreamReader
    • Input byte stream InputStream
      • Node streams FileInputStream, PipedInputStream, ByteArrayInputStream
      • Processing streams BufferedInputStream, DataInputStream, ObjectInputStream, SequenceInputStream
  • Output streams

    • Output character stream Writer
      • Node streams FileWriter, PipedWriter, CharArrayWriter
      • Processing streams BufferedWriter, OutputStreamWriter, PrintWriter
    • Output byte stream OutputStream
      • Node streams FileOutputStream, PipedOutputStream, ByteArrayOutputStream
      • Processing streams BufferedOutputStream, DataOutputStream, ObjectOutputStream, PrintStream

16. What is the difference between BIO, NIO, and AIO?#

IO methods are usually divided into several types: synchronous blocking BIO, synchronous non-blocking NIO, and asynchronous non-blocking AIO.
This is also a blind spot~ I have researched but still don’t understand it well, and need to delve deeper into it.

17. What are the common methods of Files?#

  • Files.exists() checks if the file path exists
  • Files.createFile() creates a file
  • Files.createDirectory() creates a folder
  • Files.delete() deletes a file
  • Files.copy() copies a file
  • Files.move() moves a file
  • Files.size() checks the number of files
  • Files.read() reads a file
  • Files.write() writes to a file

II. Containers#

What are the containers in Java?#

List, Set, Map, Queue, Stack;

What is the difference between Collection and Collections?#

Collection is the interface for collections, such as List, Set, etc., which inherit from it.
Collections is a utility class (sort, addAll, max) that creates empty collections.

What is the difference between List, Set, and Map?#

List is an ordered list, similar to an array. It stores elements in the order they were added.
Set is a collection that stores unique elements, equivalent to only storing the keys in a Map.
Map is in the form of key-value pairs.

What is the difference between HashMap and Hashtable?#

HashMap is not synchronized, thread-unsafe, but efficient. It was released later in version 1.2.
Hashtable is basically not used anymore, except for Properties, which inherits from Hashtable. Also, it does not use camel case naming, haha.

How to decide when to use HashMap or TreeMap?#

Use HashMap when you do not need to sort the keys; use TreeMap when you need to sort them.

What is the implementation principle of HashMap?#

HashMap is implemented using an array and linked list. It performs a hashCode() operation on the key to obtain a hash value, and then uses the modulus operation with the length of the array to get the index, which is the position for insertion into the array. It uses a linked list to handle hash collisions, meaning when the same index is encountered, it checks whether the key values are the same (equals). If they are the same, it replaces the original value. If they are different, it places it in the next node of the linked list.

What is the implementation principle of HashSet?#

It is a wrapper around HashMap, using an immutable Object as the value.

What is the difference between ArrayList and LinkedList?#

ArrayList is implemented using an array, while LinkedList is implemented using a linked list. Therefore, the advantages and disadvantages are also very clear. ArrayList is fast for lookups, while LinkedList is fast for insertions and deletions.

How to convert between arrays and List?#

Array to List: Arrays.asList()
List to array: list.toArray()

What is the difference between ArrayList and Vector?#

Vector is a thread-safe list and is basically not used anymore.

What is the difference between Array and ArrayList?#

Arrays can hold both primitive data types and object types but can only hold one type, while ArrayList can only hold object types but can hold multiple types without using generics.
ArrayList is implemented based on dynamic arrays, with a variable size, while arrays are fixed in size.

What is the expansion mechanism of ArrayList?#

The essence of ArrayList's expansion is to calculate the size of the new expanded array, instantiate it, and copy the contents of the original array into the new array.

What is the difference between poll() and remove() in Queue?#

Both delete and return the head element of the queue; remove will throw an error (throw NoSuchElementException) if the queue is empty, while poll will return false or null.

Which collection classes are thread-safe?#

Vector, Hashtable, Stack

What is an Iterator?#

An Iterator is a tool used to traverse collections.

[](#How-to-use-Iterator? What-are-its-characteristics? "How to use Iterator? What are its characteristics?")How to use Iterator? What are its characteristics?#

next returns the next element, hasNext checks if there is a next element, remove deletes the returned element.

What is the difference between Iterator and ListIterator?#

Iterator can traverse set, map, and list, while ListIterator can only traverse List but can traverse both forwards and backwards.

How to ensure a collection cannot be modified?#

Collections.unmodifiableList(List)

III. Multithreading#

What is the difference between parallelism and concurrency?#

  • Parallelism: Multiple processors simultaneously processing multiple different tasks. This is physically simultaneous.

  • Concurrency: A single processor can handle multiple tasks simultaneously. This is logically simultaneous.
    eg: Concurrency: One person eats three apples at the same time. Parallelism: Three people eat three apples at the same time.

    #### [](#What-is-the-difference-between-threads-and-processes? "What is the difference between threads and processes?")What is the difference between threads and processes?
    
    A process is a task, while a thread is a sub-task of a process. The smallest unit of scheduling by the operating system is a thread.
    
    #### [](#What-is-a-daemon-thread? "What is a daemon thread?")What is a daemon thread?
    
    A daemon thread is a thread that serves other threads. In the JVM, when all non-daemon threads have finished executing, the virtual machine will automatically exit, regardless of whether there are daemon threads or not.  
    Therefore, when the JVM exits, there is no need to worry about whether daemon threads have ended.
    
    #### [](#What-are-the-ways-to-create-threads? "What are the ways to create threads?")What are the ways to create threads?
    
    1. Create a thread class by extending the Thread class: derive a custom class from Thread and override the run() method.
    2. Create a thread class using the Runnable interface: create a Thread instance and pass in a Runnable instance.
    3. Create a thread using Callable and Future:

    What is the difference between runnable and callable?#

    1. As shown in the code above, the core of callable is the call method, which allows for a return value, while the core of runnable is the run method, which does not have a return value.
  1. The call method can throw exceptions, but the run method cannot.

  2. Because runnable has been around since Java 1.1, it does not have a return value. Later, in Java 1.5, it was optimized, leading to the introduction of callable, which allows for return values and exception throwing.

What are the states of threads?#

  • New: A newly created thread that has not yet executed;

  • Runnable: A running thread that is executing Java code in the run() method;

  • Blocked: A running thread that is suspended due to being blocked by some operation;

  • Waiting: A running thread that is waiting due to some operation;

  • Timed Waiting: A running thread that is waiting for a specified time due to executing the sleep() method;

  • Terminated: A thread that has terminated because the run() method has finished executing.

    What is the difference between sleep() and wait()?#

    What is the difference between notify() and notifyAll()?#

    What is the difference between run() and start() in threads?#

    What are the ways to create a thread pool?#

    What are the states of a thread pool?#

    What is the difference between submit() and execute() in a thread pool?#

    How to ensure thread safety in a Java program?#

    What is the upgrade principle of multithreading locks?#

    What is deadlock?#

    How to prevent deadlock?#

    [](#What-is-ThreadLocal? What-are-its-usage-scenarios? "What is ThreadLocal? What are its usage scenarios?")What is ThreadLocal? What are its usage scenarios?#

    What is the underlying implementation principle of synchronized?#

    What is the difference between synchronized and volatile?#

    What is the difference between synchronized and Lock?#

    What is the difference between synchronized and ReentrantLock?#

    What is the principle of atomic?#

    IV. Reflection#

    What is reflection?#

    Reflection refers to the ability of a program to obtain all information about an object at runtime. It is designed to solve the problem of how to call methods on an instance when nothing is known about it at runtime. Reflection is a key property that allows Java to be considered a dynamic (or quasi-dynamic) language. This method of obtaining class information through Class instances is called reflection.

    [](#What-is-Java-serialization? When-is-serialization-necessary? "What is Java serialization? When is serialization necessary?")What is Java serialization? When is serialization necessary?#

    Putting an object into IO, implementing the Serializable interface.
    Serialization refers to converting a Java object into binary content, essentially a byte[] array.

    [](#What-is-dynamic-proxy? What-are-its-applications? "What is dynamic proxy? What are its applications?")What is dynamic proxy? What are its applications?#

    Dynamic proxy provided by JDK allows for the dynamic creation of interface objects.
    It creates an instance of a certain interface at runtime without writing an implementation class.
    It creates a proxy object through Proxy and delegates the interface methods to
    InvocationHandler handler. Applications of dynamic proxy include Spring AOP, Hibernate data querying, backend mock for testing frameworks, RPC, and obtaining Java annotation objects.

    How to implement dynamic proxy?#

  1. Define an InvocationHandler instance that is responsible for implementing the method calls of the interface;
  2. Create an interface instance using Proxy.newProxyInstance(), which requires three parameters:
  • The ClassLoader being used, usually the ClassLoader of the interface class;
  • An array of interfaces to be implemented, at least one interface must be passed in;
  • An InvocationHandler instance used to handle the method calls of the interface.
  1. Cast the returned Object to the interface.

V. Object Copy#

Why use cloning?#

How to implement object cloning?#

Implement the Cloneable interface and override clone();

What is the difference between deep copy and shallow copy?#

Shallow copy refers to reference object properties pointing to the memory address of the original object;
Deep copy means completely new, where referenced other objects are also copied.

VI. Java Web#

What is the difference between jsp and servlet?#

JSP represents the front-end page, while servlet is the middle layer between the server and the browser. At runtime, JSP is compiled into a servlet by the web container (Tomcat).

[](#What-are-the-built-in-objects-in-jsp? What-are-their-functions? "What are the built-in objects in jsp? What are their functions?")What are the built-in objects in jsp? What are their functions?#

  • request: The request from the user, which includes parameters from GET/POST requests.

  • response: The response sent back to the user.

  • pageContext: The attributes of the page are managed here.

  • session: The session related to the request.

  • application: The content being executed by the servlet.

  • out: Used to send the output of the response.

  • config: The configuration component of the servlet.

  • page: The JSP page itself.

  • exception: For error pages, uncaught exceptions.

    What are the four scopes of jsp?#

    NameScope
    applicationValid for the entire application
    sessionValid for the entire session
    requestValid for the current request
    pageValid for the current page

Generally speaking, cookies record the session ID; sessions are server-side, while cookies are client-side.

What is the working principle of session?#

After the server creates the session object, it returns the ID of the session object to the client in the form of a cookie. Thus, when the user accesses the server again while keeping the current browser open, the session ID will be sent to the server, and the server will provide the corresponding service based on the session ID.

Can session still be used if the client disables cookies?#

Yes, by passing the session ID through the URL.

What is the difference between spring mvc and struts?#

How to prevent sql injection?#

Use PreparedStatement with ? as a placeholder, or use named variables.

What is XSS attack and how to prevent it?#

What is CSRF attack and how to prevent it?#

VII. Exceptions#

What is the difference between throw and throws?#

throws is at the end of a method, indicating that this method may throw an exception, and when calling this method, it must be try-catch or throw the exception. throw is used within the method, generally written in catch.

What is the difference between final, finally, and finalize?#

final describes a method that cannot be overridden, a class that cannot be inherited, and a variable that is a constant.
finally is after try-catch.
finalize() is a method in Object that is called when the JVM determines that an object is dead, allowing it to make a final struggle (for example, if this method is overridden to redirect it to GC roots, the GC algorithm will not reclaim it).

Which part of try-catch-finally can be omitted?#

Either catch or finally can be omitted.

[](#If-return-is-used-in-catch-in-try-catch-finally, will finally still execute? "If return is used in catch in try-catch-finally, will finally still execute?")If return is used in catch in try-catch-finally, will finally still execute?#

Yes, it will execute after the return expression. Changes made to it will not affect the return value.

What are the common exception classes?#

Error, RuntimeException, Exception, and throw.

VIII. Networking#

[](#What-do-http-response-codes-301-and-302-represent? What-is-the-difference? "What do http response codes 301 and 302 represent? What is the difference?")What do http response codes 301 and 302 represent? What is the difference?#

301 redirect: 301 represents permanent move (Permanently Moved)

302 redirect: 302 represents temporary move (Temporarily Moved)

What is the difference between forward and redirect?#

This guy explains it very well

Briefly describe the difference between tcp and udp?#

TCP: Connection-oriented, reliable, meaning it will not lose or duplicate data, and it is in order. Three-way handshake. Byte-oriented.
UDP: Connectionless, unreliable. Message-oriented. But fast, can broadcast.

[](#Why-does-tcp-require-three-way-handshake? Why-not-two? "Why does tcp require three-way handshake? Why not two?")Why does tcp require three-way handshake? Why not two?#

No, because two can only guarantee that one-way connection is smooth, but cannot guarantee that both ways are smooth.

What is the cause of tcp sticky packets?#

The speed at which the application reads data packets from the cache is slower than the speed at which data packets are received, causing multiple data packets in the cache to be read as one packet at once.

What are the seven layers of the OSI model?#

Application layer
Presentation layer
Session layer
Transport layer
Network layer
Data link layer
Physical layer

What are the differences between get and post requests?#

Get is used to retrieve data from the server, while post is used to send data to the server.

How to implement cross-domain?#

Briefly describe the implementation principle of JSONP?#

IX. Design Patterns#

What design patterns are you familiar with?#

Abstract factory pattern.

What is the difference between simple factory and abstract factory?#

Simple factory handles objects with lower complexity, while abstract factory handles objects with higher complexity;
The simple factory pattern is the actual factory - abstract class - implementing different products.
The abstract factory is the abstract factory - different factories (implementing different product families) - different products (inheriting from the abstract class of products).

X. Spring/Spring MVC#

Why use spring?#

To reduce development complexity, facilitate integration with other frameworks like Mybatis and Hibernate, avoid reinventing the wheel, and focus on business logic.
Supports AOP (Aspect-Oriented Programming), separating components that are not related to business logic but span multiple business areas, such as logging, transactions, security, etc., into reusable components.

Explain what AOP is?#

AOP stands for Aspect-Oriented Programming.
First, in the idea of aspect-oriented programming, functionalities are divided into core business functionalities and peripheral functionalities.
Core business functionalities include login, adding data, deleting data, etc.
Peripheral functionalities include performance statistics, logging, transaction management, etc.
Peripheral functionalities are defined as aspects in Spring's AOP.
In AOP, core business functionalities and aspect functionalities are developed independently.
Then, the aspect functionalities and core business functionalities are "woven" together, which is called AOP.

Explain what Ioc is?#

Inversion of Control.
Simply put, the creation of objects has shifted from programmers manually calling the constructor to Spring creating the objects.

What are the main modules of spring?#

  1. Spring Core
    The most basic part of the framework, providing the IOC container and managing beans.
  2. Spring Context
    Based on beans, providing context information, extending functionalities like JNDI, EJB, email, internationalization, validation, and scheduling.
  3. Spring DAO
    Provides an abstraction layer for JDBC, eliminating redundant JDBC coding and parsing database vendor-specific error codes, and also provides methods for declarative transaction management.
  4. Spring ORM
    Provides an integration layer for Object/Relational Mapping APIs, including JPA, JDO, Hibernate, MyBatis, etc.
  5. Spring AOP
    Provides an implementation of aspect-oriented programming that complies with AOP Alliance specifications.
  6. Spring Web
    Provides basic context information for web development and can integrate with other web frameworks.
  7. Spring MVC
    Provides a full-featured implementation of the Model-View-Controller for web applications.

What are the common injection methods in spring?#

Constructor injection,
Setter injection,
Annotation injection.

Are beans in spring thread-safe?#

The container itself does not provide a thread-safe strategy, meaning it does not have thread safety characteristics. It needs to be analyzed in conjunction with the specific scope of the bean.
(The scope of beans: singleton, prototype, request, session, global session)
Prototype mode: A new object is created each time, and each thread uses its own, so there is no shared thread safety issue.
Singleton mode: If it is a stateless bean, meaning calling this bean does not change its state (field properties), then it is safe. The method itself is safe. For stateful beans, the simplest solution is to change it to prototype mode.
Beans created by Spring default to singleton, and when a thread calls a bean, it holds a copy of the bean object in its own space. Because the execution speed of the code is very fast, the lifetime of the stack frame is very short, and it is created and destroyed instantly. Therefore, local variables cannot be used externally. When you call the global variable of this bean object, thread safety issues will arise (at this point, you need to define the bean as prototype).

What scope of beans does spring support?#

  • Singleton mode: In singleton mode, there is only one instance of the bean defined with singleton in the entire Spring IOC container.

  • Prototype: In prototype mode, each time the prototype-defined bean is obtained through the container's getBean method, a new instance is created.

  • Only in web applications using Spring, request, session, and global-session scopes are effective.

  • Request: For each HTTP request, a new instance of the bean defined with request will be created, meaning each HTTP request will produce a different bean instance.

  • Session: A bean instance is shared within the same session.

  • Global-session: Unlike session scope, all sessions share a single instance.

    What are the ways to autowire beans in spring?#

    The autowire parameter of the node in the spring configuration file can control the way beans are autowired.

  • default - The default method is the same as the "no" method.

  • no: The default method, manual wiring, requires setting the dependency relationship of the bean through .

  • byName: Autowires based on the name of the bean. When a bean's name matches the property of another bean, it is autowired.

  • byType: Autowires based on the type of the bean. When the property type of a bean matches the data type of another bean's property, it is autowired.

  • constructor: Autowires based on the constructor. Similar to byType, if the constructor of the bean has properties of the same type as other beans, it is autowired.

  • autodetect: If there is a default constructor, it autowires using the constructor method; otherwise, it autowires using the byType method.

    What are the transaction implementation methods in spring?#

    (1) Programmatic transaction management is the only choice for POJO-based applications. We need to call methods related to transaction management like beginTransaction(), commit(), rollback() in the code, which is programmatic transaction management.
    (2) Declarative transaction management based on TransactionProxyFactoryBean.
    (3) Declarative transaction management based on @Transactional.
    (4) Transaction management based on AspectJ AOP configuration.

    What is the transaction isolation in spring?#

    Read uncommitted;
    Read committed;
    Repeatable read;
    Serializable;

    What is the running process of spring mvc?#

  1. The user sends a request to the front controller DispatcherServlet.
  2. DispatcherServlet receives the request and calls the handler mapping HandlerMapping.
  3. The handler mapping finds the specific handler based on the request URL and generates a handler execution chain HandlerExecutionChain (including the handler object and handler interceptor) and returns it to DispatcherServlet.
  4. DispatcherServlet obtains the handler adapter HandlerAdapter from the handler and executes the HandlerAdapter to perform a series of operations such as parameter encapsulation, data format conversion, data validation, etc.
  5. The handler (Controller, also called the page controller) is executed.
  6. The handler returns ModelAndView after execution.
  7. The HandlerAdapter returns the execution result ModelAndView to DispatcherServlet.
  8. DispatcherServlet passes the ModelAndView to the ViewResolver.
  9. The ViewResolver parses and returns the specific View.
  10. DispatcherServlet renders the View (i.e., fills the model data into the View).
  11. DispatcherServlet responds to the user.

My understanding can describe the process from V to C to M to C and then back to V.

What are the components of spring mvc?#

Front controller DispatcherServlet
Handler mapping
Handler adapter
View resolver
Handler exception resolver
View component

What is the purpose of @RequestMapping?#

It is an annotation used to handle request address mapping and can be used on classes or methods. When used on a class, it indicates that all methods in the class that respond to requests use that address as the parent path.

What is the purpose of @Autowired?#

The autowiring annotation: it can mark class member variables, methods, and constructors, allowing Spring to complete the automatic wiring of beans.

XI. Spring Boot/Spring Cloud#

What is spring boot?#

"Spring Boot is a sub-project under the Spring open-source framework, a one-stop solution for Spring, mainly simplifying the difficulty of using Spring and reducing the requirements for configuration files, making it easier for developers to get started."

Spring Boot is a large framework that contains many things, with Spring being one of the core contents.

Why use spring boot?#

To simplify the difficulty of using Spring. It integrates various frameworks, web containers, etc.

What are the core configuration files of spring boot?#

application.properties && bootstrap.properties
application.yml && bootstrap.yml
The bootstrap configuration file is at the system level, used to load external configurations, such as configuration center information, and can also define properties that do not change. The bootstrap file is loaded before the application file.
The application configuration file is at the application level, which is the configuration file for the current application.
Properties are key=value, while bootstrap is key.

[](#What-types-of-configuration-files-does-spring-boot-have? What-are-their-differences? "What types of configuration files does spring boot have? What are their differences?")What types of configuration files does spring boot have? What are their differences?#

The previous question.

What are the ways to achieve hot deployment in spring boot?#

Using debug mode to achieve hot deployment.
spring-boot-devtools
Spring Loaded
JRebel

What is the difference between jpa and hibernate?#

Hibernate ORM is an implementation of the JPA specification.
Java Persistence API
JPA is a specification for Java programming language interfaces that describes the management of relational data using the standard JAVA platform and JAVA Enterprise Edition. The JPA API is part of the Java Community Expert Group for JSR220, and JPA2.0 is the work of the JSR317 Expert Group.

What is spring cloud?#

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g., configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boilerplate patterns, and using Spring Cloud, developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer’s own laptop, bare metal data centers, and managed platforms such as Cloud Foundry.
According to the official website of Spring Cloud, Spring Cloud provides tools for developers to quickly build some common patterns in distributed systems (such as configuration management, service discovery, circuit breakers, intelligent routing, leadership election, distributed sessions, cluster state). The coordination between distributed systems generates some boilerplate patterns, and developers can quickly build services and applications based on these patterns using Spring Cloud.

What is the role of the circuit breaker in spring cloud?#

When a service calls another service and encounters problems due to network reasons or its own issues, the caller will wait for the response from the callee. When more service requests reach these resources, it leads to more requests waiting, causing a chain reaction (avalanche effect). The circuit breaker solves this problem.

What are the core components of spring cloud?#

  • Service discovery - Netflix Eureka

    A RESTful service used to locate middleware services running in AWS regions. It consists of two components: the Eureka server and the Eureka client. The Eureka server acts as a service registration server. The Eureka client is a Java client that simplifies interaction with the server, acts as a polling load balancer, and provides service failover support. Netflix uses a different client in its production environment, which provides weighted load balancing based on traffic, resource utilization, and error status.

  • Client-side load balancing - Netflix Ribbon

    The Ribbon client component provides a series of comprehensive configuration options, such as connection timeout, retries, retry algorithms, etc. Ribbon has built-in pluggable and customizable load balancing components.

  • Circuit breaker - Netflix Hystrix

    The circuit breaker prevents an application from repeatedly attempting to perform an operation that is likely to fail, allowing it to continue without waiting for the failure to recover or wasting CPU cycles, while allowing the application to detect whether the failure has been resolved. If the problem seems to have been corrected, the application can attempt to call the operation.

  • Service gateway - Netflix Zuul
    Microservice gateway, this component is responsible for network routing.

  • Feign

    Based on the dynamic proxy mechanism of Feign, it constructs the URL address based on annotations and selected machines, initiating requests. Feign is a declarative web service client that makes it easier to write web service clients. Feign is a templated, declarative HTTP client that can bind to interfaces via annotations to simplify HTTP request access. Unlike when we access other service ports, which mostly use HttpClient and other requests, we can use Feign in the form of declaring interfaces to call related services registered in Eureka, and it provides fallback (which is actually the use of the Hystrix component). Feign is just a convenient REST framework that simplifies calls, ultimately still finding service instances in the registration server through Ribbon and allocating requests.

XII. Hibernate#

Why use hibernate?#

Fully automated ORM framework.

What is an ORM framework?#

Object-Relational Mapping, linking database and code instances.

How to view printed SQL statements in the console in hibernate?#

How many query methods are there in hibernate?#

Can hibernate entity classes be defined as final?#

What is the difference between using Integer and int for mapping in hibernate?#

How does hibernate work?#

What is the difference between get() and load()?#

What is the cache mechanism in hibernate?#

What are the states of hibernate objects?#

What is the difference between getCurrentSession and openSession in hibernate?#

[](#Must-hibernate-entity-classes-have-a-no-argument-constructor? Why? "Must hibernate entity classes have a no-argument constructor? Why?")Must hibernate entity classes have a no-argument constructor? Why?#

XIII. Mybatis#

Semi-automated ORM framework.

What is the difference between #{} and ${} in mybatis?#

#{} represents a placeholder, calling the set method of PreparedStatement to assign values.
${} is string replacement, which replaces ${} with the value of the variable.
Using #{} can effectively avoid SQL injection and improve system security because of the pre-compilation mechanism. After pre-compilation, the structure of the SQL is fixed, so even if the user inputs illegal parameters, it will not affect the structure of the SQL, thus avoiding potential security risks.

How many pagination methods are there in mybatis?#

Four pagination methods in mybatis

  • Array pagination: Query all and put them into a list, then slice logically.

  • SQL pagination: limit(); physical.

  • Interceptor pagination: Implement an interceptor physically.

  • RowBounds pagination: When the data volume is small; logical.

[](#Is-RowBounds-a-one-time-query-for-all-results? Why? "Is RowBounds a one-time query for all results? Why?")Is RowBounds a one-time query for all results? Why?#

On the surface, it queries all, but in fact, it queries all in batches, based on JDBC encapsulation. The JDBC driver has a parameter called Fetch Size configuration; to query more, it calls next().

What is the difference between logical pagination and physical pagination in mybatis?#

Logical pagination means querying all and then splitting the pagination data from the results;
Physical pagination means that the data is already paginated when queried.

[](#Does-mybatis-support-lazy-loading? What-is-the-principle-of-lazy-loading? "Does mybatis support lazy loading? What is the principle of lazy loading?")Does mybatis support lazy loading? What is the principle of lazy loading?#

It supports lazy loading; set lazyLoadingEnabled=true to enable it.
The principle of lazy loading is that loading is triggered when called, rather than loading information during initialization. It first queries from a single table, and when needed, it queries from the associated table, greatly improving database performance.

What are the first-level cache and second-level cache in mybatis?#

  • First-level cache: Local cache based on PerpetualCache's HashMap, its lifecycle is consistent with sqlSession. If multiple sessions or operations in a distributed environment may have dirty data, when the session flushes or closes, all caches in that session will be cleared. By default, the first-level cache is enabled.

  • Second-level cache: Also based on PerpetualCache's HashMap, the difference is that its storage scope is at the Mapper level. If multiple sqlSessions want to share the cache, the second-level cache must be enabled.

  • Cache update mechanism: When a scope performs CUD operations, all selects under the default scope are cleared.

What are the differences between mybatis and hibernate?#

Semi-ORM and fully-ORM frameworks.
Mybatis allows for flexible SQL writing but has poor portability. Hibernate can use third-party second-level caches.

What executors are there in mybatis?#

  • SimpleExecutor: Each time an update or select is executed, a Statement object is opened and closed immediately after use.

  • ReuseExecutor: When executing update or select, it looks up the Statement object using SQL as the key. If it exists, it uses it; if not, it creates it. After use, it does not close the Statement object but places it in a Map for the next use. In short, it reuses the Statement object.

  • BatchExecutor: Batch executor.

What is the implementation principle of the pagination plugin in mybatis?#

(The implementation principle of the pagination plugin PageHelper)[https://www.cnblogs.com/dengpengbo/p/10579631.html]

How to write a custom plugin in mybatis?#

MyBatis custom plugins intercept the four main objects of MyBatis (Executor, StatementHandler, ParameterHandler, ResultSetHandler). MyBatis plugins must implement the Interceptor interface.

XIV. RabbitMQ#

XV. Kafka#

[](#Can-kafka-be-used-independently-of-zookeeper? Why? "Can kafka be used independently of zookeeper? Why?")Can kafka be used independently of zookeeper? Why?#

No, because kafka needs zookeeper to manage and coordinate the kafka node servers. Kafka is a distributed messaging system coordinated based on zookeeper.

What are the data retention strategies in kafka?#

Two types: retention based on expiration time (default is 7 days) and retention based on the size of stored messages (1073741824).

[](#If-both-7-days-and-10G-of-data-clearing-are-set-in-kafka, what-will-happen-if-the-message-reaches-10G-on-the-fifth-day? "If both 7 days and 10G of data clearing are set in kafka, what will happen if the message reaches 10G on the fifth day?")If both 7 days and 10G of data clearing are set in kafka, what will happen if the message reaches 10G on the fifth day?#

Data clearing will be executed; whichever condition is met will result in data being cleared.

What factors can slow down kafka?#

CPU, performance bottlenecks, disk read/write bottlenecks, network bottlenecks.

What should be noted when using kafka cluster?#

The number of clusters is not better the more there are; it is best not to exceed 7, as the more nodes there are, the longer it takes to replicate messages, which lowers the overall throughput of the group. It is best to set the cluster number to an odd number, as if more than half of the cluster fails, the group cannot be used, and setting it to an odd number increases fault tolerance.

How does kafka ensure data is not lost?#

Kafka can ensure the order of partition messages; messages sent to a kafka partition will be consumed in the order they were sent.
Kafka provides services through a cluster, and as long as one replica in the multiple replicas in the cluster is active, the received messages will not be lost.
It mainly needs to ensure that data is not lost in three places:

  • Ensure that producer data is not lost.
    Kafka's acks mechanism allows the producer client to set the acks parameter to 0, 1, or all. 0 means that the producer considers it successful as soon as it sends it. 1 means that the partition leader is considered successful once it is written. Setting it to all means that it also requires that those partitions that are in ISR and leader must also write successfully.
  • Ensure that broker data in the cluster is not lost.
    Topics are divided into different data (partition 0, partition 1) and stored on different brokers, ensuring that topic data is distributed. Each partition has corresponding replicas, some of which are partition 0 leader and partition 0 follower. It is evident that the number of replicas cannot exceed the number of brokers. If the leader fails, a follower is elected as the leader. The replicas that keep in sync with the leader are ISR, while those that do not are OSR, AR=ISR+OSR.
  • Ensure that consumer data is not lost.
    This is ensured through the offset commit mechanism, where Kafka records the offset value of each consumption, and when continuing to consume, it will continue from the last offset.

What is the consumer consumption process?#

Consumers in the same consumer group can consume different partitions under the same topic, but consumers within the same group cannot consume the same partition. Therefore, it is recommended that the number of consumers in the consumer group match the number of partitions!

[](#Why-use-Kafka? What-is-the-role-of-message-queues? "Why use Kafka? What is the role of message queues?")Why use Kafka? What is the role of message queues?#

  • Peak shaving: If user requests are too large, the server may not be able to handle it. First, store it in the message queue, then process it slowly.
  • Decoupling and scalability: It allows different systems to decouple, facilitating expansion. It solves the problem of excessive coupling between different systems.
  • Redundancy: One-to-many, one producer publishes messages that can be consumed by multiple services subscribing to the topic, serving multiple unrelated businesses.
  • Asynchronous communication: Client A, client B, client N subscribe to the same topic, publishing and receiving messages, achieving a chatroom-like effect.

Detailed configuration parameters of Kafka#

KafKa configuration parameters detailed explanation

XVI. Zookeeper#

What is Zookeeper?#

ZooKeeper is an open-source distributed coordination service that acts as a manager for clusters, monitoring the status of various nodes in the cluster and performing reasonable operations based on the feedback submitted by the nodes. Ultimately, it provides users with a simple and easy-to-use interface along with a high-performance, stable system.

What are the functions of Zookeeper?#

Zookeeper = file system + notification mechanism

  • File system
    Zookeeper can manage state information for clients, although the number of stored items is relatively small (each node cannot exceed 1M by default).
  • Notification mechanism
    It can listen to the status of specified data nodes for clients and notify them when the data nodes change.

What are the deployment modes of Zookeeper?#

Deployment modes: standalone mode, pseudo-cluster mode, cluster mode.

How does Zookeeper ensure the synchronization of master and slave nodes?#

The core of Zookeeper is atomic broadcast, which ensures synchronization between servers. The protocol that implements this mechanism is called the ZAB protocol, which has two modes: recovery mode (election of the leader) and broadcast mode (synchronization). When the service starts or the leader crashes, ZAB enters recovery mode. When the leader is elected and most servers complete synchronization with the leader, recovery mode ends. State synchronization ensures that the leader and servers have the same system state.

Why is there a master node in a cluster?#

In a distributed environment, some business logic only needs to be executed by a specific machine in the cluster. Other machines can share the results, which greatly reduces redundant calculations and improves performance. Therefore, a master node is needed.

[](#If-one-node-in-a-cluster-of-three-servers-fails, can-Zookeeper-still-be-used? "If one node in a cluster of three servers fails, can Zookeeper still be used?")If one node in a cluster of three servers fails, can Zookeeper still be used?#

Yes, as long as no more than half of the servers are down, it can continue to be used.

Describe the notification mechanism of Zookeeper#

Clients establish a watcher event on a certain znode. When the znode changes, these clients receive notifications from Zookeeper, allowing them to make business changes based on the znode changes.

XVII. MySql#

What are the three normal forms of databases?#

1NF: Fields cannot be further divided.
2NF: There is a primary key, and other non-primary key fields depend on the primary key.
3NF: Non-primary key fields do not depend on each other.

[](#If-a-self-incrementing-table-has-7-rows-of-data, and-the-last-2-rows-are-deleted, what-will-the-id-be-when-a-new-row-is-inserted-after-restarting-the-mysql-database? "If a self-incrementing table has 7 rows of data, and the last 2 rows are deleted, what will the id be when a new row is inserted after restarting the mysql database?")If a self-incrementing table has 7 rows of data, and the last 2 rows are deleted, what will the id be when a new row is inserted after restarting the mysql database?#

If the table type is InnoDB, it will be 6, as the maximum record of the self-incrementing table is stored in memory and lost upon restart.
If the table type is MyISAM, it will be 8, as the maximum record is stored in the data and remains after a restart (MyISAM does not support transactions).

How to get the current database version?#

select version()
cmd: mysql -v

What is ACID?#

A: Atomicity: Transactions are indivisible; they either complete fully or not at all, and do not remain in an intermediate state. If an error occurs in the middle, it will roll back to the state before it started.
C: Consistency: The database transitions from one consistent state to another consistent state, maintaining data integrity.
I: Isolation: Multiple transactions do not affect each other.
D: Durability: After a transaction ends, the data is permanently recorded, and it will not disappear even if the system fails.

What is the difference between char and varchar?#

char is fixed length; the allocated length is what it is, and any shortage is padded.
varchar is variable length; it changes according to the actual situation, with actual length + 1 byte to store the length itself.

What is the difference between float and double?#

Both are floating-point numbers, with the difference being single precision and double precision.

What is the difference between inner join, left join, and right join in mysql?#

Inner join is join, left join is left join, and right join is right join. There is a diagram that can represent this well; I will find it…

How is indexing implemented in mysql?#

B+ tree, a separate blog Learning MySQL Index

How to verify if mysql indexes satisfy requirements?#

The leftmost matching principle; once a range condition is encountered, the index will not be effective.
Indexes with null values will not be effective.

What is the transaction isolation in databases?#

Read uncommitted: Can read uncommitted data; this is problematic.
Read committed: The default isolation level of Oracle databases.
Repeatable read: For non-repeatable reads, ordinary queries even if snapshot queries. The default isolation level of MySQL.
Serializable: The most stringent, transactions are executed serially, avoiding all issues but with poor efficiency.

Why does "dirty read" occur? Because there are no rules for "select" operations.
Why does "non-repeatable read" occur? Because there are no rules for "update" operations.
Why does "phantom read" occur? Because there are no rules for "insert" and "delete" operations.
What can "Read Uncommitted" prevent? Nothing.
What can "Read Committed" prevent? Using "snapshot read" to avoid "dirty reads," but it may still lead to "non-repeatable reads" and "phantom reads."
What can "Repeatable Read" prevent? Using "snapshot read" to lock the read records, avoiding "dirty reads" and "non-repeatable reads," but it may still lead to "phantom reads."
What can "Serializable" prevent? It effectively avoids "dirty reads," "non-repeatable reads," and "phantom reads," but the effectiveness is known only to those who use it.

What are the common engines in mysql?#

InnoDB, MyISAM (does not support transactions)
Because transactions and row locks are often the reasons we choose InnoDB tables.

What is the difference between row locks and table locks in mysql?#

Table locks are generally used by MyISAM, with low overhead, fast locking, no deadlocks, and low concurrency.
Row locks are generally used by InnoDB, with high overhead, slow locking, possible deadlocks, and high concurrency.
InnoDB will only use row-level locks if data is retrieved through index conditions; otherwise, it will use table locks!

What is the difference between optimistic locking and pessimistic locking?#

Optimistic locking: uses a version to record the version of the record in the data table.
Pessimistic locking: exclusive locks and shared locks.

[](#What-are#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.