Summary of Java back-end development interview questions of major companies, and java back-end interview questions

Source: Internet
Author: User
Tags mysql index

Summary of Java back-end development interview questions of major companies, and java back-end interview questions

ThreadLocal (thread variable copy)

Synchronized implements Memory sharing. ThreadLocal maintains a local variable for each thread.

It uses space for time, which is used for data isolation between threads to provide a copy for each thread that uses the variable. Each thread can change its own copy independently, it does not conflict with copies of other threads.

The ThreadLocal class maintains a Map, which is used to store a copy of the variables of each thread. The key of the element in the Map is the thread object, and the value is the copy of the variables of the corresponding thread.

ThreadLocal plays a huge role in Spring, and has appeared in Bean, transaction management, task scheduling, AOP and other modules in the Request scope.

Most beans in Spring can be declared as Singleton scopes and encapsulated using ThreadLocal. Therefore, stateful beans can work normally in multiple threads in singleton mode.

Link: In-depth study of the java. lang. ThreadLocal class

Java Memory Model:

In Java virtual machine specification, data during Java Runtime is divided into six types.

1. program counter: a data structure used to store the memory address of the currently normal program. The multithreading of the Java Virtual Machine is implemented by switching threads in turn and allocating processor time. To restore the thread to the correct position after switching, each thread needs an independent program counter, this region is "thread private ".

2. Java Virtual Machine Stack: A private thread, which has the same lifecycle as a thread. It is used to store local variable tables, Operation stacks, and method return values. The local variable table contains the basic data type and object reference.

3. Local method Stack: It is similar to the Virtual Machine stack, but it is a Native method service used by virtual machines.

4. Java heap: A memory area shared by all threads, where almost all object instances allocate memory.

5. Method Area: The area shared by each thread. It stores the class information, constants, static variables, and compiled code loaded by the virtual machine.

6. runtime Constant Volume pool: represents the constant table in each class file during runtime. There are several constants: Numeric constants, methods, or reference fields during compilation.

Link: JVM virtual machine details in Java

"Can you tell me when java GC is, what it is, and what it has done ?"

When:

1. the new generation has an Eden zone and two vor zones. First, the object is placed in the Eden zone. If there is not enough space, it is placed in one of the VOR zones, if the memory is not enough, it will trigger a occurrence in the new generation of minor GC, put the surviving object into another region vor, and then clear the memory of Eden and the previous region vor. In a GC process, if you find that the objects are still not stored, you can put these objects into the memory of the old age.

2. large objects and long-lived objects directly enter the elderly area.

3. when minor GC is executed, the objects to be promoted to the old age should be analyzed. If the size of the objects to be promoted to the old age area exceeds the remaining size of the old area, then perform a Full GC to obtain the space of the elderly area as much as possible.

Nothing: objects that cannot be searched from GC Roots and are not yet resurrected after a mark is cleared.

What to do:
New Generation: Replication cleaning;
Old: Mark-clear and Mark-compression algorithms;
Permanent generation: class loaders that store classes and classes in Java.

What are GC Roots:
1. referenced objects in the VM Stack
2. Objects referenced by static attributes in the Method Area, objects referenced by constants
3. Objects referenced by JNI (the Native method in general) in the local method stack.

Links: Java GC events (I)

Links: What about Java GC (below)

Link: CMS spam collector Introduction

Synchronized and Lock are reentrant locks. When the same thread enters the synchronization code again, you can use the locks you have obtained.

Synchronized is a pessimistic lock mechanism that exclusively locks. Locks. ReentrantLock is used to complete an operation without locking each time. If the operation fails due to a conflict, retry until the operation is successful.
Applicable scenarios of ReentrantLock

Link: Synchronized keyword, Lock, and explain the differences between them

StringBuffer is thread-safe. Each operation String generates a new object, but StringBuffer does not. StringBuilder is non-thread-safe.

Links: differences between String, StringBuffer and StringBuilder

Fail-fast: An error mechanism in java collections. When multiple threads operate on the content of the same set, a fail-fast event may occur.
For example, when thread A traverses A set through iterator, if the content of the set is changed by other threads, thread A accesses the set, concurrentModificationException will be thrown to generate the fail-fast event.

