2020 Spring recruit Java interview questions summary "two"

Foreword

Still come to the party, to share 2020 spring trick questions face this issue, and watched the last article of little friends, remember to give this article a point like oh ~

So word does not say, give us a direct dry ,,,

  1. Java exception handling in

In Java, all exceptions have a common ancestor java.lang Throwable class package.

Throwable comprises two subclasses:

Exception (abnormal):

Abnormal program itself can handle. Exception class has an important subclass of RuntimeException. RuntimeException Thrown by the Java Virtual Machine. NullPointerException (when you want to access the variable does not reference any object, throw the exception), ArithmeticException (arithmetic exception when an integer divide by zero, Thrown) and ArrayIndexOutOfBoundsException (subscript bounds exception).

Error (error):

Error can not handle, it expressed serious problems running the application. Most errors unrelated to the operation and execution of code writers, and that the problem code is running JVM (Java Virtual Machine) appears. For example, Java virtual machine runtime error (Virtual MachineError), when the JVM is no longer required memory resources to continue operations, OutOfMemoryError will appear. When these exceptions occur, Java Virtual Machine (JVM) will generally choose to terminate a thread.

These errors indicate a failure in its own virtual machine, or VM occurs when trying to execute applications such as Java Virtual Machine runtime error (Virtual MachineError), the class definition error (NoClassDefFoundError) and so on. These errors are not checked because they are outside the control and processing power of the application, but the vast majority are not allowed in the program is running situation. For application design and reasonable, even if an error does occur, in essence, we should not try to deal with the abnormal situation caused by it. In Java, the error described by the subclasses of Error.

Note: the difference between exceptions and errors: the program itself can be an exception handling, error handling is not.

Common methods class Throwable

public string getMessage (): returns a brief description when abnormalities occur

public string toString (): Returns detailed information when abnormalities occur

public string getLocalizedMessage (): Returns the exception object localization information. Using subclass of Throwable override this method to generate localized information. If the child class does not override this method, the same result information returned by the method getMessage () returns

public void printStackTrace (): print object encapsulates Throwable exception information on the console

Exception handling summary

try block: for capturing exception. Thereafter be zero or more catch blocks, if there is no catch block, must be followed by a finally block.

catch block: a process to try to capture the exception.

finally block: whether to capture or handle exceptions, finally block will be executed in a statement. When encountering a return statement in the try block or catch block, finally statement block will be executed before the method returns.

eg:

If the call f (6), the return value will be 0, since the return value to cover the return value of the try block finally statement.

In the following four special cases, finally block is not executed:

Abnormality has occurred in the first row finally block. Because in the other row, finally block will still be implemented

In the previous code with the System.exit (int) have withdrawn from the program. function is parameterized exit; if the statement after an exception statement, finally executes

Threaded programs where the death.

Close CPU.

  1. IO streams in Java

In accordance with the flow of shunt it can be divided into input and output streams;

Divided according to the operation unit, it may be divided into a byte stream and character stream;

Stream is divided into nodes and the role of the processing flow according to the flow.

Java Io flows involving a total of more than 40 classes, which looks very messy, but in fact are the rules, and there is very close contact with each other, more than 40 classes Java I0 flows are from the following four abstract class derived from the base class.

InputStream / Reader: base class for all input streams, the former is the input stream of bytes, which is the character input stream.

OutputStream / Writer: base class for all output streams, the former is output byte stream, which is the output character stream.

FIG classified by mode of operation structure:

FIG classified by mode of operation structure:

problem:

In the file read and write and network transmission and reception, the smallest unit of information are stored in bytes, why I / O operations to flow into a byte stream and character stream does it operate?

answer:

Java Virtual Machine character stream is converted by the byte, the problem lies in this process be very time-consuming, and, if we do not know it into a byte stream encoding type prone to garbled phenomenon. Thus, I / O stream provides an interface directly operate on the characters, the character we usually convenient to operate. If the audio files, images and other media files with a byte stream is better, if it comes to the characters, then use a stream of characters better.

BIO, NIO, AIO What is the difference?

