Java frequently asked interview questions are organized to help you get the'gold 9 silver 10' (with the answer pure dry goods)

Foreword:

Work as screws and interview rockets. I think this is a headache for every programmer, but there are processes that must go through, especially the questions that the interviewer asks are not clear, and the preparation is insufficient, which leads to not knowing during the interview. How to answer. This article is about some of the questions that I personally selected from dozens of interviews with a relatively high probability of interview. I guarantee that everyone has been asked (just so confident). I hope it will help you find a job.

Insert picture description here
The following questions are just part of the frequently asked interview questions I have compiled. In addition, I have collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. The following are just some screenshots if you want information. You can click 795983544 to receive the secret code CSDN.
Insert picture description here

Basic part

Insert picture description here


1. The difference between abstract class and interface 1. Syntax difference
(1) Abstract classes can have constructors, but interfaces cannot have constructors;
(2) Abstract classes can have ordinary member variables, but interfaces have no ordinary member variables;
(3) There can be non-abstract methods in an abstract class, and the methods in an interface must be abstract;
(4) The methods in an abstract class can be of public and protected types, and the methods in an interface can only be of public type, and the default is public. Abstract type;
(5) There can be static methods in abstract classes, and there can be no static methods in interfaces;
(6) The access type of static variables in abstract classes can be arbitrary, but static variables in interfaces can only be public static final types .
(7). A class can implement multiple interfaces, but a class can only inherit one abstract class;

2. Application difference The
interface plays a role more in the system architecture, mainly used to define the communication contract between the modules; while the abstract class plays a role in the code method, you can use the reuse of the code block;

2. Can interfaces in java inherit general classes? Why?
Not because there can only be three kinds of members in the interface:
1. Public static constant (public static final)
2. Public abstract method (public abstract)
3. Static inner class (static class)
And in a class, even if there is nothing Write, you must also bring a construction method, which will be inherited by subclasses when extends. If it is an interface, this construction method will also be inherited. Obviously, the construction method is not among the above three items.
If the class has general methods and member variables, It will also be inherited by all subclasses, and these cannot appear in the interface, so it is absolutely impossible for an interface to inherit a class

3. The default value of the basic data type? Bytes occupied by basic data types
1. Default value
(1) The default value of byte, short, int, long is 0
(2) The default value of float, double is 0.0
(3) The default value of char is empty
(4) The default value of boolean The value is false
2. The occupied bytes
(1) byte 1 byte
(2) short 2 bytes
(3) char 2 bytes
(4) int 4 bytes
(5) long 8 bytes
( 6) Float 4 bytes
(7) Double 8 bytes

Fourth, which class String belongs to, and the commonly used methods
1.java.lang.string
2.substring(), indexOf(), concat(), endswith(), length(), replace()

5. Familiar network protocol
1. The TCP/IP protocol is a connection-oriented and reliable protocol.

The four layers in the TCP/IP protocol are the application layer, the transport layer, the network layer, and the link layer. Each layer is responsible for different communication functions. Next, we will explain these four layers in detail.

Link layer: used to define the physical transmission channel, usually a driver protocol for certain network connection devices, such as drivers for optical fibers and network cables.

Network layer: The network layer is the core of the entire TCP/IP protocol. It is mainly used to group the transmitted data and send the grouped data to the target computer or network.

Transport layer: It mainly enables network programs to communicate. In network communication, TCP protocol or UDP protocol can be used.

Application layer: Mainly responsible for the protocol of the application, such as HTTP protocol, FTP protocol, etc.
2. FTP file transfer protocol, allowing file transfer on the network.

六、String、StringBuffer、StringBuilder

The value of String is immutable, which leads to the creation of new String objects every time a String is operated on, which can not help but waste a lot of memory space; StringBuilder is a variable class, any operation on the string pointed to by it No new objects will be generated, but single thread is not safe; the underlying method of StringBuffer uses the synchronized keyword, thread is safer, but the efficiency is slower than StringBuilder;

