2019 Java Interview Basics series 228

The answer to questions 1 to 20 in the first update is analyzed

Juejin. Cn/post / 684490…

21~50


Juejin. Cn/post / 684490…





The answer to questions 51 to 95 is updated

51. Class ExampleA inherits Exception and class ExampleB inherits ExampleA.

There is the following code snippet:

try {
	throw new ExampleB("b")} catch (ExampleA e) {system.out.println ("ExampleA"); } catch (Exception e) {system.out.println ("Exception");
}Copy the code
** What is the output of executing this code?

A:

Output: ExampleA. (According to the Richter substitution principle, catching a catch block of ExampleA type exceptions can catch an exception of ExampleB type thrown in a try block.)

Interview question – State the result of running the following code. (This question comes from the book Java Programming Ideas)

class Annoyance extends Exception {
}
class Sneeze extends Annoyance {
}
class Human {
	public static void main(String[] args)
	throws Exception {
		try {
			try {
				throw new Sneeze();
			}
			catch ( Annoyance a ) {
				System.out.println("Caught Annoyance");
				throw a;
			}
		}
		catch ( Sneeze s ) {
			System.out.println("Caught Sneeze");
			return ;
		}
		finally {
			System.out.println("Hello World!"); }}}Copy the code

Do List, Set, Map inherit from Collection interface?

List and Set are allowed, but Map is not. A Map is a key-value mapping container, distinct from a List or Set, which stores discrete elements and does not allow duplicate elements (the same is true of sets in mathematics). A List is a linear container, suitable for accessing elements by numerical index.

53. Explain the storage performance and features of ArrayList, Vector and LinkedList.

ArrayList and Vector both store data in arrays that have more elements than the actual number of stored data to add and insert elements. They both allow elements to be indexed directly by ordinal number. However, inserting elements involves memory operations such as moving array elements, so indexing data is fast and inserting data is slow. The methods in Vector are thread-safe, thanks to the synchronized modifier, but perform worse than ArrayList and are already legacy containers in Java. LinkedList USES two-way linked list to achieve storage (memory scattered memory unit by attaching the reference, can form a linear structure according to the serial number index, the chain store mode compared with continuous storage arrays, memory utilization is higher), according to the serial number prior to or after the index data needed to traverse, However, only the items before and after the item need to be recorded when inserting data, so the insertion speed is fast. Vector is a legacy container (provided in earlier versions of Java, along with Hashtable, Dictionary, BitSet, Stack, and Properties) and is no longer recommended. But because ArrayList and LinkedListed are both non-thread-safe, if you have multiple threads working on the same container, It can then be converted into thread-safe containers through the synchronizedList method in the utility class Collections (this is an application of the decorator pattern, which enhances the implementation by passing existing objects into another class’s constructor to create new objects).

Supplement:Properties is a special key-value pair mapping with both keys and values as strings. It should be designed to associate a Hashtable and set its two generic parameters to String. But Properties in the Java API directly inherits Hashtable, which is an obvious abuse of inheritance. On the other hand, containers belong to utility classes. It Is A mistake to inherit utility classes. The best way to Use utility classes Is to Use HAS-A relationships (associations) or use-A relationships (dependencies). Similarly, it is incorrect for Stack classes to inherit from Vector. Sun engineers also make this kind of stupid mistake, which makes people sigh.

What is the difference between Collections and Collections?

Collection is an interface that is the parent of sets, lists, etc. Collections is a utility class that provides a set of static methods to assist container operations, including searching for containers, sorting, thread-safety, and so on.

55, What are the characteristics of the List, Map, and Set interfaces when accessing elements?

A List accesses elements with a specific index and can have duplicate elements. A Set cannot hold duplicate elements. (Use the equals() method of objects to tell if elements are duplicated.) Map stores key-value pair mappings. The mappings can be one-to-one or many-to-one. Both Set and Map containers have two implementation versions based on hash storage and sort tree. The theoretical access time complexity of the version based on hash storage is O(1), while the implementation based on sort tree will form a sort tree according to elements or their keys when inserting or deleting elements, so as to achieve the effect of sorting and de-duplicating.

56. How do TreeMap and TreeSet compare elements when sorting? How does the sort() method in the Collections utility class compare elements?

TreeSet requires that the class to which the object belongs implement the Comparable interface, which provides a compareTo() method for comparing elements that is called back to compare their size when they are inserted. TreeMap requires that the keys of a stored key-value pair map implement the Comparable interface to sort elements by key. The Sort method of the Collections utility class takes two forms of overloading. The first requires the comparison of objects held in the incoming containers to be sorted to implement the Comparable interface for the comparison of elements. The second, non-mandatory, requires that the elements in the container be comparable, but requires passing in a second argument that is a subtype of the Comparator interface (the compare method needs to be overridden to compare elements). It is also an application of the callback pattern (Java’s support for functional programming).

57, What is the difference between Thread’s sleep() and object’s wait() methods, which suspend execution?