BIO (Blocking I / O): synchronous blocking I / O mode, the read data is written to be blocked waiting for its completion within a thread. In the case of active connections is not particularly high (less than stand-alone 1000), and this model is quite good, allowing each to focus on their connected I / O and simple programming model, it does not give much thought to overload the system, issues such as limiting. Thread pool itself is a natural funnel, some systems can not deal with a buffer or a connection request. However, when connected to the face of thousands or even one million, BIO traditional model is powerless. Therefore, we need a more efficient I / O processing model to cope with higher concurrency.

NIO (New I / O): NIO is a synchronous non-blocking I / O model, incorporated in the Java 1.4 NIO frame corresponding java.nio package, provided Channel, Selector, Buffer other abstract. NIO N can be understood as the Non-blocking, not simply New. It supports buffer-oriented, channel-based I / O operation method. NIO provides traditional BIO model Socket and ServerSocket corresponding SocketChannel and ServerSocketChannel two different socket channel to achieve both channel supports blocking and non-blocking modes. Blocking mode using just tradition, like support, is relatively simple, but the performance and reliability is not good; just the opposite non-blocking mode. For low load, low concurrent applications, can use synchronous blocking I / O rate and to enhance the development of better maintenance; high load, high concurrency (network) applications, use of non-blocking mode to develop NIO

AIO (Asynchronous I / O): AIO i.e. NIO 2. Introduced an improved version of NIO 2 NIO in Java 7, it is asynchronous non-blocking IO model. Asynchronous IO is based on the event and the callback mechanism to achieve, that is, after the application of the operation will be returned directly, will not plug in there, when background processing is complete, the operating system will notify the appropriate thread for subsequent operations. AIO is an acronym for asynchronous IO, although the NIO in network operation, provides non-blocking method, but IO NIO or synchronous behavior. For the NIO, the thread when our business is ready IO operations to be notified, and then they were operated by the IO thread itself, IO operation itself is synchronized. Access to relevant information online, I found that for the present application AIO is not very extensive, but also try to use the AIO had before Netty, but gave up.

  1. Common keywords summary: static, final, this, super

final keyword

final keyword is mainly used in three places: variables, methods and classes.

1, for a final variable, if the basic data types of variables, then its value can not be changed once after the initialization; if it is a reference type variable, then after its initialization will not allow its point to another object.

2, when modifying a class with a final, indicating that this class can not be inherited. All members of the final class methods will be implicitly designated as the final method.

3, there are two reasons for using final methods. The first reason is the method of locking to prevent any derived class to modify its meaning; second reason is efficiency. In earlier versions of Java implementation, it will be built into final method call. However, if the method is too large, you may not see any performance embedded calls to bring (the current version of Java do not need to use these methods to optimize the final). All private class methods implicitly designated as final.

The static keyword

There are four main static keyword usage scenarios:

Member variables and member methods modifications: the modified static members belong to the class, not part of a single class of objects, is shared by all objects in the class, and can be recommended by the class name calling. Static member variables are declared in a static member variables, static variables stored in the memory area of ​​Java method area. Call format: name of the class static variable names class names static method name ().

Static block of code: static block of code is defined in an outer class methods, static block of code (static block of code -> non-static block -> Constructor) before the non-static block. No matter how many objects the class is created, static code block is executed only once.

Static inner class (static modification of that kind of thing can only be modified inside the class): There is a difference between the maximum static inner class with non-static inner classes: non-static inner classes after the completion of the translation will implicitly holds a reference that points to create its enclosing class, but static inner classes do not. Without this reference means that: 1. It does not require the creation of dependence created enclosing class. 2. It can not use any non-static member variables and methods of the enclosing class.

Static guide package (used to import class static resources, new features after 1.5): The format is: import static once every two keywords can specify import specify a static resource class, and does not require the use of the class name calling static class members, the class can use static member variables and member methods directly.

this keyword

this keyword is used to reference the current instance of the class.

In the example above, this keyword is used in two places:

this.employees.length: access variables in the current instance of the class Manager.

this.report (): method call to the current instance of the class Manager.