Happens-before: if the two operations have a happens-before relationship, the result of the previous operation is visible to the next operation.
1. program sequence rules: any subsequent operations of happens-before in a thread.
2. Monitor lock rules: unlock a monitor lock. happens-before then locks the monitor lock.
3. volatile variable rules: Write a volatile domain, and happens-before reads the volatile domain in any future.
4. Transmission: If A happens-before B and B happens-before C, then A happens-before C.
5. Thread startup rules: the start () method of the Thread object happens-before each action of this Thread.

Volatile and Synchronized have four differences:
1. The granularity is different. The former is for variables, and the latter locks objects and classes.
2 syn blocking, volatile thread is not blocked
3 syn guarantees three major features, and volatile does not guarantee atomicity
4 syn Compiler optimization, volatile not optimized
Volatile has two features:
1. ensure the visibility of this variable to all threads. It means that a thread modifies the value of this variable. The new value is visible to other threads, but not multi-thread security.
2. disable command re-sorting optimization.
How does Volatile ensure memory visibility:
1. When writing a volatile variable, JMM will refresh the shared variable in the local memory corresponding to the thread to the main memory.
2. When reading a volatile variable, JMM will invalidate the local memory corresponding to this thread. The thread will then read the shared variable from the main memory.

Synchronization: a task depends on another task to complete. The dependent task can be completed only after the dependent task is completed.
Asynchronous: you do not need to wait for the dependent task to complete, but only notify the dependent task to complete the task. if the task is complete, you will be notified of whether the dependent task is complete. (Asynchronous notification is a feature ).
Call and send text messages to compare synchronous and asynchronous operations.
Blocking: the CPU stops and waits for a slow operation to complete other tasks.
Non-blocking: the non-blocking operation is performed by the CPU during this slow execution. After the slow execution is completed, the CPU will continue to complete subsequent operations.
Non-blocking will increase thread switching and increase the CPU usage time to compensate the system switching cost.

Link: volatile keyword parsing for Java concurrent programming

CAS (Compare And Swap) Lock-free algorithm:
CAS is an optimistic lock technology. When multiple threads attempt to use CAS to update the same variable at the same time, only one thread can update the variable value, while other threads fail, the failed thread will not be suspended, but will be told that the competition failed and can be tried again. CAS has three operands, memory value V, old Expected Value A, and new value B to be modified. If and only when the expected value A is the same as the memory value V, change the memory value V to B. Otherwise, nothing is done.

Link: non-blocking synchronization algorithm and CAS (Compare and Swap) Lock-free Algorithm

The role of the thread pool:
When the program starts, several threads are created for Response Processing. They are called thread pools, and the threads in them are called worker threads.
1. reduce resource consumption. Reuse created threads to reduce the consumption caused by thread creation and destruction.
Second, increase the response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.
Third: Improve the manageability of threads.
Common thread pool: ExecutorService is the main implementation class.
Executors. newSingleThreadPool (), newFixedThreadPool (), newcachedTheadPool (), newScheduledThreadPool ().

Link: thread pool Principle

Link: Analysis of thread pool principles

Classloader working mechanism:
1. Load: import the Java binary code into jvm to generate a Class file.
2. Connection: a) Check: Check the correctness of the data loaded into the Class file B) preparation: allocate the storage space to the static variables of the Class c) Resolution: Convert the symbol reference to a direct reference
3. Initialization: Initialize static variables, static methods, and static code blocks of the class.

Parent-Child Delegation Model: when the class loader receives a class loading request, it first delegates the request to the parent class loader.
User-Defined loaders-> application loaders-> extended class loaders-> started class loaders.

Link: a deep understanding of the Java Virtual Machine note-parent Assignment Model

Links: JVM class loading

Link: JVM (1): Java class loading mechanism

Consistent hash:

Memcahed cache:
Data Structure: key, value Pair
Usage: get, put, and other methods

Link: in-depth analysis of hashcode () and equal () Methods

Redis Data Structure: String-String (key-value type)
The Hash-Dictionary (hashmap) Redis Hash structure allows you to modify only one attribute value just like updating an attribute in the database.
List-List for message queues
Set-uniqueness of Set
Sorted Set-ordered Set can be Sorted
Data Persistence

Link: cache of data using Spring + Redis

In-depth analysis of java automatic packing and unpacking

Java reflection mechanism

How to write an immutable class?