The sleep() method is a static method of the Thread class. Calling this method causes the current Thread to suspend execution for a specified time, giving up the CPU to another Thread. However, the lock on the object remains, so it is automatically resumed when the sleep time expires (the Thread returns to the ready state, See thread state transition diagram in question 66). Wait () is a method of the Object class. Calling the Object’s wait() method causes the current thread to abandon the lock on the Object and enter the Object’s wait pool. A thread in the wait pool can be awakened to enter the lock pool only when notify() (or notifyAll()) of an object is called. If the thread recaptures the lock of the object, it enters the ready state.

Add: Many people may be confused about what a process is and what a thread is, or why you need multithreaded programming. Simply said: process is a program with certain independent functions on a data set of a running activity, is an independent unit of the operating system for resource allocation and scheduling; A thread is an entity of a process, the basic unit of CPU scheduling and dispatching, and a smaller unit that can run independently than a process. The scale of thread partition is smaller than that of process, which makes the concurrency of multithreaded program high. Processes typically have separate memory units at execution, whereas threads can share memory. Programming using multithreading generally leads to better performance and user experience, but multithreaded programs are less friendly to other programs because they may consume more CPU resources. Of course, the more threads you have, the better your program will perform, because scheduling and switching between threads can also waste CPU time. Node.js, the most fashionable one, uses single-threaded asynchronous I/O.

What’s the difference between the sleep() method and the yield() method?

(1) The sleep() method does not consider the priority of the thread when giving other threads a chance to run, so it gives the lower priority thread a chance to run; The yield() method only gives threads of the same or higher priority a chance to run;

(2) The thread is blocked after executing sleep(), and ready after executing yield();

(3) The sleep() method declares to throw InterruptedException, while the yield() method does not declare any exceptions;

(4) The sleep() method is more portable than the yield() method, which is related to operating system CPU scheduling.

59. When A thread enters the synchronized method A of an object, can other threads enter the synchronized method B of that object?

Can’t. Other threads can access only asynchronous methods of the object, and synchronized methods cannot. Since synchronized modifiers on non-static methods require that the object’s lock be acquired when executing the method, A thread that is already in method A must wait for the object’s lock to be taken, and A thread that is trying to enter method B must wait for the object’s lock in the pool.

Describe methods related to thread synchronization and thread scheduling.

(1) Wait () : to cause a thread to wait(block) and release the lock on its holding object;

(2) Sleep () : puts a running thread to sleep. This method is static and handles InterruptedException.

(3) Notify () : this method is used to wake up a thread that is in the waiting state. This method is used to wake up a thread that is in the waiting state.

(4) notityAll() : wakes up all threads in the waiting state. This method does not give the lock of the object to all threads, but makes them compete. Only the thread that obtained the lock can enter the ready state;

Bonus: Java 5 provides explicit locking via the Lock interface for increased flexibility and thread coordination. The Lock interface defines methods for adding (Lock ()) and unlocking (unlock()). The newCondition() method is also provided to generate Condition objects for communication between threads. In addition, Java 5 provides semaphore, which can be used to limit the number of threads accessing a shared resource. Before accessing a resource, the thread must obtain permission from the Semaphore (call acquire() method on the Semaphore object); After completing access to the resource, the thread must return permission to the Semaphore (calling the Release () method of the Semaphore object).

How many ways to write multithreaded programs?

There are two ways to implement multithreading in Java 5: One is to inherit the Thread class; The other is to implement the Runnable interface. Either way, you override the run() method to define the behavior of a Thread. The latter is recommended because Java inheritance is single-inheritance. A class has a parent class, and if it inherits Thread, it cannot inherit other classes.

Add: There is a third way to create threads after Java 5: implement the Callable interface, where the Call method produces a return value at the end of thread execution.

62, Synchronized?

The synchronized keyword marks an object or method as synchronized to achieve mutually exclusive access to the object or method. You can use the synchronized(object) {… } defines blocks of synchronized code, or synchronized as a method modifier when declaring methods. The use of the synchronized keyword has been shown in the example in question 60.

63. Give examples of synchronization and asynchrony.

If the system exists in the critical resources (resource quantity is less than the competition of the number of threads resources), for example is writing data could be read another thread, the data may have been or are in the read another thread to write, so these data must be synchronized access (exclusive lock is the best example of database operations). When your application calls a method on an object that takes a long time to execute, and you don’t want to leave your program waiting for the method to return, you should use asynchronous programming, which in many cases is more efficient. In fact, synchronous is a blocking operation and asynchronous is a non-blocking operation.

64. Do I call the run() or start() method to start a thread?

Starting a thread is a call to the start() method that puts the virtual processor it represents in a runnable state. This means that it can be scheduled and executed by the JVM. This does not mean that the thread will run immediately. The run() method is a callback to be performed after a thread is started.

What is a thread pool?