This keyword is optional, which means that if the same performance in the above example without using this keyword. However, using this keyword may make the code more readable or understandable.

super keyword

super keyword is used to access variables and methods from the parent class is a subclass.

In the example above, Sub class to access the parent class member variable number and call its parent class's Super showNumber () method.

Use this super problem and to note:

When using the super in the constructor () call other constructor in the parent class, the statement must be the first line of the constructor, otherwise the compiler will complain. In addition, this call other constructor in this class, but also on the first line.

this, super not be used in a static method.

Simple explanation:

Modified static members belong to the class, not part of a single class of objects, is the class of all objects share. And this representative of a reference to this class of objects, directed present class object; and super representative parent class object reference to point to the parent object; therefore, this and super something belonging to the target areas, the static method is what belongs to the class category .

  1. Servlet summary

In Java Web program, Servlet mainly responsible for receiving user requests HttpServletRequest, handled accordingly in doGet (), doPost (), and the HttpServletResponse response to user feedback. Servlet initialization parameters may be provided, for internal use Servlet. A Servlet class will be only one instance, call the init () method when it is initialized, calls the destroy () method ** when destroyed. ** Servlet need to configure (create Servlet automatically configures the MyEclipse) in web.xml, a Servlet can set up multiple URL access. Servlet is not thread safe, so be careful to use class variables.

Servlet interface defines five methods, wherein the first three methods associated with Servlet life cycle:

Life cycle:

After the Web Servlet container loading and instantiating, Servlet life cycle starts, it initializes Servlet container runs the init () method; Servlet invocation request arrives when the service () method, service () method invocation request will be needed or the like corresponding doGet doPost method; closed when the server or servers would be unloaded items Servlet examples destruction, then calls the destroy Servlet () method.

init method and destroy method only once, service method Servlet will be executed each time the client requests. Servlet is sometimes used that require initialization and destruction of resources, so you can put the code into the init method to initialize resources, the destruction of the code resources into the destroy method, so that you do not need to deal with each client's request to be initialized and destruction of resources.

get and post requests differences:

Can get and post as two different acts, and there is no essential difference between the two, it is the underlying TCP connection. get request for obtaining resources from the server, and the post is used to submit data to the server. For example, you can get a list of people request, you need to create a person can post. This is also a basic requirement Restful API.

Forwarding (Forward) and redirection (Redirect) the difference between:

Forwarding server behavior, redirect the client behavior.

Forwarding (Forward) target by RequestDispatcher forward (HttpServletRequest request, HttpServletResponse response) implemented method. RequestDispatcher () method is obtained by getRequestDispatcher HttpServletRequest. For example, the following code is to jump to login_success.jsp page.

Redirection (the Redirect) is achieved using the status code returned by the server. When a client browser requests to the server, the server returns a status code. Server status codes provided by the HttpServletResponse setStatus (int status) method. If the server returns a 301 or 302, the browser will go to a new URL re-request the resource.

1, showing it from the address bar

forward is the server resource requests, the server URL to directly access the target address, the response content that URL to read over, and then re-distributed to the content browser. browser does not know the content sent by the server where it came from, so its address bar or the original address. redirect server is based on logic, send a status code that tells the browser to re-request the address, so the address bar shows the new URL.

2, the data sharing is

forward: Forwarding pages and pages can be forwarded to the request which shared data redirect:. You can not share data.

3, for the use of local

forward: time for the general user login, based on the role forwarded to the appropriate module redirect:. Generally used to return the main page and jump to other sites when the user logs off landing, etc.

4, speaking from efficiency

forward: High redirect:. low.

Auto Refresh (Refresh)

Automatic refresh not only can automatically jump to another page after a period of time, it can also automatically refresh this page after some time. Header property provided by Servlet HttpServletResponse object automatic refresh example:

JSP and Servlet What is the relationship