Seven, design mode
Singleton mode: a class can only have one instance, providing a global access point;
factory mode: define an object creation interface, let the subclass decide which class to instantiate;
proxy mode: provide for other objects An agent to control the access of this object;

8. How to deal with high concurrency?
1. Start from the most basic place, optimize the code we write, and reduce the waste of necessary resources.
a. Avoid frequent new objects. For classes that only need one instance of the entire program, we can use singleton mode; for String link operations, use StringBuffer or StringBuilder, and for tool classes, you can use static methods to access;
b. Avoid using errors The way, use high-efficiency classes in java, such as ArrayList has better performance than Vector;
2.html staticization staticize
some content that does not change frequently, reducing the pressure on the server when high concurrency;
3. image server separation
for web servers , The picture is the most resource-consuming, so we put the picture on a separate server, which can reduce the system pressure of the page request server;
4. Cache
avoids going to the database every time to query, reducing the amount of database access; and using redis The database is used as a cache, and its read and write speed is very fast;
5. Database optimization
(1) optimize the sql statement a.
Select statement must specify the column name
b. When the query result is one, use limit 1
c. Avoid using% Prefix search to avoid full table scan

9. The difference between get and post
GET is harmless when the browser rolls back, while POST will submit the request again. The URL address generated by GET can be Bookmarked, but not POST. GET requests will be actively cached by the browser, while POST will not, unless manually set GET requests can only be url-encoded, and POST supports multiple encoding methods. GET request parameters will be completely retained in the browser history, while POST parameters will not be retained. The parameters sent in the URL for GET requests are limited in length, but not for POST. For the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions. GET is less secure than POST, because parameters are directly exposed on the URL, so it cannot be used to transmit sensitive information. GET parameters are passed through the URL, and POST is placed in the Request body.

Ten, JDK1.8 new features

  1. Providing lambda expressions greatly reduces code redundancy;
  2. The default and static keywords can be used in the interface to modify the ordinary methods in the interface;
  3. Provide new API LocalDate | LocalTime | LocalDateTime
    (1) Java.util.Date and SimpleDateFormatter are not safe on the thread, and LocalDate and LocalTime and String are both immutable classes, which are safer on the thread and cannot be modified;
    (2) Java.util.Date month starts from 0, December is 11, and java.time.LocalDate month and week are changed to enum, it is impossible to go wrong;

Collection part

1. The three interfaces of List, Map, and Set have their own characteristics when accessing elements
(1) The add of the Set collection has a boolean type return value. When there is no element in the collection, the element can be successfully added , The return result is true; when there is an element in the set that is equal to the equals method of an element, the element cannot be added. When fetching the element, you can only use the Iterator interface to get all the elements, and each element is traversed one by one;
(2) List means For sequential collections, call the add() method to specify the storage location of the current object in the collection; an object can be repeatedly stored in the collection; each time the add() method is called, the object will be inserted into the collection once, In fact, instead of storing the object itself in the collection, it uses an index variable to point to the object in the collection. When an object is added multiple times, there are multiple indexes pointing to the object. You can use Iterator to take out all the elements when you go to the elements of List, and you can use get(int index) to get the elements of the specified table below;
(3) Map is a collection of two-column elements, call put(key, value), you need Store a pair of key/value, and cannot store duplicate keys. This is judged based on eauals; when fetching elements, use get(key) to get the value corresponding to the key, and you can also get all keys and all values

2. The underlying implementation principle of ArrayList and LinkedList? Why are they thread safe? Under the multi-threaded concurrent operation, what should we use instead?
1. The bottom layer of ArrayList is implemented by arrays. ArrayList allows indexing of elements by sequence number, and inserting elements requires memory operations such as shifting the array, so index insertion is slower; (expansion method) Once we instantiate ArrayList, the parameterless constructor defaults The length of the array is 10. At the bottom of the add method, if more than 10 elements are added, then the bottom of the ArrayList will generate a new array with a length of 1.5 times the length of the original array + 1, and then copy the contents of the original array to the new array, and all subsequent additions Put it in the new array. When the new array cannot accommodate the added element, repeat the process;