Index: B +, B-, full-text index
Mysql index is a data structure designed to make the database efficiently search for data.
The Common Data Structure is B + Tree. Each leaf node not only stores the index key information, but also adds pointers to adjacent leaf nodes, in this way, B + Tree with sequential access pointers is formed. The purpose of this optimization is to improve the performance of access in different intervals.
When to use indexes:
1. fields that often appear after the group by, order by, and distinc keywords
2. For tables that are often connected to other tables, indexes should be created on the connection fields.
3. fields that frequently appear in the Where clause
4. fields often used for query Selection

Link: MySQL: B + Tree Index Algorithm of InnoDB Storage Engine

Link: Data Structure and algorithm principles behind MySQL Indexes

Spring IOC (control inversion, dependency injection)

Spring supports three dependency injection methods: Property (Setter method) injection, constructor injection, and interface injection.

In Spring, the subjects that constitute the application and the objects managed by the Spring IOC container are called beans.

Spring IOC containers instantiate beans through reflection and establish dependencies between beans.
Simply put, Bean is the object initialized, assembled, and managed by the Spring IOC container.
To obtain a Bean object, first load the configuration file using Resource and start the IOC container. Then, you can call the getBean method to obtain the bean object.
Scope of Spring Bean:
Singleton: there is only one shared Bean instance in the Spring IOC container, which is generally in the Singleton scope.
Prototype: A new Bean instance is generated for each request.
Request: Each http Request generates a new Bean instance.

Link: Spring framework IOC container and AOP Parsing

Link: Usage Analysis of Spring framework annotations

Link: 69 questions and answers about Spring-ultimate list

Proxy has the following advantages: the business class only needs to focus on the business logic itself, ensuring the reusability of the business class.
Java static Proxy:
The proxy object and the target object implement the same interface. The target object is an attribute of the proxy object, the proxy object can add other business processing logic before and after calling the corresponding method of the target object.
Disadvantage: one proxy class can only represent one service class. If the business class adds a method, the corresponding proxy class also needs to add the method.
Java Dynamic Proxy:
The Java Dynamic proxy is used to write a class to implement the InvocationHandler interface, override the Invoke method, and write the enhanced processing logic in the Invoke method, only when this public proxy class is running can it identify the object to be proxy. At the same time, it can implement the method of the proxy class, and then enhance the processing when implementing the class method.
Actually: the method of the proxy object = the method of enhancing the processing + the method of the proxy object

The differences between JDK and CGLIB for generating dynamic proxy classes:
JDK dynamic proxy can only generate a proxy for classes that implement interfaces (instantiate a class ). At this time, the proxy object and the target object implement the same interface. The target object is an attribute of the proxy object. In the specific interface implementation, you can add other business processing logic before and after calling the corresponding method of the target object.
CGLIB is a class implementation proxy. It mainly generates a subclass for the specified class (a class is not instantiated) and overwrites the method.
Spring AOP application scenarios
Performance Detection, access control, log management, transactions, etc.
The default policy is to use JDK dynamic proxy technology if the target class implements interfaces. If the target object does not implement interfaces, CGLIB proxy is used by default.

SpringMVC running principle
1. Submit the client request to DispatcherServlet
2. The DispatcherServlet Controller queries HandlerMapping and finds and distributes it to the specified Controller.
4. After the Controller calls business logic processing, it returns ModelAndView
5. The DispatcherServlet queries one or more ViewResoler view Resolvers and finds the view specified by ModelAndView.
6. The view is responsible for displaying the results to the client.

Link: Spring: annotation-based Spring MVC (I)

Link: Spring: annotation-based Spring MVC (below)

Link: Differences and comparison between SpringMVC and Struts2

Link: SpringMVC and Struts2 comparison

One Http Request
DNS domain name resolution-> initiate TCP three-way handshake-> initiate an http request after establishing a TCP connection-> the server responds to the http request, the browser obtains the html code-> the browser parses the html code, and request resources in html code (such as javascript, css, and images)-> the browser renders the page to the user

Design a storage system for storing massive data: design a logic layer called the "middle layer", at which the massive data of the database is captured and cached, it runs in the memory of the server. Similarly, when new data comes, it is also possible to cache the data and find a way to make it persistent to the database. This is a simple idea. The main step is Server Load balancer, which distributes requests from different users to different processing nodes, first stores them in the cache, and regularly updates data to the primary database. The read/write process adopts an optimistic lock mechanism, which can be read all the time (or when writing data), but each read has a version mark, if the Read version is lower than the cached version, the data will be re-read. This is not a lot of situations and can be tolerated.

Link: differences between HTTP and HTTPS

Link: Why is HTTPS more secure? first look at these