Servlet is a special Java program that runs on the JVM server, the server can count on the support provided to the browser to display the content. The JSP is essentially a simplified form of the Servlet, JSP is similar to the processing server to a Java program Servlet, can simplify the generation of page content. Servlet and JSP main difference that the application logic is a Java Servlet file, and completely separated from the presentation layer HTML. The situation JSP is Java and HTML can be combined into a .jsp file extension. Some people say, Servlet is written in Java, HTML, and JSP Java code is written in HTML, of course, this argument is very one-sided and inaccurate. JSP focuses on view, Servlet more focused on the control logic in the MVC architecture model, suitable to act as JSP view (view) and Servlet for serving as a controller (controller).

  1. JSP summary

JSP is a class Servlet, but the HttpServlet works are not the same. After HttpServlet is the first by compiling the source code for the class file server to deploy to the next, as compiled after the first deployment. The JSP is compiled before deployment. When JSP will first request for a JSP file is compiled into the client HttpJspPage class (a subclass of Servlet interfaces). This class will be temporarily stored on the server server working directory.

JSP built-in objects:

JSP has nine built-in objects:

request: the client's request package, containing the parameters from the GET or POST request;

response: Response package end server to client;

pageContext: other objects can be acquired by the object;

session: the user session object encapsulates;

application: object encapsulates server operating environment;

out: output target stream output from the server response;

config: configuration objects Web applications;

page: JSP page itself (equivalent to this Java program);

exception: package page throwable exception.

The main method of the Request object which

setAttribute (String name, Object): set the name for the name of the request parameter values

getAttribute (String name): Returns the value specified by the attribute name

getAttributeNames (): Returns the request object is a collection of the names of all the properties, the result is an enumeration of instances

getCookies (): Cookie returned to the client all the objects, the result is an array of Cookie

Returns the requested length of the Body: getCharacterEncoding (): returns the character encoding request = getContentLength ()

getHeader (String name): get the file header information HTTP protocol definition

getHeaders (String name): Returns the name of all the values ​​of the request Header, the result is an enumeration of instances

getHeaderNames (): Returns the name so request Header, the result is an enumeration of instances

getInputStream (): returns the input stream request for obtaining data request

getMethod (): get the client Method to transmit data to the server

getParameter (String name): get the client are transmitted to the server name specified by the parameter values

Examples of obtaining the names of all the parameters of the client to the server side, the result is an enumeration of: getParameterNames ()

getParameterValues ​​(String name): get all values ​​are specified by name arguments

Gets the name of the client protocol to transmit data to the server is based on: getProtocol ()

getQueryString (): get the query string

getRequestURI (): Get the requesting client address string

getRemoteAddr (): obtain the IP address of the client

getRemoteHost (): get the client's name

getSession ([Boolean create]): Returns the Session associated with the request

getServerName (): Gets the server name

getServletPath (): Gets the path to the script file requested by the client

getServerPort (): Gets the server port number

Delete a property request: removeAttribute (String name)

JSP in four scopes

JSP in four scopes include page, request, session and application, specifically:

representatives of the relevant page with a page of objects and attributes.

A request on behalf of related objects and attributes with the Web request issued by the client. A request may span multiple pages, to a plurality of Web components; this scope may be placed in the required temporary data displayed page.

On behalf of a user session established with a session with the server-related objects and attributes. Associated with a user data should be placed in the user's own session.

application on behalf of the entire Web application-related objects and attributes, it is essentially across the entire Web applications, including multiple pages, requests, and a global session scope.

6. Talk about the difference between List, Set, Map of the three?

List (in order to deal with a good helper): List stores a set of interfaces is not unique (there can be multiple elements reference the same object), ordered objects

Set (pay attention to the unique nature): Do not allow duplicate collections. There will be no more elements refer to the same object.

Map (expert with Key to search for): Use to store key-value pairs. Map will maintain and Key associated value. Key two can reference the same object, but can not repeat Key, typically of type String Key, but may be any object.

7.Arraylist and LinkedList difference?

  1. Whether guarantee thread safety: ArrayList and LinkedList are not synchronized, that is not guaranteed to be thread safe;

  2. Underlying data structure: Arraylist bottom Array using a dynamic array; using the LinkedList underlying Link linked list data structure (as before JDK1.6 circular linked list, JDK1.7 canceled and the circular doubly linked list bidirectional attention distinction circular linked list.)