In object-oriented programming, creating and destroying objects is time consuming because creating an object requires memory resources or more. This is especially true in Java, where the virtual machine will try to keep track of every object so that it can be garbage collected after the object is destroyed. So one way to improve the efficiency of a service application is to minimize the number of objects created and destroyed, especially those that are very expensive. This is where pooling resources comes in. Thread pool, as its name implies, is to create a number of executable threads in advance into a pool (container), when needed to obtain threads from the pool without creating their own, after use does not need to destroy threads but put back into the pool, thereby reducing the creation and destruction of thread objects overhead. The Executor interface in Java 5+ defines a tool for executing threads. Its subtype, the thread pool interface, is ExecutorService. * If the thread pool configuration is complete and the mechanism of the thread pool is not clear, so the following static factory methods are provided for the tool Executors:

(1) newSingleThreadExecutor: Create a single thread pool. This thread pool has only one thread working, which is equivalent to a single thread executing all tasks in serial. If the unique thread terminates due to an exception, a new thread will replace it. This thread pool ensures that all tasks are executed in the order in which they were submitted.

(2) newFixedThreadPool: create a fixed size thread pool. A thread is created each time a task is submitted until the thread reaches the maximum size of the thread pool. The size of the thread pool stays the same once it reaches its maximum size, and if a thread terminates due to execution exceptions, a new thread is added to the pool.

NewCachedThreadPool: Create a cacheable thread pool. If the size of the thread pool exceeds the number of threads needed to process the task, the pool can reclaim some of the idle (60-second non-executing) threads and intelligently add new threads to process the task as the number of tasks increases. This thread pool has no limit on the thread pool size, which is entirely dependent on the maximum thread size that the operating system (or JVM) can create.

(4) newScheduledThreadPool: create a thread pool of unlimited size. This thread pool supports the need to execute tasks regularly and periodically.

(5) newSingleThreadExecutor: Create a single thread pool. This thread pool supports the need to execute tasks regularly and periodically.

Create a thread pool and use the thread pool to execute the thread using the Executors tool class. If you want to use thread pools on the server, the newFixedThreadPool method is strongly recommended to create thread pools for better performance.

What is the basic state of the thread and the relationship between the states?



Description: The Running, Runnable, and Blocked states can occur as a result of calling a wait() method to enter the wait pool, or executing a synchronized method or code block to enter the isolock pool. Either the sleep() or Join () methods were called to wait for sleep or another thread to finish, or an I/O interrupt occurred.

67, briefly synchronized and Java. Util. Concurrent. The locks. The similarities and differences of the Lock?

Lock is a new API introduced after Java 5. It has some similarities with the keyword synchronized: Lock can accomplish all the functions achieved by synchronized; Key differences: Lock has more precise thread semantics and better performance than synchronized, and it is not mandatory to acquire the Lock. Synchronized automatically releases locks, whereas locks must be released manually by the programmer and are best released ina finally block (which is the best place to release external resources).

68. How serialization is implemented in Java, and what does it mean?

Serialization is a mechanism for dealing with streams of objects, that is, streaming the contents of objects. You can read and write the fluidized object or transfer the fluidized object between networks. Serialization is intended to solve problems that may occur when reading or writing objects (data may be out of order if not serialized). To implement serialization, you need to have a class that implements the Serializable interface, which is an identifier indicating that objects of the class can be serialized, An output stream is then used to construct an Object output stream and the implementation Object is written out (that is, its state is saved) using the writeObject(Object) method. If deserialization is required, an object input stream can be created with an input stream, and objects can be read from the stream using the readObject method. In addition to persisting objects, serialization can also be used for deep cloning of objects (see question 29).

How many types of flows are there in Java?

Byte stream and character stream. The byte stream inherits from InputStream and OutputStream, and the character stream inherits from Reader and Writer. There are many other streams in the java.io package, mainly for performance and ease of use. There are two things to note about Java I/O: first, there are two symmetries (symmetry of input and output, byte and character); The second is two design modes (adapter mode and decoration mode). In addition, Java flows differ from C# in that they have only one dimension and one direction.

Write a method that enters a file name and a string and counts the number of times the string appears in the file.

The code is as follows:

import java.io.BufferedReader; import java.io.FileReader; Public final class MyUtil {// Methods in utility classes are accessed statically so keeping constructors private does not allow object creation (absolutely good practice) privateMyUtil() { throw new AssertionError(); } /** * count the number of occurrences of a given string in a given file ** @param filename filename * @param word string * @return*/ public static int countWordInFile(String filename, String word) {int counter = 0; try (FileReader fr = new FileReader(filename)) { try (BufferedReader br = new BufferedReader(fr)) { String line = null;while((line = br.readLine()) ! = null) { int index = -1;while (line.length() >= word.length() && (index =
					line.indexOf(word)) >= 0) {
						counter++;
						line = line.substring(index + word.length());
					}
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		returncounter; }}Copy the code

71, How to use Java code to list all files in a directory?

If only files under the current folder are required to be listed, the code looks like this:

import java.io.File;
class Test12 {
	public static void main(String[] args) {
		File f = new File("/Users/Hao/Downloads");
		for (File temp : f.listFiles()) {
			if(temp.isFile()) { System.out.println(temp.getName()); }}}}Copy the code
If you need to expand the folder further, the code looks like this:

import java.io.File;
class Test12 {
	public static void main(String[] args) {
		showDirectory(new File("/Users/Hao/Downloads"));
	}
	public static void showDirectory(File f) {
		_walkDirectory(f, 0);
	}
	private static void _walkDirectory(File f, int level) {
		if(f.isDirectory()) {
			for(File temp : f.listFiles()) { _walkDirectory(temp, level + 1); }}else {
			for (int i = 0; i < level - 1; i++) {
				System.out.print("t"); } System.out.println(f.getName()); }}}Copy the code
In Java 7 you can use the NIo.2 API to do the same thing, as shown below:

class ShowFileTest {
	public static void main(String[] args) throws IOException {
		Path initPath = Paths.get("/Users/Hao/Downloads");
		Files.walkFileTree(initPath, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes
			attrs)
			throws IOException {
				System.out.println(file.getFileName().toString());
				returnFileVisitResult.CONTINUE; }}); }}Copy the code

Using Java socket programming to achieve a multithreaded echo server.

73. How many forms does an XML document definition take? What are the essential differences between them? What are some ways to parse AN XML document?

XML document definition can be divided into DTD and Schema, both of which are constraints on XML syntax. The essential difference is that Schema itself is also an XML file, which can be parsed by XML parsers and can define types for the data carried by XML. Constraints are more powerful than DTDS. XML parsing mainly includes DOM (Document Object Model), SAX (Simple API forXML) and StAX (Java 6 introduced a new way of parsing XML, Streaming API for XML), in which the performance of DOM processing large files deteriorates greatly. This problem is caused by the large memory occupied by DOM tree structure, and DOM parsing must load the entire document into memory before parsing the file. Suitable for random access to XML (a typical space-for-time strategy); SAX is an event-driven XML parsing method that reads XML files sequentially without loading the entire file at once. When it encounters things like the beginning of a file, the end of a document, or the beginning and end of a tag, it triggers an event, and the user processes the XML file through the event callback code, suitable for sequential access to the XML; As the name suggests, StAX focuses on streams, but the essential difference between StAX and other parsing approaches is that applications can process XML as a stream of events. The idea of processing XML as a set of events is not new (SAX does this), but the difference is that StAX allows application code to pull these events out one by one, rather than providing a handler that receives the events from the parser at its convenience.

74. Where did you use XML in your project?

XML has two main functions: data exchange and information configuration. In data exchange, XML assembled data with tags, then compressed, packaged, encrypted and sent to the receiver over the network. After receiving decryption and decompression, relevant information was restored from XML files for processing. XML used to be the de facto standard for data exchange between heterogeneous systems. But this feature has almost been replaced by JSON (JavaScript Object Notation). Of course, a lot of software still uses XML to store configuration information, and we often write hard code for configuration information in XML files in many projects. Many Java frameworks do the same, and they all use DOM4J as their tool for processing XML. Because Sun’s official API is not very useful.

Add: With trendy software such as Sublime starting to write configuration files in JSON format, there is a strong sense that another aspect of XML is being abandoned by the industry.

75, describe the steps of JDBC database operation.

The following code uses connecting to the local Oracle database as an example to demonstrate the steps for JDBC database operations.

(1) Load the driver.

Class.forName("oracle.jdbc.driver.OracleDriver");Copy the code
(2) Create a connection.

Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl"."scott"."tiger");Copy the code
(3) Create statement.

PreparedStatement ps = con.prepareStatement("select * from emp
where sal between ? and ?");
ps.setint(1, 1000);
ps.setint(2, 3000);Copy the code
(4) Execute the statement.

ResultSet rs = ps.executeQuery();Copy the code
(5) Processing results.

while(rs.next()) {
	System.out.println(rs.getint("empno") + "-" +
	rs.getString("ename"));
}Copy the code
(6) Close resources.

finally {
	if(con ! = null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); }}}Copy the code
Tip:Closing external resources should be done in the reverse order of opening them, that is, closing a ResultSet first, then a Statement, and then a Connection. The above code only closes the Connection, although normally when you close a Connection, statements created on the Connection and open cursors are also closed, but this is not always guaranteed, so you should close them separately in the order just described. In addition, the first step of loading the driver can be omitted in JDBC 4.0 (automatically loading the driver from the classpath), but we recommend keeping it.

76. What is the difference between a Statement and PreparedStatement? Which has better performance?

Compared with Statement, the PreparedStatement interface represents a PreparedStatement. The main advantage of PreparedStatement is that it can reduce the compilation errors of SQL and increase the security of SQL (reduce the possibility of SQL injection attacks). (2) SQL statements in PreparedStatement can be prepared with parameters, avoiding the trouble and insecurity of using string concatenation SQL statements; (3) PreparedStatements have obvious performance advantages when batch processing SQL or frequently executing the same query. Preparedstatements can be cached by the database, and the next time a statement with the same structure is executed, it will be faster (no need to compile and generate an execution plan again).

Note: To provide calls to stored procedures, the JDBC API also provides the CallableStatement interface. Stored Procedure is a set of SQL statements in a database to complete a specific function. After being compiled, it is Stored in the database. The user can execute the Stored Procedure by specifying its name and giving parameters (if the Stored Procedure has any parameters). Although there are many benefits to calling stored procedures in terms of network overhead, security, and performance, there is a lot of trouble if the underlying database is migrated, because the stored procedures of each database are written differently.

