Complete Works of Java Interview Questions(9)

Complete Works of Java Interview Questions(9)

Baiyu IT haha

80. What is the ACID of a transaction?

answer:

  • Atomic: All operations in the transaction are either done or not done at all. The failure of any one operation will cause the failure of the entire transaction;
  • Consistent: The system state is consistent after the transaction ends;
  • Isolation (Isolated): concurrently executed transactions cannot see each other's intermediate state;
  • Durable: The changes made after the transaction is completed will be persisted, even if a catastrophic failure occurs. Data can be reconstructed after a failure occurs through log and synchronous backup.

Supplement: Regarding affairs, the probability of being asked in an interview is very high, and there are many questions that can be asked. The first thing to know is that transactions are only required when there are concurrent data accesses. When multiple transactions access the same data, there may be five types of problems, including three types of data read problems (dirty reads, non-repeatable reads, and phantom reads) and two types of data update problems (type 1 missing updates and type 2 Lost update).

Dirty Read: Transaction A reads the uncommitted data of Transaction B and operates on this basis, and Transaction B performs a rollback, then the data read by A is dirty data.

Complete Works of Java Interview Questions(9)

Unrepeatable Read: Transaction A rereads the previously read data and finds that the data has been modified by another committed transaction B.

Complete Works of Java Interview Questions(9)

Phantom Read: Transaction A re-executes a query and returns a series of rows that meet the query conditions. It is found that rows submitted by transaction B are inserted.
Time statistics amount transaction A transfer transaction B
Complete Works of Java Interview Questions(9)
type 1 lost update: When transaction A is cancelled, the updated data of transaction B that has been submitted is overwritten.
Complete Works of Java Interview Questions(9)
The second type of lost update: transaction A overwrites the data that transaction B has committed, causing the operation of transaction B to be lost.
Complete Works of Java Interview Questions(9)

The problems caused by concurrent access to data may be allowed in some scenarios, but may be fatal in some scenarios. The database usually solves the problem of concurrent access to data through a lock mechanism, which can be divided into table-level locks and locks according to different lock objects. Row-level locks can be divided into shared locks and exclusive locks according to the locking relationship of concurrent transactions. You can check the information to understand the specific content.
It is very troublesome to use locks directly. For this reason, the database provides users with an automatic lock mechanism. As long as the user specifies the transaction isolation level of the session, the database will analyze SQL statements and add appropriate locks to the resources accessed by the transaction. In addition, the database It will also maintain these locks to improve the performance of the system through various means, which are transparent to the user (that is, you don't need to understand, in fact I don't know). The ANSI/ISO SQL 92 standard defines 4 levels of transaction isolation levels, as shown in the following table:
Complete Works of Java Interview Questions(9)

It should be noted that the transaction isolation level and the concurrency of data access are opposite. The higher the transaction isolation level, the worse the concurrency. Therefore, the appropriate transaction isolation level must be determined according to the specific application. There is no universal principle in this place.

81. How to deal with transactions in JDBC?

Answer: Connection provides a method of transaction processing, by calling setAutoCommit(false) you can set to manually commit the transaction; when the transaction is completed, use commit() to explicitly commit the transaction; if an exception occurs during transaction processing, use rollback() to perform the transaction Roll back. In addition, the concept of Savepoint has been introduced from JDBC 3.0, allowing you to set a savepoint through code and roll back the transaction to the specified savepoint.
Complete Works of Java Interview Questions(9)

82. Can JDBC handle Blob and Clob?

Answer: Blob refers to Binary Large Object, and Clob refers to Character Large Objec, so Blob is designed to store large binary data, and Clob is to store large text data And designed. JDBC's PreparedStatement and ResultSet both provide corresponding methods to support Blob and Clob operations. The following code shows how to use JDBC to operate LOB:
Take MySQL database as an example, create a user table with three fields, including ID, name, and photo. The table statement is as follows:


create table tb_user
(id int primary key auto_increment,
name varchar(20) unique not null,
photo longblob );