2. The bottom layer of LinkedList is realized by a doubly linked list. When fetching elements, it is necessary to traverse the previous item or the next item. When inserting an element, only need to record the preceding and following items of this item, so the insertion is fast and the query is slow;

3. The underlying methods of ArrayList and LinkedList do not add the synchronized keyword. During multi-threaded access, multiple threads will change the data one after another, causing the data to be dirty. In multi-threaded concurrent operations, Vector is used instead. The bottom layer of Vector is also an array, but The underlying methods all add the synchronized keyword to make thread safe, and the efficiency is worse than ArrayList;

3. What is the difference between HashMap and HashTable? What is the underlying implementation? What is the lock mechanism of CurrentHashMap? If you want to make a Map ordered, how to achieve it?

1. Differences:
(1) HashMap does not implement synchronized thread safety, HashTable implements synchronized thread safety;
(2) HashMap allows key and value to be null, while HashTable does not

2. The underlying principle: array + linked list implementation

3. ConcurrentHashMap lock segmentation technology: The reason for the low efficiency of HashTable is that the threads accessing HashTable must compete for the same lock. If there are multiple locks in the container, each lock is used to lock part of the data in the container , Then when multiple threads access different data in the container, there will be no lock competition between threads, thereby improving the concurrent access rate; ConcurrentHashMap uses the lock segmentation technology, first divide the data into a segment of storage, and then give each segment The data is equipped with a lock. When a thread occupies the lock to access one of the data, the data in other segments can also be accessed by other threads;

4. Implement TreeMap

Frame part

1. What is Spring
Spring is a lightweight open source framework created to solve the complexity of enterprise application development; IOC is provided to help us create objects and manage dependencies between objects, and AOP is provided to help us Complete log printing, exception handling, transaction management and other operations, provide JDBC, ORM to complete the operation of the persistence layer, built-in SpringMvc control layer framework

2. Spring advantages
1: Convenient decoupling and simplifying development;
2: Conveniently intercept, run, monitor and other functions of the program;
3: Provide declarative things;
4: Belongs to a universal framework, and it is versatile with many frameworks ;

3. What is IOC? What is AOP ?
(1) IOC called inversion of control refers to the automatic injection of dependent objects when the program is running; the
underlying implementation principle: reflection mechanism
(2) AOP is called aspect-oriented programming, that is, there are many methods in the program that you don’t want to do. In these methods Add
the code of a certain system function; for example, add log, add exception handling, add transaction management. The
underlying implementation principle: dynamic agent

4. Reflection mechanism : Obtain class information according to the specified class name when the program is running;
main functions:
1. Construct an object of a class at runtime;
2. Determine the member variables and methods of a class;
3. Call an object Method;
4. Generate dynamic proxy;

**Five. Dynamic proxy: **Using Java reflection technology to create a new class that implements some given interface at runtime (divided into JDK dynamic proxy and Cglib dynamic proxy).
Main functions:
1. Can hide the delegated class ( The specific implementation of the proxy class)
2. It can realize the decoupling between the client and the delegated class, and can do some extra processing
of the difference between JDK dynamic proxy and Cglib dynamic proxy without modifying the code of the delegated class ?
JDK dynamic proxy can only generate proxy for the class that implements the interface.
Cglib dynamic proxy is not for class. Cglib dynamic proxy is for class implementation proxy. It is mainly to generate a subclass for the specified class and cover the method (integration)

6. What is the DI mechanism?
Dependecy Injection and Inversion of Control are the same concept. Specifically: when a role needs the assistance of another role, in the traditional programming process, it is usually created by the caller The instance of the callee. But the work of creating the callee in spring is no longer done by the caller, so it is called inversion of control. The job of creating the callee is done by spring, and then injecting the caller, so it is called dependency injection;