When using JDBC to operate database, how to improve the performance of reading data? How to improve the performance of updated data?

To improve the performance of reading data, you can specify the number of records fetched each time through the setFetchSize() method of the ResultSet object (a typical space-to-time strategy). To improve the performance of updated data, you can build a batch using the PreparedStatement statement, in which several SQL statements are executed in a batch.

78, What is the role of connection pool in database programming?

Due to create connections and release the connection has great overhead (especially the database server is not local, every time requires a connection is established the TCP three-way handshake, release the connection needs to be TCP handshake, four times the overhead is not to be ignored), in order to improve the performance of the system to access the database, can create a number of connections in the connection pool in advance, Fetching directly from the connection pool when needed and returning the connection pool at the end of use without having to close the connection avoids the overhead of frequently creating and releasing connections, which is a typical space-for-time strategy (wasting space storing connections, but saving time creating and releasing connections). Pooling techniques are common in Java development, and the same is true for creating thread pools when using threads. Java based open source database connection pools include C3P0, Proxool, DBCP, BoneCP, Druid, and so on.

Addendum: Understanding that time and space are irreconcilable contradictions in computer systems is crucial to designing algorithms that meet performance requirements. One key to optimizing the performance of large sites is the use of caching, which is a space-for-time strategy very similar to the connection pooling principle described above. You can put hot data in the cache and get it directly from the cache when the user queries it, which is faster than the database query anyway. Of course, cache substitution strategies and so on can also have a significant impact on system performance, which is beyond the scope of this discussion.

What is the DAO pattern?

DAO (Data Access Object), as its name implies, is an Object that provides an abstract interface for a database or other persistence mechanism. It provides various Data Access operations without exposing the implementation details of the underlying persistence scheme. In real development, all access operations to the data source should be abstracted and encapsulated in a common API. In programming languages, this is to create an interface that defines all the transaction methods that will be used in the application. In this application, this interface is used when you need to interact with the data source, and a separate class is written to implement this interface, which logically corresponds to a specific data store. DAO mode actually contains two modes, one is DataAccessor (Data accessor) and the other is Data Object (Data Object). The former is to solve the problem of how to access Data, while the latter is to solve the problem of how to encapsulate Data with objects.

What is transaction ACID?

(1) Atomic: all operations in a transaction can be done or not done at all. The failure of any operation will lead to the failure of the whole transaction.

(2) Consistent: The system state is Consistent after the end of a transaction;

(3) Isolation: Concurrently executed transactions cannot see each other’s intermediate state;

(4) Durable: Changes made after the completion of transactions will be persisted, even if catastrophic failure occurs. Log and synchronous backups can be used to rebuild data after a failure.

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

Dirty reads:If transaction A reads and operates on uncommitted data from transaction B, and transaction B performs rollback, the data read by transaction A is dirty.

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

Phantom Read:Transaction A re-executes A query, returns A list of rows that match the query criteria, and finds that the rows committed by transaction B have been inserted.

Type 1 Missing updates: When transaction A is revoked, the updated data of the committed transaction B is overwritten.

Type 2 missing update: Transaction A overwrites the data already committed by transaction B, causing the operations done by transaction B to be lost.

The problem caused by concurrent data access may be allowed in some scenarios, but it may be fatal in some scenarios. Databases usually solve the problem by locking mechanism, which can be divided into table level locking and row level locking according to different locked objects. According to the concurrent transaction lock relationship can be divided into shared lock and exclusive lock, the specific content we can consult the information to understand. Directly using the lock is very troublesome, for this database provides users with automatic locking mechanism, as long as the user of the specified session transaction isolation level, the database will be based on the analysis of the SQL statement and then for the transaction to access resources, plus appropriate locks, in addition, the database will also maintain the lock through various means to improve the performance of the system, All of this is transparent to the user (which means you don’t have to understand, which I don’t). The ANSI/ISOSQL 92 standard defines four levels of transaction isolation levels, as shown in the following table:

It should be noted that the transaction isolation level and the concurrency of data access are antithetical, and the higher the transaction isolation level, the worse the concurrency. There is no one-size-fits-all rule for determining the appropriate transaction isolation level for your application.

How do transactions occur in JDBC?

Connection provides a method for transaction processing. You can set the transaction to commit manually by calling setAutoCommit(false). Commit () to explicitly commit the transaction when it completes; If an exception occurs during the transaction, the transaction is rolled back with rollback(). In addition, the concept of savepoints was introduced from JDBC 3.0, allowing you to set savepoints in code and roll back transactions to specified savepoints.

Can JDBC handle BLOBs and CLOBs?

Blob stands for Binary Large Object, while Clob stands for Character Large Objec, so BLOBs are designed to store Large Binary data, Clobs are designed to store large amounts of text data. Both JDBC PreparedStatement and ResultSet provide methods to support Blob and Clob operations.