The following Java code inserts a record into the database:


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class JdbcLobTest {
    public static void main(String[] args) {
        Connection con = null;
        try {
            // 1. 加载驱动(Java6以上版本可以省略)
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 建立连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
            // 3. 创建语句对象
            PreparedStatement ps = con.prepareStatement("insert into tb_user values (default, ?, ?)");
            ps.setString(1, "骆昊");              // 将SQL语句中第一个占位符换成字符串
            try (InputStream in = new FileInputStream("test.jpg")) {    // Java 7的TWR
                ps.setBinaryStream(2, in);      // 将SQL语句中第二个占位符换成二进制流
                // 4. 发出SQL语句获得受影响行数                System.out.println(ps.executeUpdate() == 1 ? "插入成功" : "插入失败");
            } catch(IOException e) {
                System.out.println("读取照片失败!");
            }
        } catch (ClassNotFoundException | SQLException e) {     // Java 7的多异常捕获
            e.printStackTrace();
        } finally { // 释放外部资源的代码都应当放在finally中保证其能够得到执行
            try {
                if(con != null && !con.isClosed()) {                    con.close();    // 5. 释放数据库连接 
                    con = null;     // 指示垃圾回收器可以回收该对象
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

83. Briefly describe regular expressions and their uses.

Answer: When writing programs that process strings, there is often a need to find strings that meet certain complex rules. Regular expressions are tools used to describe these rules. In other words, regular expressions are codes that record text rules.

Note: In the early days of the computer’s birth, almost all information processed was numeric values, but time has passed. Today we use computers to process information more often than numeric values ​​but strings. Regular expressions are the most powerful for string matching and processing. Tools, most languages ​​provide support for regular expressions.

84. How does Java support regular expression operations?

Answer: The String class in Java provides methods to support regular expression operations, including matches(), replaceAll(), replaceFirst(), split(). In addition, the Pattern class can be used to represent regular expression objects in Java. It provides a rich API for various regular expression operations. Please refer to the code of the interview questions below.

Interview questions:-If you want to intercept the string before the first English left parenthesis from the string, for example: Beijing (Chaoyang District) (Xicheng District) (Haidian District), the interception result is: Beijing, then the regular expression how to write?


import java.util.regex.Matcher;import java.util.regex.Pattern;
class RegExpTest {
    public static void main(String[] args) {
        String str = "北京市(朝阳区)(西城区)(海淀区)";
        Pattern p = Pattern.compile(".*?(?=\\()");
        Matcher m = p.matcher(str);
        if(m.find()) {
            System.out.println(m.group());
        }
    }
}
  • 14

Note: Lazy matching and look ahead are used in the above regular expressions. If you are not sure about these contents, I recommend reading the well-known "Regular Expression 30-Minute Tutorial" on the Internet.

85. What are the ways to obtain a class object?

answer:

  • Method 1: Type.class, for example: String.class
  • Method 2: Object.getClass(), for example: "hello".getClass()
  • 方法3:Class.forName(),例如:Class.forName("java.lang.String")

    86. How to create objects through reflection?

    answer:

  • Method 1: Call the newInstance() method through the class object, for example: String.class.newInstance()
  • Method 2: Obtain the Constructor object through the getConstructor() or getDeclaredConstructor() method of the class object and call its newInstance() method to create the object, for example: String.class.getConstructor(String.class).newInstance("Hello" );

    87. How to obtain and set the value of an object's private field through reflection?

    Answer: You can use the getDeclaredField() method of the class object to set the Field object, and then set it to be accessible through the setAccessible(true) of the field object, and then you can get/set the value of the field through the get/set method Up. The following code implements a reflective tool class. The two static methods are used to obtain and set the value of a private field. The field can be a basic type or an object type and supports multi-level object operations, such as ReflectionUtil.get( dog, "owner.car.engine.id"); The ID number of the engine of the car of the owner of the dog object can be obtained.


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
/** * 反射工具类 * @author 骆昊 * */
public class ReflectionUtil {
    private ReflectionUtil() {
        throw new AssertionError();
    }
    /**     * 通过反射取对象指定字段(属性)的值     * @param target 目标对象     * @param fieldName 字段的名字     * @throws 如果取不到对象指定字段的值则抛出异常     * @return 字段的值     */
    public static Object getValue(Object target, String fieldName) {
        Class<?> clazz = target.getClass();
        String[] fs = fieldName.split("\\.");
        try {
            for(int i = 0; i < fs.length - 1; i++) {
                Field f = clazz.getDeclaredField(fs[i]);
                f.setAccessible(true);
                target = f.get(target);
                clazz = target.getClass();
            }
            Field f = clazz.getDeclaredField(fs[fs.length - 1]);
            f.setAccessible(true);
            return f.get(target);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**     * 通过反射给对象的指定字段赋值     * @param target 目标对象     * @param fieldName 字段的名称     * @param value 值     */
    public static void setValue(Object target, String fieldName, Object value) {
        Class<?> clazz = target.getClass();
        String[] fs = fieldName.split("\\.");
        try {
            for(int i = 0; i < fs.length - 1; i++) {
                Field f = clazz.getDeclaredField(fs[i]);
                f.setAccessible(true);
                Object val = f.get(target);
                if(val == null) {
                    Constructor<?> c = f.getType().getDeclaredConstructor();
                    c.setAccessible(true);
                    val = c.newInstance();
                    f.set(target, val);
                }
                target = val;
                clazz = target.getClass();
            }
            Field f = clazz.getDeclaredField(fs[fs.length - 1]);
            f.setAccessible(true);
            f.set(target, value);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

88. How to call an object's method through reflection?

Answer: Please see the code below:


import java.lang.reflect.Method;
class MethodInvokeTest {
    public static void main(String[] args) throws Exception {
        String str = "hello";
        Method m = str.getClass().getMethod("toUpperCase");
        System.out.println(m.invoke(str));  // HELLO
    }
}

89. Briefly describe the object-oriented "six principles and one rule".

answer:

  • Single responsibility principle: A class only does what it should do. (The single responsibility principle wants to express "high cohesion", and the ultimate principle of writing code is only six words "high cohesion, low coupling", just like the central idea of ​​the Sunflower Book or the sword of evil spirits is "desire". To practice this exercise, you must first come from the palace." The so-called high cohesion means that a code module only completes one function. In object-oriented, if only one class is allowed to do what it should do, it does not involve areas that have nothing to do with it. Practicing the principle of high cohesion, this class has only a single responsibility. We all know a saying called "Because of focus, so professional", if an object undertakes too many responsibilities, then it is doomed to do nothing. This world Any good thing on the above has two characteristics. One is that it has a single function. A good camera is definitely not the kind of machine sold in TV shopping. It has more than one hundred functions. It can basically only take pictures; the other is modular. A good bicycle is an assembled bicycle. From the shock absorber, brakes to the transmission, all parts can be disassembled and reassembled. A good ping pong racket is not a finished racket. It must be the base plate and rubber that can be disassembled and assembled by themselves. , A good software system, each functional module in it should also be easily used in other systems, so as to achieve the goal of software reuse.)
  • Principle of opening and closing: The software entity should be open for extension and closed for modification. (In an ideal state, when we need to add new functions to a software system, we only need to derive some new classes from the original system, without modifying any original line of code. There are two ways to open and close. Key points: ①Abstraction is the key. If there is no abstract class or interface system in a system, there will be no extension point; ②Encapsulate variability, encapsulate various variable factors in the system into an inheritance structure, if multiple variable factors are mixed Together, the system will become complex and chaotic. If you don’t know how to encapsulate the variability, you can refer to the chapter on the bridge pattern in the book "Design Patterns Elaboration".)
  • Rely on the principle of inversion: interface-oriented programming. (The principle is straightforward and specific. When declaring method parameter types, method return types, and variable reference types, use abstract types as much as possible instead of concrete types, because abstract types can be used by any of its subtypes. For substitution, please refer to the Richter Substitution Principle below.)
    Richter Substitution Principle: You can replace the parent type with a subtype at any time. (Regarding the description of the Richter substitution principle, Ms. Barbara Liskov's description is much more complicated than this, but in simple terms, the subtype can be used wherever the supertype can be used. The Richter substitution principle can check whether the inheritance relationship is reasonable. If an inheritance relationship violates the Richter substitution principle, then the inheritance relationship must be wrong, and the code needs to be refactored. For example, letting cats inherit from dogs, or dogs inheriting from cats, or letting squares inherit from rectangles are all wrong inheritance relationships. , Because you can easily find scenes that violate the Richter substitution principle. It should be noted that the child class must increase the ability of the parent class instead of reducing the ability of the parent class, because the child class has more capabilities than the parent class. Of course there is no problem in using the object as a less capable object.)
  • The principle of interface isolation: The interface should be small and specialized, never big and comprehensive. (The bloated interface is a pollution to the interface. Since the interface expresses the ability, an interface should only describe one kind of ability, and the interface should also be highly cohesive. For example, Qinqi, calligraphy and painting should be designed as four interfaces instead of It should be designed into four methods in one interface, because if it is designed into four methods in one interface, then this interface is difficult to use. After all, there are still a few people who are proficient in all four of piano, chess, calligraphy and painting, and if you design into four interfaces , A few items will implement several interfaces. In this way, the possibility of each interface being reused is very high. Interfaces in Java represent capabilities, conventions, and roles. Whether the interface can be used correctly must be a level of programming level Important mark.)
  • Synthetic aggregation reuse principle: Prioritize the use of aggregation or synthetic relationship reuse codes. (Reusing code through inheritance is the most abused thing in object-oriented programming, because all textbooks promote inheritance without exception, which misleads beginners. There are three types of classes. Relationships, Is-A relationship, Has-A relationship, and Use-A relationship, respectively represent inheritance, association, and dependency. Among them, association relationships can be further divided into association, aggregation, and synthesis according to the strength of their association, but they are all Has-A relationship, the principle of composite aggregation reuse wants to express that priority is given to Has-A relationship instead of Is-A relationship to reuse code. The reason can be found on Baidu for 10,000 reasons. It needs to be explained that even in There are also many examples of abuse of inheritance in the Java API. For example, the Properties class inherits the Hashtable class, and the Stack class inherits the Vector class. These inheritances are obviously wrong. A better approach is to place a Hashtable type member in the Properties class and Set its keys and values ​​to strings to store data, and the design of the Stack class should also place a Vector object in the Stack class to store data. Remember: do not inherit the tool class at any time, tools can have and Can be used, not inherited.)
  • Dimit's law: Dimit's law is also called the principle of least knowledge. An object should have as little knowledge as possible about other objects. (The law of Demeter simply means how to achieve "low coupling". The facade model and the mediator model are the practice of the law of Demeter. For the facade model, you can give a simple example, you go to a company to negotiate business, You don’t need to understand how the company works internally. You can even know nothing about the company. When you go, you just need to find the beauty at the front desk at the entrance of the company and tell them what you are going to do. They will find the right person to follow. You contact, the beauty at the front desk is the facade of the company's system. No matter how complex the system is, it can provide users with a simple facade. Isn't the Servlet or Filter as the front controller in Java Web development just a facade? The browser is the server The mode of operation is unknown, but through the front controller you can get the corresponding service according to your request. The mediator mode can also be illustrated by a simple example, such as a computer, CPU, memory, hard disk, graphics card, sound card Various devices need to cooperate with each other to work well, but if these things are directly connected together, the wiring of the computer will be extremely complicated. In this case, the motherboard appears as a mediator and connects each device to There is no need to directly exchange data between each device, which reduces the coupling and complexity of the system, as shown in the following figure. Dimit’s rule is to use popular words to not deal with strangers, if it is true Need, find a friend of yours and let him deal with strangers for you.)

Complete Works of Java Interview Questions(9)
Complete Works of Java Interview Questions(9)

90. Briefly describe the design patterns you know.

Answer: The so-called design pattern is a summary of a set of code design experience that has been used repeatedly (a proven solution to a problem in a situation). The use of design patterns is to reusable code, make it easier for others to understand, and ensure code reliability. Design patterns allow people to reuse successful designs and architectures more simply and conveniently. Expressing proven technologies into design patterns will also make it easier for new system developers to understand their design ideas.
In GoF's "Design Patterns: Elements of Reusable Object-Oriented Software", three types (created type [abstraction of the instantiation process of the class] and structural type [describe how to combine classes or objects together to form a more Large structure], behavioral [abstracting the division of responsibilities and algorithms between different objects]), a total of 23 design patterns, including: Abstract Factory (Abstract Factory), Builder (Builder), Factory Method ( Factory method mode), Prototype (original model mode), Singleton (singleton mode); Facade (facade mode), Adapter (adapter mode), Bridge (bridge mode), Composite (composite mode), Decorator (decorative mode), Flyweight (Flyweight mode), Proxy (agent mode); Command (command mode), Interpreter (interpreter mode), Visitor (visitor mode), Iterator (iterative sub mode), Mediator (mediator mode), Memento (memorandum mode) ), Observer (observer mode), State (state mode), Strategy (strategy mode), Template Method (template method mode), Chain Of Responsibility (chain of responsibility mode).
When asked about the knowledge of design patterns in the interview, you can pick the most frequently used answers, such as:

  • Factory pattern: The factory class can generate different subclass instances according to conditions. These subclasses have a common abstract parent class and implement the same methods, but these methods perform different operations (polymorphic methods) for different data. After getting the instance of the subclass, the developer can call the method in the base class without having to consider which instance of the subclass is returned.
  • Proxy mode: Provide a proxy object to an object, and the proxy object controls the reference of the original object. In actual development, agents can be divided into remote agents, virtual agents, protection agents, Cache agents, firewall agents, synchronization agents, and intelligent reference agents according to the purpose of use.
  • Adapter pattern: Transform the interface of one class into another interface that the client expects, so that classes that cannot be used together because of interface mismatch can work together.
  • Template method pattern: Provide an abstract class, implement part of the logic in the form of concrete methods or constructors, and then declare some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods (polymorphic implementation) in different ways to achieve different business logic.
    In addition, you can also talk about the facade mode, bridge mode, singleton mode, decoration mode (decoration mode is used in Collections tools and I/O systems) mentioned above. Anyway, the basic principle is to choose the most familiar The answer is the most frequently used, so as not to miss

Guess you like

Origin blog.51cto.com/15061944/2593697