Link: HTTP request message and HTTP Response Message

Link: Comparison of HTTP request methods: GET and POST

Session and Cookie: cookies allow the server to track access from each client, but each access from the client must return these cookies. If there are many cookies, this increases the amount of data transmitted between the client and the server,
The Session solves this problem well. Each time a client interacts with the server, data is stored through the Session to the server, and no Cookie value needs to be returned each time, instead, an ID is returned. Each client accesses the server for the first time and generates a unique ID. The client only needs to return this ID. This ID is usually a Cookie whose NAME is JSESSIONID. In this way, the server can use this ID to retrieve the KV value stored on the server.
Session and Cookie timeout and Cookie security issues

Distributed Session framework
1. Configure the server. The Zookeeper cluster management server can manage the configuration files of all servers in a unified manner.
2. Shared sessions are stored in a distributed cache and can be written and read at any time, and the performance is good, such as Memcache and Tair.
3. encapsulate a class inherited from HttpSession, store the Session into this class, and then store it in the distributed cache.
4. Because the Cookie cannot be accessed across domains, to synchronize sessions, you must synchronize the SessionID to different domain names.

Adapter mode: one interface is adapted to another interface. In Java I/O, InputStreamReader adapts the Reader class to InputStream, thus realizing the quasi-change of byte stream to the bytes stream.
Modifier mode: Maintain the original interface and enhance the original functions.
FileInputStream implements all the interfaces of InputStream. BufferedInputStreams inherits from FileInputStream, which is the actual decorator. It stores the content read by InputStream in the memory to improve reading performance.

Spring transaction configuration method:
1. Cut Point Information, used to locate the business method for implementing the transaction aspect
2. Transaction attributes that control transaction behaviors. These attributes include transaction isolation level, transaction Propagation Behavior, timeout time, and rollback rules.
Spring uses the aop/tx Schema namespace and @ Transaction annotation technology to configure declarative transactions.

Mybatis
Every Mybatis application is centered on an instance of a SqlSessionFactory object. First, use the word throttling to read the configuration file through Resource, then use SqlSessionFactoryBuilder (). build to create SqlSessionFactory, and then use SqlSessionFactory. openSession () to create a SqlSession for each Database Transaction Service.
After Mybatis initialization-> creating SqlSession-> running SQL statements, three processes are returned.

Differences between Servlet and Filter:
The whole process is: the Filter processes user requests, then sends the requests to the Servlet for processing and generates a response, and finally the Filter processes the server response.

Filters are useful in the following ways:
Filters can be used to pre-process and post-process specific url requests.
Before HttpServletRequest arrives at the Servlet, it intercepts the customer's HttpServletRequest.
Check HttpServletRequest as needed. You can also modify the HttpServletRequest header and data.
Before HttpServletResponse arrives at the client, it intercepts HttpServletResponse.
Check HttpServletResponse as needed. You can also modify the HttpServletResponse header and data.

In fact, the Filter and Servlet are very similar. The difference is that the Filter cannot directly generate a response to the user. In fact, the code in the doFilter () method in the Filter is the general code extracted from the service () method of multiple Servlets, which can be used for better reuse.

Filter and Servlet lifecycle:
1. Filter initialization at web server startup
2. If a Servlet is configured with 1, the Servlet is also initialized at Tomcat (Servlet container) startup.
3. If Servlet is not configured with 1, the Servlet will not be initialized at Tomcat startup, but will be initialized when the request arrives.
4. Each Request is initiated. After the Request is responded, the Request is destroyed.
5. After the Servlet is initialized, it will not be canceled as the request ends.
6. When Tomcat is disabled, Servlet and Filter are deregistered in sequence.

The difference between HashMap and HashTable.
1. HashMap is non-thread-safe, and HashTable is thread-safe.
2. HashMap keys and values both allow null values, whereas HashTable does not.
3. Because of thread security issues, HashMap is more efficient than HashTable.

Implementation Mechanism of HashMap:
1. Maintain that each element is an array of a linked list, and each node in the linked list is the data structure of an Entry [] key-value pair.
2. Implemented the array + linked list feature, fast search, and fast insertion and deletion.
3. For each key, its corresponding array index subscript is int I = hash (key. hashcode) & (len-1 );
4. Each newly added node is placed at the beginning of the linked list, and the newly added node points to the first of the original linked list.

Differences between HashMap and TreeMap