83. Briefly describe regular expressions and their uses.

When writing programs that work with strings, there is often a need to find strings that conform to some complex rules. Regular expressions are a tool for describing these rules. In other words, regular expressions are code that records rules for text.

Description: computer was born in the early processing of information are almost, but times have changed, today we use computer processing information more often rather than numeric string, the regular expression is in string matching and deal with the most powerful tools, most languages have provided support for regular expressions.

84. How are regular expression operations supported in Java?

The String class in Java provides methods that support regular expression operations, including matches(), replaceAll(), replaceFirst(), and split(). In addition, regular expression objects can be represented in Java using the Pattern class, which provides a rich API for various regular expression operations.

Interview question: – If you want to extract the string before the first opening parenthesis from the string, for example: Beijing (Chaoyang District)(Xicheng District)(Haidian District), the result is: Beijing, then how to write the regular expression?

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpTest {
	public static void main(String[] args) {
		String str = "Beijing (Chaoyang District)(Xicheng District)(Haidian District)";
		Pattern p = Pattern.compile(". *? (? = \ ()");
		Matcher m = p.matcher(str);
		if(m.find()) { System.out.println(m.group()); }}}Copy the code


What are the ways to get a class object of a class?

(1) Method 1: type.class, for example, string.class

(2) Method 2: object.getClass (), e.g. “hello”.getClass()

Method 3: class.forname (), e.g. Class.forname (” java.lang.string “)

How do I create objects with reflection?

Method 1: Call newInstance() through class objects, such as string.class.newinstance ().

Method 2: Get the Constructor object from the class object’s getConstructor() or getDeclaredConstructor() method and call its newInstance() method to create the object, for example: String. Class. GetConstructor (String. The class). NewInstance (” Hello “);

How do I get and set the value of an object’s private field by reflection?

The Field object can be made accessible by the getDeclaredField() method of the class object, and then by the setAccessible(true) method of the Field object, and then by the get/set method of the Field. The following code implements a reflected utility class in which two static methods are used to get and set the values of private fields, which can be primitive or object types and support multi-level object operations.

How do I call a method on an object through reflection?

Take a look at the following code:

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
	}
}Copy the code

89. Briefly describe the “six principles and one Law” of object orientation.

