Java interview real questions & reference answers [volume 1]

Tips: The following is a brief description of the real java interview questions. If you are interested in reading this article, and those who are about to interview, prepare a pen and paper if possible , and transfer it to your own knowledge. I hope the next interview will be good luck Again and again

Table of contents

1. What are the four access rights in Java? What can they modify respectively?

2. What is the difference between interface and abstract class in Java?

3. Talk about polymorphism in Java and how it is implemented.

4. What is multithreading and what is thread safety? When do thread safety issues arise? How to ensure thread safety?

5. Briefly describe the core functions of the Spring framework, including IOC and AOP.

6. What is the Mapper in the MyBatis framework? how to use?

7. What are the benefits of using frames regularly?

8. What is the difference between synchronized and Renntrantlock? How did the latter come about?

9. What is aqs?

10. Please briefly introduce the MySQL database, and explain its characteristics, advantages and disadvantages.


1. What are the four access rights in Java? What can they modify respectively?

    The four access rights are: public: protected: default: private:
    public: public modified classes, variables, methods, both inside and outside the package have access rights;
    protected: protected rights are designed for inheritance , the members modified by protected are accessible to all subclasses and classes in the same package, but not to outsourced non-subclasses; default: package access rights are only available to classes in the
    same package Permissions;
    private: private can only be used for the methods of this class (you can say a few more words about whether private can modify the class)

2. What is the difference between interface and abstract class in Java?

1) From the aspect of basic knowledge (extended learning)
The definition syntax of interfaces and abstract classes in Java are interface and abstract keywords respectively.
Abstract class: In Java, a class modified by the abstract keyword is called an abstract class, and a method modified by the abstract keyword is called an abstract method. An abstract method has only a method declaration and no method body.
Characteristics of abstract classes:
a. Abstract classes cannot be instantiated, but can only be inherited;
b. Those containing abstract methods must be abstract classes, but abstract classes do not necessarily contain abstract methods;
c. Modifiers of abstract methods in abstract classes It can only be public or protected, and the default is public;
d. If a subclass inherits an abstract class, the subclass must implement the abstract method of the parent class, otherwise the subclass must also be defined as an abstract class;
e. An abstract class can contain attributes and methods , construction method, but the construction method cannot be used for instantiation, the main purpose is to be called by subclasses.
Interface: The interface in Java is decorated with the interface keyword. The characteristics are:
a. The interface can contain variables and methods; variables are implicitly designated as public static final, and methods are implicitly designated as public abstract (before JDK1.8); b
. The interface supports multiple inheritance, that is, an interface can implement multiple interfaces, which indirectly solves the problem of single inheritance of classes in Java;
c. A class can implement multiple interfaces;
d. New features have been added to interfaces in JDK1.8: (1) default method: JDK 1.8 allows non-abstract method implementations to be added to interfaces, but must be modified with the default keyword; methods that define default can It is not implemented by the subclass, but can only be called by the object of the subclass; if the subclass implements multiple interfaces, and these interfaces contain the same default method, the subclass must override the default method; (2) static Method (static method): JDK 1.8 allows the use of the static keyword to modify a method and provide an implementation, which is called an interface static method. Interface static methods can only be called through the interface (interface name. static method name).
As shown in the following example:

public interface Person{
  public static final int a=10;
  //JDK1.8
    default void sayHello(){
        System.out.println("Hello World");
    }
    public void say();
}
public abstract class Person{
  public abstract void say();
  public void eat(){};
}

As shown in the above code:

An interface can only be the definition of a function, while an abstract class can be both a function definition and a function realization.

2) From the perspective of the interview: the difference between the interface and the abstract class
is the same:
(1) Neither can be instantiated (2) The implementation class of the interface or the subclass of the abstract class can only be instantiated after implementing the methods in the interface or abstract class change.
Differences:
(1) Interfaces only have definitions and cannot have method implementations. In Java 1.8, default method bodies can be defined, while abstract classes can have definitions and implementations, and methods can be implemented in abstract classes.
(2) The keyword for implementing an interface is implements, and the keyword for inheriting an abstract class is extends. A class can implement multiple interfaces, but a class can only inherit from one abstract class. Therefore, multiple inheritance can be achieved indirectly by using interfaces.
(3) The interface emphasizes the realization of specific functions, while the abstract class emphasizes the relationship of ownership.
(4) Interface member variables default to public static final, must be assigned an initial value, and cannot be modified; all its member methods are public and abstract. The member variables in an abstract class default to default, which can be redefined in subclasses or reassigned; abstract methods are modified by abstract, and cannot be modified by private, static, synchronized, and native. They must end with a semicolon without a flower brackets.