Link: a deep understanding of the differences between HashMap and TreeMap in Java

HashMap conflict

Link: HashMap conflict resolution and Principle Analysis

Link: How HashMap works

Link: differences between HashMap and Hashtable

Link: two methods to secure the HashMap thread

Differences between HashMap, ConcurrentHashMap and LinkedHashMap

ConcurrentHashMap Application Scenario

1: The Application Scenario of ConcurrentHashMap is high concurrency, but thread security cannot be guaranteed. The synchronized HashMap and HashMap are used to lock the entire container. After the lock, ConcurrentHashMap does not need to lock the entire container, you only need to lock the corresponding Segment, so it can ensure high concurrent access and improve efficiency.

2: multi-thread writing is supported.
ConcurrentHashMap divides a HashMap into several Segmenet
1. If get is not locked, first locate the segment and then locate the header node to perform the read operation. Value is a volatile variable, so it can ensure that the latest value is read during the competition conditions. If the read value is null, it may be being modified, then the ReadValueUnderLock function is called, lock to ensure that the read data is correct.
2. locks will be applied during Put and will be added to the hash chain header.
3. The lock will also be applied when removing the node. Since the next type cannot be changed, you must copy all the nodes before the deleted node.
4. ConcurrentHashMap allows concurrent modification operations. The key is to use the lock separation technology. It uses multiple locks to control modifications to different segments of the Hash table.

The Application Scenario of ConcurrentHashMap is high concurrency, but thread security cannot be guaranteed. The synchronized HashMap and HashTable are used to lock the entire container. After the lock, ConcurrentHashMap does not need to lock the entire container, you only need to lock the corresponding segment, so it can ensure high concurrent access and improve efficiency.

ConcurrentHashMap ensures that each call is an atomic operation, but it does not guarantee that multiple calls are also an atomic operation.

Link: Java set-ConcurrentHashMap Principle Analysis

Differences between Vector and ArrayList

Link: differences between Vector and ArrayList in Java

ExecutorService service = Executors ....
ExecutorService service = new ThreadPoolExecutor ()
ExecutorService service = new ScheduledThreadPoolExecutor ();

ThreadPoolExecutor source code analysis

The status of the thread pool itself:


Waiting for task queue and working set:


The main status lock of the thread pool:


The lifetime and size of the thread pool:


1.2 internal working principle of ThreadPoolExecutor
With the data defined above, let's take a look at how internal implementation is achieved. Doug Lea's overall thinking is summarized as follows:
1. If the current pool size is smaller than corePoolSize, a new thread is created to execute the task.
2. If the current pool size is greater than corePoolSize and the waiting queue is not full, enter the waiting queue
3. If the current pool size is greater than corePoolSize and smaller than maximumPoolSize, and the waiting queue is full, a new thread is created to execute the task.
4. If the current pool size is greater than corePoolSize and greater than maximumPoolSize, and the waiting queue is full, a denial policy is called to process the task.
5. every thread in the thread pool does not exit immediately after the task is executed. Instead, it checks whether there are other thread tasks in the waiting queue that need to be executed. If new tasks cannot be waited in keepAliveTime, then the thread will exit.

Executor Package Structure




CopyOnWriteArrayList: Lock upon writing. When an element is added, copy the original container, copy a new container, and write it in the new container, after writing, point the reference of the original container to the new container. when reading the data of the old container, you can read the data concurrently. However, this is a weak consistency policy.
Use Cases: CopyOnWriteArrayList is suitable for scenarios where read operations are much larger than write operations, such as caching.

Common Linux commands: cd, cp, mv, rm, ps (process), tar, cat (View content), chmod, vim, find, ls

Conditions for deadlock
1. At least one resource is not shared.
2. possess and wait
3. Non-Preemption
4. Loop wait
To solve deadlocks, the first one is deadlock prevention, that is, preventing the above four conditions from being established at the same time. Second, rationally allocate resources.
Third, the banker algorithm is used. If the resource operating system surplus requested by the process can be satisfied, the system will be allocated.

Inter-process communication

Difference and connection between processes and threads

Operating System Process Scheduling Algorithm

Hierarchical Storage Structure of computer systems

Database transactions are a series of operations performed as a single logical unit of work.


Link: four features of database transactions and the isolation level of transactions

MySQL database optimization Summary

Common MYSQL Optimization Methods

MySQL storage engine-differences between MyISAM and InnoDB

Paradigm in SQL database