7. How many spring ioc injection methods are there?
1. Set injection
2. Constructor injection
3. Interface injection.
Spring injection is convenient for management. Dependency injection or inversion of control. To put it bluntly, it uses configuration files. The only advantage of this idea is to increase the flexibility of module reuse. .

Eight, the working principle of hibernate
1. Read and parse the hibernate.cfg.xml configuration file through Configuration().configure();
2. Read and parse the mapping information from hibernate.cfg.xml
3. Through config.buildSessionFactory ();//Create SessionFactory
4.sessionFactory.openSession();//Open Sesssion
5.session.beginTransaction();//Create Transaction
6.persistent operate
7.session.getTransaction().commit() ;//Submit transaction
8. Close Session
9. Close SesstionFactory

Nine, hibernate advantages:
1. The JDBC access database code is encapsulated, which greatly simplifies the tedious and repetitive code of the data access layer.
2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. It greatly simplifies the coding work of the DAO layer
3. Hibernate uses Java reflection mechanism instead of bytecode enhancement program to achieve transparency.
4. The performance of hibernate is very good because it is a lightweight framework. The flexibility of mapping is excellent. It supports various relational databases, from one-to-one to many-to-many complex relationships.

X. SpringMvc running process
1. The user sends a request to DispatchServlet
2. DispatchServlet queries the specific Handler according to the request path 3. DispatchServlet
calls the HandlerAdapter adapter, and the adapter calls the specific Handler to process the business.
4. Handler processing ends and returns a specific ModelAndView to the adapter, The adapter sends ModelAndView to DispatchServlet
5. DispatchServlet gives the view name to ViewResolver view resolver
6. ViewResolver view resolver returns a specific view to DispatchServlet
7. Displays the rendered view to the user

11. The difference between ssh and ssm
SSH usually refers to Struts2 as the controller, spring manages the components of each layer, and hibernate is responsible for the persistence layer.
SSM refers to SpringMVC as the controller, Spring manages the components of each layer, and MyBatis is responsible for the persistence layer.
Common points:
1. Spring dependency injection DI to manage the components of each layer.
2. Use aspect-oriented programming AOP to manage things, logs, permissions, etc.
Differences:
1. The difference between
struts2 and springmvc ; 2. the difference between hibernate and mybatis;

12. What is the difference between struts2 and SpringMvc?
1. The entrance of springmvc is a servlet front-end controller, and the entrance of struts2 is a filter filter;
2. springmvc is developed based on methods, and parameters are passed through method parameters; struts2 is developed based on classes, and parameters are passed through classes. Attributes are passed;
3. SpringMvc parses the request content through the parameter binding period and assigns values ​​to the method parameters; struts2 uses the value stack to store the request and response data, and stores the data through OGNL;

13. The difference between hibernate and Mybatis?
Shielding the low-level access details of jdbc, so that we can access data without dealing with jdbc api; the jdbc api programming process is fixed, and the sql statement and java code are mixed together, and it is often necessary to piece together sql statements, which is very cumbersome; provided by iBatis In order to automatically encapsulate the result set into entity objects and object collections, queryForList returns a collection of objects, and queryForObject returns a single object, and provides parameters for passing the attributes of the entity object to the SQL statement; Hibernate is a fully automatic orm mapping tool, He can automatically generate sql statements, ibatis needs us to write sql statements in the xml configuration file, hibernate or ibatis is much more powerful. Because hibernate automatically generates sql statements and cannot write high-efficiency sql statements, hibernate can help us complete some less complex sql queries, especially complex queries ibatis is more appropriate;

14. Mybatis caching mechanism?
Cache mechanism: Mybatis first queries the result set in the cache, if not, then queries the database, if there is, then retrieves the result set from the cache and does not go to the database;
Mybatis's first level cache is a SqlSession level cache, which needs to be created when operating the database SqlSession object, there is a data structure in the object for storing cached data, the caches between different SqlSessions do not affect each other and cannot be read from each other;
Mybatis's second-level cache is the query cache, and its scope is a mapper namespace, that is, query sql in the same namespace to obtain data from the cache, and the second-level cache can cross SqlSession;
MyBatis does not enable the second-level cache by default, and you only need to write the following code in the configuration file to enable it:

<settings>  
      		<setting name="cacheEnabled" value="true"/>
	</settings>

Web part

1. The nine built-in objects of JSP? What are the roles? What are the methods

request: the client request, this request will contain the parameters from the GET/POST request
response: the response from the webpage back to the client
pageContext: the properties of the webpage are here to manage the
session: the session related to the request
application servlet: the content being executed
out : The output
page used to send the response : the JSP web page itself
config: the servlet framework
exception: for the error page, the uncaught exception
request represents the HttpServletRequest object; it contains information about the browser request, and provides several for The method
response to get cookie, header and session data represents the HttpServletResponse object, and provides several methods for setting the response back to the browser

2. The difference between forward() and redirect()?
Forward is the redirection of control in the container. The client browser will not display the redirected address; redirect is a complete redirection. The browser will get the redirected address and resend the request link, so the browser address You can see the link address after the jump in the column. So forward is more efficient. When forward can meet the needs, try to use forward and help hide the actual link. If you need to jump to a resource on another server, you must use redirect;

Thread part

1. What is the relationship between programs, processes, and threads?

A program can call multiple processes, and a process can have multiple threads; for example, a video player has two processes: one is the process of playing the video, the other is the process of downloading and uploading the video; multiple users watch Video is that multiple threads access a process;

2. What is the difference between single thread and multithread, and the meaning of multithread?

If the program has only one execution path, it is single-threaded; on the contrary, if there are multiple paths, it is multi-threaded;
the meaning of multi-threading allows the program to perform multiple things at a time, which improves the utilization rate of the application;

3. Understand concurrency and parallelism

Concurrency: Through the CPU scheduling algorithm, users can appear to execute at the same time. In fact, it is through the CPU to switch at a high speed. It is not true at the same time. This is concurrency.
Parallel: Multiple CPU instances or multiple machines execute a piece of logic at the same time. It's real simultaneously, this is parallelism;

4. How to create a thread
Method one:
(1) The class inherits the Thread class;
(2) This class rewrites the run method of the Thread class, and stores the code to be executed by the thread in the run method;
(3) Thread object call start() method, start the thread, the thread will automatically execute the run method
Method two
(1) the class inherits the Runnable interface
(2) rewrite the interface run method, and store the thread execution code in the run method
(3) create a Thread object, also Is to create a thread
(4) Thread thread object calls the start method to start the thread

5. How many states of thread?
Initialization (new Thread()) --> Ready (start() ready to execute) --> Execute (obtain CPU execution rights)
Execute 1 --> Wait (wait()): The thread is in a waiting state and cannot wake up by itself. It can be awakened by notify() or notifyAll(). The waiting thread will release the CPU execution power and release resources at the same time;
execute 2 --> sleep (sleep()): put the current orthographic execution thread to sleep within the specified number of milliseconds , Just suspend execution, he will release CPU execution rights, but will not release resources, the set time is up, it will leave the sleep state and enter the execution state;
execution 3 --> blocking: when multiple threads have input and output, There will be a blocking state.
Execution 4 --> Death: the run method is finished, and the thread is finished, that is, it is dead

6. Multi-threaded solution
(1) Synchronized code block: put the code block into the synchronization lock
(2) Synchronized method: add the synchronized keyword before the method

7. What is a deadlock (deadlock)?
The deadlock occurred when both processes were waiting for the object to execute before continuing, and both processes were caught in infinite waiting;

database

1. What do you know about database optimization?
1. The Select statement must specify the field name
2. When only the query result is a piece of data, use limit 1
3. Avoid the where clause to judge the null value of the field (the judgment of null will cause the engine to give up using the index and perform a full table scan )
4. It is not recommended to use% prefix fuzzy query to prevent full table scan