3. Talk about polymorphism in Java and how it is implemented.


    Three major characteristics of java object-oriented: Encapsulation and inheritance Polymorphism
    Polymorphism: the same type of behavior has the ability to have multiple different manifestations or forms. Java allows a subclass object to be directly assigned to a parent class reference variable without any type conversion , or known as upcasting, upcasting is done automatically by the compiler.
    Necessary conditions for polymorphism: 1. There must be inheritance (or interface implementation) 2. There must be rewriting 3. Parent class references point to subclass objects. Advantages of polymorphism: 1.
    Realize code reuse and avoid code redundancy; 2. Reduce the correlation between codes, that is, the degree of coupling, which is convenient for later modification of codes and improvement of functions, without having to affect the whole body, reducing unnecessary troubles; 3. By rewriting subclasses, Making different objects have different functions extends the functionality.
    Class methods implement polymorphism:
        1. Overloading (the number, order, and type of parameters are different)
        2. Method rewriting (the method name of the parent class and the subclass are the same)
        3. The parent class reference points to the subclass object (see the parent class during compilation) , look at the subclass during runtime)
        4. For static member methods and member variables: look at the left side for both compilation and operation

        Animal x = new Cat();//Upcasting
        x can only call the parent class method, and calling the subclass method will report an error
        Animal x = new Cat();
        Cat s = (Cat)x;//Downcasting
        s can be called Subclass and superclass methods


4. What is multithreading and what is thread safety? When do thread safety issues arise? How to ensure thread safety?


    Multithreading : Java multithreading refers to the ability to execute multiple threads simultaneously in the Java programming language. A thread is the execution unit of a program, which can execute multiple tasks at the same time, improving the concurrency and efficiency of the program.
        In Java, threads can be created and managed by creating an instance of the Thread class. The execution of a thread can be started using the start() method of the Thread class. In addition, you can also implement the Runnable interface and pass it to the constructor of the Thread class to create threads.
Multi-threaded programming can achieve the following purposes:
Improve the responsiveness of the program: Time-consuming tasks can be performed in the background while maintaining the interactivity of the program.
Improve system resource utilization: Make full use of CPU resources by executing multiple tasks at the same time.
Realize parallel computing: Split the task into multiple subtasks and assign them to different threads for parallel execution to speed up the calculation.
However, multi-threaded programming also needs to pay attention to issues such as thread safety, race conditions, deadlocks, etc., and it is necessary to design and synchronize threads reasonably to avoid these problems.
    Thread safety : Thread safety is a concept in computer program code when multi-threaded programming. In a program that is executed in parallel by multiple threads with shared data, the thread-safe code will ensure that each thread can execute normally and correctly through a synchronization mechanism, and there will be no accidents such as data pollution.
    Thread safety issues : Thread safety issues can arise in multithreaded programming, depending on several factors:

        Shared data: When multiple threads access and modify shared data concurrently, it can cause thread safety issues. For example, multiple threads writing to the same variable at the same time may cause data inconsistency or loss.

        Race Conditions: Race conditions can arise when the results of multiple threads during execution depend on each other's execution order. For example, two threads simultaneously read and write the same variable, which may lead to unexpected results due to the uncertainty of the execution order.

        Improper synchronization: If the synchronization mechanism is not used correctly in a multi-threaded environment, it may cause thread safety problems. For example, not properly using locks or other synchronization tools to protect shared data can lead to data inconsistency.

        Deadlock: A deadlock can occur when multiple threads wait for each other to release resources. In this case, all threads cannot continue to execute, causing the program to fail to run normally.

        The emergence of thread safety problems is caused by the concurrent execution of multiple threads. When multiple threads access and modify shared resources at the same time, it is necessary to use the synchronization mechanism correctly to ensure the consistency and correctness of the data.
    How to ensure thread safety:
        Atomic class (JUC): JDK has provided the java.util.concurrent.atomic package since 1.5. The atomic operation class in this package provides a simple, efficient, and thread-safe way to update a variable. Way. A total of 17 classes are provided in the atomic package, which can be summarized into 4 types of atomic update methods according to their functions, namely atomic update basic type, atomic update reference type, atomic update attribute, and atomic update array. Regardless of the type of atomic update, the "compare and replace" rule must be followed, that is, compare whether the value to be updated is equal to the expected value, update if it is, and fail if not.
        volatile : It is a lightweight synchronized, which ensures the "visibility" of shared variables and prevents instruction reordering in multiprocessor development, thereby ensuring thread safety when reading and writing a single variable. The visibility problem is caused by the caches of the processor cores, each core has its own cache, and these caches are synchronized with the memory. Volatile has the following memory semantics: when writing a volatile variable, the value of the shared variable in the thread local memory will be immediately refreshed to the main memory; when reading a volatile variable, the thread local memory will be invalidated, forcing Threads read shared variables directly from main memory.
        Lock: Atomic classes and volatile can only guarantee the thread safety of a single shared variable, while locks can guarantee the thread safety of multiple shared variables in the critical section. There are two ways to lock in Java, namely the synchronized keyword and the Lock interface. Synchronized is a relatively early API, which did not consider the timeout mechanism, non-blocking form, and multiple condition variables at the beginning of the design. If you want to upgrade it to support these relatively complex functions, you need to change its grammatical structure, which is not conducive to compatibility with old codes. Therefore, the JDK development team added the Lock interface in 1.5, and supported the above-mentioned functions through Lock, namely: support for responding to interrupts, support for timeout mechanisms, support for acquiring locks in a non-blocking manner, and support for multiple condition variables (blocking queues) ).