The first-level cache of Hibernate is provided by the Session, so it only exists in the Session lifecycle. When the program calls save (), update (), saveOrUpdate () when you call the query interface list, filter, or iterate, Hibernate adds the object to the first-level cache if the Session cache does not contain the corresponding object, when the Session is closed, the cache will also disappear.

The level-1 cache of Hibernate is built in the Session and cannot be uninstalled or configured. The level-1 cache is implemented using the key-value Map method. When the object is cached, the primary key ID of an object is the key of Map, and the object is the corresponding value.

Hibernate second-level cache: puts all data objects obtained into the second-level cache by ID. Hibernate second-level cache policy is a cache policy for ID queries. cache is updated when data is deleted, updated, and added.

Updated on

Java I/O Summary

JVM (8): Overview of JVM knowledge points-required for senior Java engineer interviews

Detailed JDK Design Patterns

Five different methods for creating objects in Java

Several common questions about Java Collections

When is the class loaded and initialized?

Two stacks implement two queues implement stacks

Updated on

Java collection. sort () sort by time list

Single Sign-On principle and simple implementation

Updated on

AQS details

Java concurrent package

Java concurrency toolkit java. util. concurrent User Guide

Updated on

Differences between processes and threads:

Process: each process has its own code and data space (process context). switching between processes has a large overhead. A process contains 1-n threads.

Thread: the same class of threads share code and data space. Each thread has an independent running stack and program counter (PC), and the thread switching overhead is small.

Threads and processes are divided into five phases: creation, readiness, running, blocking, and termination.

Multi-process means that the operating system can run multiple tasks (programs) at the same time ).

Multithreading means that multiple sequential streams are executed in the same program.

There are three methods to implement multithreading in java: one is to continue the Thread class, the other is to implement the Runable interface, and the other is to implement the Callable interface.

Can a Switch use string as a parameter?

A. Before Java 7, the switch can only support byte, short, char, int, or its corresponding encapsulation class and Enum type. In Java 7, String Support is added.

What are the common methods of Object?

A. The equals method tests whether two objects are equal.

B. Method clone to copy objects

C. The getClass method returns the Class object related to the current object.

D. The methods notify, policyall, and wait are used to synchronize threads for a given object.

Four references of Java, strong and weak soft virtual libraries, and Use Cases

A. solve the OOM problem by using soft reference and weak reference: Use a HashMap to store the ing between the image path and the soft reference associated with the corresponding image object. When the memory is insufficient, JVM automatically recycles the space occupied by these cached image objects, effectively avoiding the OOM problem.

B. Implement High-speed cache of Java objects through soft and object re-acquisition methods: for example, if we create a class of Employee, if you need to query the information of an Employee every time. It takes a lot of time to build a new instance, even if it was just queried in a few seconds. We can use soft references and HashMap to save references. First, we can use soft references to reference the instance of an Employee object and save the reference to HashMap, key is the id of this Employee. value is the soft reference of this object. On the other hand, it is used to retrieve the reference and check whether the soft reference of this Employee instance is in the cache. If yes, it is obtained from the soft reference. If there is no soft reference, or the Instance obtained from the soft reference is null, re-build an instance and save the soft reference to the new instance.

C. Strong reference: if an object has a strong reference, it will not be recycled by the garbage collector. Even if the current memory space is insufficient, the JVM will not recycle it, but throw an OutOfMemoryError to terminate the program. If you want to interrupt the association between a strong reference and an object, you can explicitly assign the reference value to null, so that JVM will reclaim the object at the appropriate time.

D. soft reference: When soft reference is used, if the memory space is sufficient, soft reference can continue to be used instead of being recycled by the garbage collector. Only when the memory is insufficient, soft reference will be recycled by the garbage collector.

E. Weak references: objects with weak references have shorter lifecycles. This is because when the JVM executes garbage collection and finds a weak reference object, the weak reference will be recycled regardless of whether the current memory space is sufficient. However, since the garbage collector is a thread with a lower priority, it is not necessarily able to quickly find weak referenced objects.

F. Virtual Reference: as the name suggests, it is just a virtual object. If an object only holds a virtual reference, it is equivalent to no reference and may be recycled by the garbage collector at any time.

What is the difference between Hashcode and equal?