3. Efficiency different:

When the Random Access List (get and set operations), are more efficient than the ArrayList LinkedList because LinkedList linear data storage, it is necessary to move the pointer from front to back order lookup.

When operations (add and remove operations) add and delete data, and more efficient than the LinkedList ArrayList, because ArrayList is an array, so the time in which to add or delete operation, then the operating point will index all the data in the index cause the impact, the need for mobile data.

  1. Supports fast random access: LinkedList does not support efficient random element access, and support for ArrayList. Quick access to fast random access is via the object element is an element number (corresponding to the get (int index) method).

  2. Memory footprint: wasted space ArrayList is mainly reflected in the list at the end of the list will reserve some space capacity, cost and space LinkedList is reflected in each of its elements need to consume more space than ArrayList (because you want to store direct and immediate successor and predecessor data).

  3. The difference between Vector and ArrayList it? Why Arraylist replaced Vector it?

All methods of the Vector class are synchronized. A Vector object can be accessed by two threads safely, but one thread to access the code words of Vector to spend a lot of time on the synchronous operation.

Arraylist not synchronized, it is recommended that when not needed to ensure the safe use of thread Arraylist.

  1. Talk about it ArrayList expansion mechanism

a.ArrayList building functions:

** When you create a ArrayList with no-argument constructor, assignment is actually initialize an empty array. When really add to the array elements operate, really allocated capacity. ** When adding the first array element namely, expansion of the capacity of the array 10 (will be explained below why 10)

b. Expansion Mechanism

Here no-argument constructor to create ArrayList A case study

  1. First look at the add method

  2. Let's look at ensureCapacityInternal () method

We can see the add method first calls ensureCapacityInternal (size + 1)

When you want to add into the first element, to be minCapacity 1, in comparison Math.max () method, be minCapacity 10.

3. ensureExplicitCapacity() 方法

When we add an element to the first intake ArrayList, elementData.length is 0 (or because a List empty), because the execution of ensureCapacityInternal () method, in this case 10 so minCapacity. At this point, minCapacity - elementData.length> 0 holds, and hence will enter grow (minCapacity) method.

When the second add elements, be minCapacity is 2, then e lementData.length (capacity) after adding the first expansion element 10 into the. At this point, minCapacity - elementData.length> 0 does not hold, it will not enter (execute) grow (minCapacity) method.

When adding 3,4 · · · 10 to the second element, the method is still not executed grow, the capacity of the array 10 are.

Until add the first 11 elements, minCapacity (11) is larger than elementData.length (10). Grow into the methods of expansion.

  1. grow () method

int newCapacity = oldCapacity + (oldCapacity >> 1), so that after each expansion ArrayList capacity will become 1.5 times the original! (JDK1.6 later version) is JDk1.6 version, after the expansion capacity of 1.5 times +1!

When the first add element, oldCapacity is 0, if after comparing the first decision is affirmative, newCapacity = minCapacity (10). But if the judge does not set up a second, that newCapacity than MAX_ARRAY_SIZE large, it will not enter hugeCapacity method. Array capacity 10, add methods return true, size increased to 1.

When the element 11 into the first add grow method, newCapacity 15, be minCapacity ratio (11) is large, if the first determination is not satisfied. The new capacity is not greater than the maximum array size, will not enter hugeCapacity method. Expanding the capacity of the array 15, add methods return true, size increased to 11.

So ??????

5. hugeCapacity () method.

From the above grow () method source code we know: if the new capacity is greater than MAX_ARRAY_SIZE, enter the (execution) hugeCapacity () method to compare minCapacity and MAX_ARRAY_SIZE, if minCapacity greater than the maximum capacity, the new capacity was Integer.MAX_VALUE, otherwise, the size of new capacity It was MAX_ARRAY_SIZE is the Integer.MAX_VALUE - 8.

And the Hashtable difference 10.HashMap

Thread Is it safe: HashMap is not thread-safe, HashTable are thread-safe; internal HashTable basic methods have been synchronized modification. (If you want to ensure thread-safe, then use ConcurrentHashMap it!);