(1) Single responsibility principle: A class only does what it’s supposed to do. Want to express (single responsibility principle is “high cohesion,” write code the ultimate principle only six words “high cohesion and low coupling”, or to ward off bad luck is like sunflower treasure dian jian spectrum is the center of the eight words “before this work will first from the palace”, the so-called high cohesion is only a code module to complete a function, in the object-oriented, if only to make a class do it should do, By not touching areas that are not relevant to it, we are practicing the principle of high cohesion, so that the class has only one responsibility. We all know the phrase “focus is the key”, and if a subject takes on too much responsibility, it is doomed to do nothing well. Any good thing in the world has two characteristics. One is that it has a single function. A good camera is definitely not the one sold in TV shopping. The other is a modular, a good bicycle is hard, from suspension fork and the brakes to the transmission, of all the parts can be disassembled and reassembled, good table tennis racket is not finished, must be a base plate and the rubber can be split and self-assembly, a good software system, it’s each function module should be also can easily get used in other systems, In this way, the goal of software reuse can be achieved.

(2) Open closed principle: software entities should be open for extension and closed for modification. In an ideal world, when we need to add new functionality to a software system, we can simply derive new classes from the original system without changing a single line of code. (1) Abstraction is the key. If there is no abstract class or interface in a system, there is no extension point. (2) Encapsulate variability, encapsulate various variable factors in the system into an inheritance structure. If multiple variable factors are mixed together, the system will become complicated and chaotic. If it is not clear how to encapsulate variability, you can refer to the chapter on bridge mode in the book “Design Mode Refinement”.

(3) Dependency reversal principle: interface oriented programming. (When declaring method parameter types, method return types, and variable reference types, use abstract types instead of concrete types. Abstract types can be replaced by any of their subtypes. See The Richter substitution rule below.)

(4) Richter’s substitution principle: the parent type can be replaced by a child type at any time. (Mrs. Barbara Liskov’s description of The Richter substitution principle is much more complex than this, but simply states that where a parent type can be used, a child type can be used. The Richter substitution principle checks 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 refactured. For example, having a cat inherit from a dog, or a dog inherit from a cat, or a square inherit from a rectangle is a false inheritance, because you can easily find situations that violate The Richter’s substitution principle. Note that subclasses must increase the power of the parent class rather than decrease the power of the parent class, because subclasses have more power than the parent class, and there is no problem using objects with more power as objects with less power.

(5) Interface isolation principle: The interface should be small and specialized, never large and complete. (Bloated interfaces pollute interfaces. Since interfaces represent capabilities, an interface should only describe one capability, and interfaces should be highly cohesive. Unique romance, for example, should be designed respectively for four interface, and should not be designed as an interface of the four methods, as if designed into four methods in an interface, the interface is difficult to use, unique romance, after all, four are proficient in one or a few, and if the design into four interface, would achieve several several interfaces, The likelihood of each interface being reused is high. In Java, interface represents ability, convention and role. Whether the interface can be used correctly must be an important indicator of programming level.

(6) Principle of composite polymerization reuse: priority is given to the reuse of composite or composite relation code. (through inheritance to copy code Is being abused at most in object-oriented programming, because all the textbooks without exception to preach to mislead beginners, inheriting classes with simple says there are three kinds of relationships between classes, Is A relationship, Has A relationship, Use – A relationship, represent the inheritance, association and dependency. Among them, association relation can be further divided into association, aggregation and synthesis according to the strength of its association, but all of them are HAS-A relation, and the principle of composite polymerization reuse wants to express that HAS-A relation Is given priority over IS-A relation reuse code. The reason can be found in Baidu for 10,000 reasons. It needs to be explained that: Even in Java apis, there are examples of inheritance abuse, such as Properties inheriting from Hashtable and Stack inheriting from Vector, which are clearly wrong. It would be better to put a Hashtable member in the Properties class and set its keys and values to strings to store the data, while the Stack class would be designed to put a Vector in the Stack class to store the data. Remember: never inherit utility classes. Tools are owned and used, not inherited.

(7) Demeter’s Law: Demeter’s law is also called the least knowledge principle, one object should know as little as possible about other objects. Demeter’s Law is simply how to achieve “low coupling”. The facade mode and the mediator mode are the practices of Demeter’s Law. For facade pattern can cite a simple example, you go to a company to negotiate business, you don’t need to understand how this company works, you can even do not know anything about this company, only need to find the front desk at the entrance of the company when he went to the beauty, tell them you want to do, they will find the right person contact with you, The beauty at the front desk is the face of the system. Any complex system can provide a simple facade for the user. A Servlet or Filter, as a front-end controller in Java Web development, is a facade. The browser does not know how the server works, but the front-end controller can get the corresponding service according to your request. Mediator pattern can also be a simple example to illustrate how, for example, a computer, CPU, memory, hard disk, video card, sound card, all kinds of equipment need to cooperate with one another to be a very good job, but if all the things are directly connected to the computer wiring will be complicated, in this case, the main board have emerged as a mediator, It connects devices together without the need to exchange data directly between each device, thus reducing the coupling and complexity of the system, as shown in the figure below. In layman’s terms, Demeter’s Law would be to avoid strangers, and if you really need to, find a friend and let him do the strangers for you.)



90. Briefly describe the design patterns you understand.

A design pattern is a set of code design lessons that have been used over and over again (a proven solution to a problem in a situation). Design patterns are used to re-use code, make it easier for others to understand, and ensure code reliability. Design patterns make it easier to reuse successful designs and architectures. Expressing proven technologies as design patterns also makes it easier for developers of new systems to understand their design ideas.

Design Patterns at GoF: Elements of Reusable Object-OrientedSoftware presents three types of design patterns (creative [abstraction of the instantiation process of a class], structural [description of how to combine classes or objects together to form a larger structure], behavioral [abstraction of dividing responsibilities and algorithms between different objects]), including: Abstract Factory, Builder, Factory Method, Prototype, Singleton; Facade, Adapter, Bridge, Composite, Decorator, Flyweight, Proxy; Facade, Adapter, Bridge, Composite, Decorator, Flyweight, Proxy; A Command, an Interpreter, a Visitor, an Iterator, a Mediator, a Memento, an Observer, a Visitor, an Interpreter, a Visitor, an Iterator, a Mediator, a Memento, an Observer, a Mediator. State, Strategy, Template Method, Chain Of Responsibility.

When asked about design patterns in an interview, you can choose the most common answers, such as:

(1) Factory pattern: Factory classes can generate different instances of subclasses based on conditions. These subclasses have a common abstract parent class and implement the same methods, but these methods perform different operations on different data (polymorphic methods). Once you have an instance of a subclass, the developer can call a method in the base class regardless of which instance of the subclass is being returned.

(2) Proxy mode: an object is provided with a proxy object, and the proxy object controls the reference to the original object. In actual development, according to different purposes, agents can be divided into: remote proxy, virtual proxy, protection proxy, Cache proxy, firewall proxy, synchronization proxy, intelligent reference proxy.

(3) Adapter mode: the interface of a class is transformed into another interface expected by the client, so that the classes that cannot be used together due to interface mismatch can work together.

(4) Template method pattern: Provide an abstract class that implements some of the logic as concrete methods or constructors, and then declare some abstract methods to force subclasses to implement the rest of the logic. Different subclasses can implement these abstract methods (polymorphic implementations) in different ways to implement different business logic. In addition, you can also talk about the facade pattern, the bridge pattern, the singleton pattern, the decoration pattern (used in the Collections utility class and I/O system) mentioned above, etc. Anyway, the basic principle is to pick the most familiar and used ones, so as not to miss the point.

Write a singleton class in Java.

(1) Hangry singleton

public class Singleton {
	private Singleton(){
	}
	private static Singleton instance = new Singleton();
	public static Singleton getInstance() {returninstance; }}Copy the code
(2) lazy singleton

public class Singleton {
	private static Singleton instance = null;
	private Singleton() {
	}
	public static synchronized Singleton getInstance() {if (instance == null) instance = new Singleton();
		returninstance; }}Copy the code
Note: There are two points to note when implementing a singleton: ① Make the constructor private and do not allow outsiders to create objects through the constructor; ② Return a unique instance of a class to the outside world via an exposed static method. Here’s a question to ponder: Spring’s IoC container can create singletons for ordinary classes. How does it do it?

What is UML?

UML is short for Unified Modeling Language (UML). Published in 1997, UML combines existing object-oriented Modeling languages, methods, and processes. It is a graphical Language that supports Modeling and software system development. Provides modeling and visualization support for all phases of software development. Using UML can aid in communication and communication, aid in application design and documentation generation, and explain system structure and behavior.

What diagrams are commonly used in UML?

UML defines a variety of graphical symbols to describe part or all of the static and dynamic structures of a software system, including: Use case diagram, class diagram, sequencediagram, collaboration diagram, statechart Diagram, activity diagram, component diagram, deploymentdiagram, etc. Among these graphical symbols, there are three diagrams that are the most important: Use case diagrams (used to capture requirements, describes the function of the system, through the picture can quickly understand the function modules of the system and their relationships), the class diagram (describe the relationship between class and class with class, through which can quickly understand system), sequence diagrams (describe the interactions between objects when performing a specific task and execution order, This diagram shows what messages an object can receive, that is, what services it can provide to the outside world. Use case diagram:

Class diagram:

Sequence diagram:



Write a bubble sort in Java.

Bubble sort is almost a programmer can write, but how to write a forced high bubble sort interview is not everyone can do, the following provides a reference code:

import java.util.Comparator; /** * collator interface (policy mode: Encapsulate algorithms into separate classes with common interfaces so that they are interchangeable) * @author Luo hao ** / public interface Sorter {/** ** sort * @param list array to sort */ public <T extends Comparable<T>> void sort(T[] list); Public <T> void sort(T[] list, Comparator<T> comp); } import java.util.Comparator; Public class BubbleSorter implements Sorter {@override public <T category <T>> void sort(T[] list) { Boolean swapped =true;
		for (int i = 1, len = list.length; i < len && swapped; ++i) {
			swapped = false;
			for (int j = 0; j < len - i; ++j) {
				if (list[j].compareTo(list[j + 1]) > 0) {
					T temp = list[j];
					list[j] = list[j + 1];
					list[j + 1] = temp;
					swapped = true;
				}
			}
		}
	}
	@Override
	public <T> void sort(T[] list, Comparator<T> comp) {
		Boolean swapped = true;
		for (int i = 1, len = list.length; i < len && swapped; ++i) {
			swapped = false;
			for (int j = 0; j < len - i; ++j) {
				if (comp.compare(list[j], list[j + 1]) > 0) {
					T temp = list[j];
					list[j] = list[j + 1];
					list[j + 1] = temp;
					swapped = true;
				}
			}
		}
	}
}Copy the code

Write a half search in Java.

Split search, also known as binary search, binary search, is a search algorithm in an ordered array to find a particular element. The search process starts with the middle element of the array. If the middle element is exactly the element to be searched, the search process ends. If a particular element is greater than or less than the middle element, it looks in the half of the array that is greater than or less than the middle element, and compares from the middle element as it began. If the array is empty at any point, the specified element cannot be found. This search algorithm reduces the search scope by half with each comparison, and its time complexity is O(logN).

import java.util.Comparator;
public class MyUtil {
	public static <T extends Comparable<T>> int binarySearch(T[] x, T
	key) {
		returnbinarySearch(x, 0, x.length- 1, key); } public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {int low = 0; int high = x.length - 1;while (low <= high) {
			int mid = (low + high) >>> 1;
			int cmp = comp.compare(x[mid], key);
			if (cmp < 0) {
				low= mid + 1;
			} else if (cmp > 0) {
				high= mid - 1;
			} else {
				returnmid; }}return- 1; } private static<T extends Comparable<T>> int binarySearch(T[] x, int low, int high, T key) {if(low <= high) {
			int mid = low + ((high -low) >> 1);
			if(key.compareTo(x[mid])== 0) {
				return mid;
			} else if(key.compareTo(x[mid])< 0) {
				return binarySearch(x,low, mid - 1, key);
			} else {
				returnbinarySearch(x,mid + 1, high, key); }}return -1;
	}
}Copy the code
Note: the above code gives two versions of the split search, a recursive implementation, a circular implementation. Note that (high+ low) / 2 should not be used when calculating the middle position, as addition may cause the integer to be out of bounds. Instead, use one of the following three methods: Low + (high-low)/ 2 or low + (high-low) >> 1 or (low + high) >>> 1

The last

Welcome everyone to pay attention to my public kind hao [programmer tracking wind], organized 1000 2019 Java interview questions of many companies more than 400 pages of PDF documents, articles will be updated in it, organized information will also be placed in it. If you like the article, remember to pay attention to me. Thank you for your support!