Two, the four characteristics of the transaction
1. Atomicity (Atomicity) Atomicity
means that all operations included in the transaction either succeed or fail and roll back;
2. Consistency
means that a thing is executed before and after execution Both must be in a consistent state; for the transfer, suppose that the money of both A and B is 5000 in total, no matter how the transfer between A and B, how many transfers, the sum of the two people's money after the end of the transaction is still 5000. This is the consistency of the transaction;
3. Isolation
isolation When multiple users access the database concurrently and operate the same table, the transaction opened by the database for each user cannot be interfered by other transaction operations. Between multiple concurrent transactions To be isolated from each other; for example, two concurrent transactions T1 and T2, from the perspective of transaction T1, T2 either ends the transaction before the start of T1, or starts the transaction after the end of T1, this is the isolation of the transaction;
4. The durability of
execution is Refers to once a transaction is submitted, then the change to the data in the database is permanent;

Three, Spring isolation level

  1. If multiple transactions access the same data at the same time, what problems may occur if the necessary isolation level is not adopted?
    (1) Dirty read: read expired data, that is, one thing reads new data that is not committed by another transaction;
    (2) phantom read: read temporary data, that is, when one thing is modifying the entire table, the other A transaction adds data to it, so after the execution of the first transaction, it is found that there is no modified data, as if an illusion has occurred;
    (3) Non-repeatable reading: it means to execute two consecutively in the same transaction The same select statement, the Del statement has not been executed but the results are different, this is non-repeatable reading;
  2. Spring transaction isolation level
    (1) Default: use the database's own isolation level ORACLE (read committed) Mysql (repeatable read);
    (2) Read_Uncomited: read uncommitted (dirty read), the lowest isolation level, everything is possible;
    (3) Read_Commited: the read has been submitted, there is a risk of phantom reading and non-repeatable reading;
    (4) RepeaTable_Read: repeatable reading, but there is still the risk of phantom reading;
    (5) Serializable: serialization, the highest isolation sector, to eliminate All hidden dangers, but low efficiency;

4. How does Spring set the isolation level?

  1. Use @Transactional annotation to set the isolation level of the isolation attribute in the transaction management of declarative transactions
  2. Set the transaction tx:method element in the configuration file

server

Nginx is a lightweight web server/reverse proxy server and email (IMAP/POP3) proxy server, and is issued under a BSD-like protocol. It is characterized by less memory and strong concurrency.

The function of Keepalived is to detect the status of the server. If a web server is down or the work fails, Keepalived will detect it and remove the faulty server from the system. At the same time, it will use other servers to replace the work of the server. After it works normally, Keepalived automatically adds the server to the server group. All these tasks are automatically completed without manual intervention. All that is required is to repair the faulty server.

Redis

1. Set the expiration time of the cached value?
(1) Commonly used method: expire key time (in seconds)
(2) String unique method: setex (String key, int seconds, String value)
If no time is set, the cache will never expire;
2. Redis three expiration strategies
(1) Timed deletion: While setting the key expiration time, create a timer for the key so that the timer deletes the key when the key expires;
(2) Lazy deletion: the key expires It is not deleted at the time, every time the key is obtained from the database, it is checked whether it has expired. If it is deleted, it returns null;
(3) Periodic deletion: delete the expired key once every certain period of time

to sum up:

In response to the above interview questions, I summarized most of the interview questions and answers involved in the Internet company java programmer interview. Documents and architecture video materials are shared for free (including Dubbo, Redis, Netty, zookeeper, Spring cloud) , Distributed, high concurrency and other architecture technical materials), I hope to help you review before the interview and find a good job, and also save everyone’s time to search for materials on the Internet to learn. You can also pay attention to me for more dry goods in the future share it.

In addition, if you want to answer the interview, please click on the 795983544 secret code CSDN to get it yourself. I also collected more than 20 years of company interview knowledge points and various technical points. Here are some screenshots I hope to help you.
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/banzhuanhu/article/details/108645162