Efficiency: Because the thread safety problems, HashMap HashTable than a little high efficiency. Further, the HashTable basically been eliminated, it is not used in the code;

Null key support and the Null value: HashMap in, as null key, only one such key, there may be one or more keys corresponding to the value of null. . But put the HashTable into the keys as long as there is a null, direct throw NullPointerException.

The initial capacity and each capacity expansion size different sizes: ① When creating an initial value if the capacity is not specified, Hashtable default initial size is 11, after each expansion, the capacity of the original becomes 2n + 1. HashMap default initialization size is 16. After each expansion, capacity becomes 2 times the original. ② When you create if given the capacity of the initial value, Hashtable will direct you to use a given size, and HashMap will expand its size is a power of 2 (tableSizeFor HashMap in () method guaranteed source is given below Code). That HashMap always use a power of 2 as the size of the hash table, it will be introduced later to why it is a power of two.

Underlying data structure: JDK1.8 after HashMap has made significant changes in resolving hash collision, when the chain length is greater than the threshold value (the default is 8), into a red-black tree list to reduce the search time. Hashtable is no such mechanism.

11.HashMap and HashSet difference

If you've seen HashSet source, then you should know: HashSet is based on the underlying HashMap implementation. (HashSet source very, very small, because in addition to clone (), writeObject (), readObject () is outside the HashSet themselves having to implement, other methods are methods in HashMap called directly.

How to check for duplicate HashSet

When you join objects HashSet, HashSet first calculates a target value hashcode to determine the position of the object is added, but also compared with other added values ​​hashcode object, if there is no match hashcode, assume the object is not repeated HashSet appear. But if the object has the same hashcode value found, then we will call equals () method to check whether the object really equal hashcode same. If they are the same, HashSet will not let join a successful operation. (Excerpt from my book Java enlightenment "Head fist java" second edition)

And the Hashtable difference 12.ConcurrentHashMap

ConcurrentHashMap and Hashtable difference is mainly reflected in the different ways to achieve thread-safe.

Underlying data structure: ConcurrentHashMap bottom segment array using JDK1.7 + linked list implementation, the data structure used with JDK1.8 HashMap1.8 like structure, a linked list arrays + / red and black binary tree. Hashtable HashMap underlying data structure and are similar to the previous JDK1.8 + linked list using an array, the array is subject HashMap, the main chain is to solve hash collision exists;

Way to achieve thread-safe (important): ① when the JDK1.7, ConcurrentHashMap (sub-lock) on the whole bucket array has been divided segments (Segment), each lock only lock the container in which part of the data, multithreaded access container data from different segments, there would not lock contention and improve concurrency rate. JDK1.8 to have abandoned the concept of time Segment, but directly linked list data structure Node array + + red-black tree to implement concurrency control and synchronized using CAS operated. (JDK1.6 later on synchronized lock to do a lot of optimization) the whole looks like optimized and thread-safe HashMap, although you can still see the data structure Segment in JDK1.8, but has simplified the property, only to compatible with older versions; ② Hashtable (same lock): use synchronized to ensure thread safety, efficiency is very low. When one thread to access synchronization method, other threads can also access synchronization method, might be blocked or enter a polling state, such as adding elements using a put, you can not add another thread to use elements put, you can not use get, competition will become increasingly fierce the lower the efficiency.

HashMap multi-threaded operating results in infinite loop problem

The main reason is that in the concurrent Rehash will result in a circular linked list is formed between the elements. However, jdk 1.8 solves this problem, but still do not recommend the use of HashMap in a multi-threaded, multi-threaded use because HashMap will still have other problems such as data loss. Concurrent environment recommended ConcurrentHashMap.

Finally, the same, the entire contents of this article Xiao Bian has been organized into a PDF document . For free access, please click on the link below: https: //shimo.im/docs/pVhDCpYqdRTqWRqq/read to

Published 65 original articles · won praise 5 · Views 5350

Guess you like

Origin blog.csdn.net/WANXT1024/article/details/104364675