A. it is also used to identify whether two objects are equal. java sets have two types: list and set. set does not allow repeated implementation of elements. This method does not allow repeated implementation, if equal is used for comparison, if there are 1000 elements, you need to call equal 1000 times to compare them with the same object one by one, this will greatly reduce the efficiency. Hashcode is actually the storage address of the returned object. If there are no elements at this position, the elements are directly stored. If there is already an element at this position, at this time, the equal method is called to compare with the new element. If the new element is the same, it will not be saved and hashed to other addresses.

Meanings and differences between Override and Overload

A. overload, as its name implies, is a reload, which can represent the class polymorphism. It can be a function with the same name but the parameter name, return value, and type cannot be the same; or you can change the parameters, types, and returned values, but the function name remains unchanged.

B. this is the meaning of ride (override). When the subclass inherits the parent class, the subclass can define a method with the same name and parameters as its parent class, when a subclass calls this function, it automatically calls the subclass method, and the parent class is overwritten.

For details, go to the case study on the differences between heavy load and overwrite (overwrite) in C ++.

Differences between abstract classes and interfaces

A. a class can only inherit a single class, but multiple interfaces can be implemented.

B. There can be constructor in the abstract class, and no constructor IN THE INTERFACE

C. All methods in the abstract class are not necessarily abstract. You can implement some basic methods in the abstract class. Interfaces require that all methods be abstract.

D. The abstract class can contain static methods, but not interfaces.

E. abstract classes can contain common member variables, but interfaces cannot.

Principles and features of parsing XML: DOM, SAX, and PULL

A. DOM: memory consumption: Read all xml documents into the memory, and then use DOM APIs to access the tree structure and obtain data. This is easy to write, but it consumes a lot of memory. If the data is too large, the mobile phone is not enough, and the mobile phone may crash.

B. SAX: High Resolution efficiency and low memory usage. event-driven: Simply put, documents are scanned sequentially. When a document is scanned) the event processing function is notified when the start and end of an element, the document ends, and so on. The event processing function performs the corresponding action and continues the same scan, until the end of the document.

C. PULL: similar to SAX, it is also event-driven. We can call its next () method to obtain the next parsing event (that is, start document, end document, and start tag, when an element is present, you can call the getAttributte () method of XmlPullParser to obtain the attribute value, or call its nextText () to obtain the value of the current node.

Difference between wait () and sleep ()

Sleep comes from the Thread class, and wait comes from the Object class.

When the sleep () method is called, the thread does not release the object lock. The thread that calls the wait method will release the object lock.

After sleep, system resources are not transferred. wait allows other threads to occupy CPU resources.

Sleep (milliseconds) needs to specify a sleep time, the first time will automatically wake up

The difference between heap and stack in JAVA. Let's talk about the memory mechanism in java.

A. The basic data types are allocated on the stack compared to variables and object references.

B. heap memory is used to store objects and arrays created by new.

C. class variables (static modified variables). The program allocates memory for class variables in the heap upon loading, and the memory addresses in the heap are stored in the stack.

D. instance variable: when you use the java keyword new, the system opens up in the heap and does not necessarily allocate continuous space to the variable. It is based on the scattered heap memory address, the hash algorithm is used to convert a long string of numbers to indicate the "physical location" of the variable in the heap. the life cycle of the instance variable-when the reference of the instance variable is lost, it will be GC (Garbage Collector) included in the recyclable "list", but not immediately released the heap memory

E. local variables: When declared in a method or code segment (such as for loop), the memory is opened in the stack when it is executed. When a local variable is out of scope, immediate memory release

Implementation principle of JAVA Polymorphism

A. abstractly speaking, polymorphism means that a message can adopt different behavior methods based on different sending objects. (Function call is used to send messages)

B. The implementation principle is dynamic binding, and the method called by the program is dynamically bound at runtime. tracing the source code can find that JVM can find a suitable method through automatic parameter transformation.

For more resources, visit the Java backend interview summary.

Various Java-based resources

Interpretation of Java engineers from the interview perspective (1)

Interpretation of Java engineers from the interview perspective (2)

Java interview Reference Guide (1)

Java interview Reference Guide (2)

I came back from Alibaba's interview and wanted to talk to Java programmers.

Interview experience and summary-BAT, Netease, mogujie.com

Summary of Alibaba interview questions over the years (updated continuously in 2017)

List of 133 Java interview questions in the past 5 years

Common Mistakes and details of Java

Java 9 is coming soon. How much do you know about the ten new features of Java 8?

For more information, see my personal public account.



QQ learning exchange group (with dry goods in it ):




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.