5. Briefly describe the core functions of the Spring framework, including IOC and AOP.


    The spring framework is a lightweight framework, the core of which is ioc control reversal and aop aspect-oriented programming;
    IOC: Spring IOC container management object, IoC is not a technology, but an idea, an important object-oriented programming rule, it It can guide us how to design loosely coupled and better programs. In traditional applications, we actively create dependent objects inside the class, which leads to high coupling between classes and is difficult to test; with the IoC container, the control of creating and finding dependent objects is given to the container, and the container Injecting combined objects, so objects are loosely coupled, which is also convenient for testing, conducive to function reuse, and more importantly, makes the entire architecture of the program very flexible.
    AOP: Aspect-oriented programming, aop is an idea and a supplement to object-oriented (oop) programming. Object-oriented programming abstracts the program into objects of various levels, while aspect-oriented programming abstracts the program into various aspects.
In the SpringMVC framework, what is the role of the controller? How to configure the controller?
    1. The controller is complex to provide the behavior of accessing the application, usually through interface definition or annotation definition. 2. The controller is responsible for parsing the user's request and converting it into a model. 3. In Spring MVC, a controller class can contain multiple methods. In Spring MVC, there are many ways to configure Controller.


6. What is the Mapper in the MyBatis framework? how to use?


    In the MyBatis framework, Mapper is an interface used to define methods for database operations. The Mapper interface defines the SQL statements that interact with the database, as well as the rules for mapping database result sets to Java objects.

        The methods in the Mapper interface usually correspond to CRUD operations (addition, deletion, modification, query) of the database, such as inserting data, updating data, deleting data, and querying data. The MyBatis framework will dynamically generate corresponding SQL statements according to the method name and parameters of the Mapper interface, and perform database operations.

        The implementation of the Mapper interface is automatically generated by the MyBatis framework, and there is no need to manually write the implementation class. In the configuration file of MyBatis, it is necessary to associate the Mapper interface with the corresponding mapping file (XML file), which defines the specific implementation of SQL statements and the mapping rules with Java objects.

        Through the method of the Mapper interface, we can conveniently perform database operations without writing cumbersome SQL statements and result set mapping codes. This makes database operations more concise and easier to maintain.


7. What are the benefits of using frames regularly?


There are several benefits to using a framework:

  • Improve development efficiency: The framework provides a series of tools, components and specifications, which can simplify the development process and reduce repetitive code writing. Developers can directly use the functions provided by the framework without having to build the application infrastructure from scratch, thus saving development time and effort.
  • Provide standardization and normalization: Frameworks usually follow a series of design principles, best practices, and standardized specifications, making the code structure clearer and more maintainable. Developers can develop based on the framework, follow the specifications of the framework, and improve the readability and maintainability of the code.
  • Provide high performance and optimization: Frameworks are usually optimized and tested to provide high-performance operation. The framework implements some complex algorithms and data structures under the hood to improve the performance and efficiency of the application.
  • Provide rich function extensions: The framework usually provides a rich function extension mechanism, which can selectively extend and customize functions according to needs. Developers can integrate their own code with the framework through plug-ins, modules, extension points, etc. to achieve more functions and business requirements.
  • Provide good documentation and community support: Common frameworks usually have comprehensive documentation and active community support. Developers can get help and solve problems through official documents, tutorials, sample codes, etc. Other developers in the community can also share experiences and provide support, speeding up the problem-solving and learning process.

        To sum up, the use of frameworks can improve development efficiency, standardize code, provide high performance and rich function extensions, and at the same time obtain documentation and community support, making the development process more convenient and efficient.


8. What is the difference between synchronized and Renntrantlock? How did the latter come about?


        Synchronized is a reusable lock . There are two ways to use it, method or code block. Locking is to pass in a person object or a static class. In fact, it is an operation on the object header, which will store the thread id in the object header. When the thread calls the lock for the second time, it will judge the Is the id the id in the lock? If so, he can directly operate it. Because it is managed by jvm itself, if the lock is released, it will be released directly when the run method is executed.

        ReentrantLock needs to be locked and released manually. First, we need to lock it and release it in finally. Compared with synchronized, ReentrantLock is more complicated to use. In terms of basic locking and unlocking, the two are the same, so it is recommended to use synchronized under no special circumstances. The advantage of ReentrantLock is that it is more flexible and powerful, adding advanced functions such as rotation training, timeout, and interruption

ReentrantLock is a reentrant lock in Java:

        Its implementation principle is based on AQS (AbstractQueuedSynchronizer). AQS is an abstract synchronizer, which provides a synchronization mechanism based on FIFO waiting queue, which can be used to implement various synchronizers, such as locks, semaphores, countdown timers, etc.

        ReentrantLock internally maintains a state variable to represent the state of the lock. When the state is , it means that the lock is unlocked; when the state is 1, it means that the lock is locked. When a thread requests a lock, if the state is, indicating that the lock is unlocked, then the thread can acquire the lock and set the state to 1; if the state is 1, indicating that the lock has been locked by other threads, then the thread It will be added to the waiting queue, waiting for other threads to release the lock.

        ReentrantLock also supports reentrancy, that is, the same thread can acquire the same lock multiple times without being blocked. This is achieved by maintaining an owner variable, which records the thread currently holding the lock. When a thread requests the lock again, if it is the thread currently holding the lock, it can directly acquire the lock without being blocked. When the thread releases the lock, it will decrement the state by 1. If the state becomes , indicating that the lock has been completely released, then it will wake up a thread in the waiting queue and let it acquire the lock.

        In short, the implementation principle of ReentrantLock is based on AQS. It implements the lock function by maintaining a state variable and a waiting queue. At the same time, it supports reentrancy and ensures that the same thread can obtain the same lock multiple times.


9. What is aqs?


        AQS is the abbreviation of the English word AbstractQueuedSynchronizer, which translates to queue synchronizer.
It is the basic framework for building locks or other synchronization components (such as ReentrantLock, ReentrantReadWriteLock, Semaphore, etc.), and the author of JUC (Doug Lea) expects it to be the basis for most synchronization requirements. It is the core basic component in the JUC concurrency package.
        The main way to use AQS is inheritance. Subclasses manage the synchronization state by inheriting the synchronizer and implementing its abstract methods.


10. Please briefly introduce the MySQL database, and explain its characteristics, advantages and disadvantages.


        MySQL is a relational database management system developed by the Swedish company MySQL AB and is currently a product of Oracle. MySQL is one of the most popular relational database management systems. In terms of WEB applications, MySQL is the best RDBMS (Relational Database Management System, relational database management system) application software.
        advantage:

  • Small size, fast speed, low total cost of ownership, open source, the interface provided supports multi-language connection operations
  • The core program of MySQL adopts complete multi-thread programming. Threads are lightweight processes that flexibly provide services to users without overwhelming system resources. MySQL implemented with multithreading and C language, making full use of CPU resources
  • There is a very flexible and secure permission and password system. When a client connects to a MySQL server, all password transfers between them are encrypted, and MySQL supports host authentication
  • Supports large databases, and can easily support databases with tens of millions of records. As an open source database, it can be modified for different applications
  • Support multiple operating systems, such as Linux, Windows, AIX, FreeBSD, HP-UX, MacOS, NovellNetware, OpenBSD, OS/2 Wrap, Solaris, etc.
  • Provide multi-language support, common encoding such as GB2312, BIG5, UTF8

        shortcoming:

  • Does not support hot backup
  • Custom data types are not supported
  • Not friendly enough for stored procedure and trigger support
  • The biggest disadvantage of MySQL is its security system, which is mainly complex rather than standard, and it only changes when calling mysqladmin to reread user permissions.

Guess you like

Origin blog.csdn.net/weixin_56800176/article/details/131815167