Home  >  Article  >  Java  >  Summary of some classic Java interview questions

Summary of some classic Java interview questions

零下一度
零下一度Original
2017-06-25 10:54:401055browse

Interviewing is something that each of us has to go through, and most of us do it more than once. Here is a summary of the latest 2016 interview questions, so that everyone can get twice the result with half the effort when looking for a job.

1. Can Switch use string as a parameter?

a. Before Java 7, switch could only support byte, short, char, int or their corresponding encapsulation classes and Enum types. In JAVA 7, String support was added.

2. The difference between equals and ==:

a.== is used to determine whether two variables or instances point to the same memory space. equals is used to determine what two variables or instances point to. Are the values ​​of the memory space the same?

3.What are the public methods of Object?

a. Method equals tests whether two objects are equal
b. Method clone performs object copy
c. Method getClass returns the Class object related to the current object
d. Method notify , notifyall, and wait are all used for thread synchronization of a given object

4. Java’s four types of references, strong, weak, soft, and virtual, usage scenarios

a. Using soft references and weak references to solve the OOM problem: use a HashMap to save the mapping relationship between the path of the image and the soft reference associated with the corresponding image object. When the memory is insufficient, the JVM will automatically reclaim the space occupied by these cached image objects, thus effectively Avoiding the problem of OOM
b. Implement the cache of Java objects through the soft-accessible object retrieval method: For example, we create an Employee class, and if we need to query the information of an employee each time. Even if it was just queried a few seconds ago, an instance must be rebuilt, which takes a lot of time. We can combine soft references and HashMap. First, save the reference: reference an instance of the Employee object in the form of a soft reference and save the reference to the HashMap. The key is the employee's id and the value is the soft reference of this object. , on the other hand, is to retrieve the reference and see if there is a soft reference to the Employee instance in the cache. If so, obtain it from the soft reference. If there is no soft reference, or the instance obtained from the soft reference is null, rebuild an instance and save the soft reference to the newly created instance
c. Strong reference: If an object has a strong reference, it will not be Garbage collector recycling. Even if the current memory space is insufficient, the JVM will not reclaim it, but will throw an OutOfMemoryError error, causing the program to terminate abnormally. If you want to break the association between a strong reference and an object, you can explicitly assign the reference to null. In this way, the JVM will recycle the object at the appropriate time
d. Soft reference: When using soft reference When referencing, if there is enough memory space, the soft reference can continue to be used without being recycled by the garbage collector. Only when there is insufficient memory, the soft reference will be recycled by the garbage collector.
e. Weak reference: Objects with weak references have a shorter life cycle. Because when the JVM performs garbage collection, once a weak reference object is found, the weak reference will be recycled regardless of whether the current memory space is sufficient. However, since the garbage collector is a low-priority thread, it may not be able to quickly find weak reference objects
f. Virtual reference: As the name suggests, it is in name only. If an object only holds a virtual reference, then it is equivalent to Without a reference, it may be collected by the garbage collector at any time.
g. Usage scenarios:

5. What is the role of Hashcode and what is the difference between it and equal

a. It is also used to identify whether two objects are equal. There are list and There are two types of set. Among them, set does not allow repeated implementation of elements. This method does not allow repeated implementation. If you use equal to compare, if there are 1000 elements and you create a new element, you need to call equal 1000 times to go one by one. Comparing with them whether they are the same object will greatly reduce efficiency. The hashcode actually returns the storage address of the object. If there is no element at this position, the element is stored directly above it. If an element already exists at this position, the equal method is called at this time to compare with the new element. If they are the same, they will not be Save and hash to other addresses

6.The difference between String, StringBuffer and StringBuilder

a.The main performance difference between String type and StringBuffer type is actually that String is an immutable object
b.StringBuffer and StringBuilder are implemented by char[] arrays at the bottom.
c.StringBuffer is thread-safe, while StringBuilder is thread-unsafe.

7. Distinguish the meanings of Override and Overload

a.Overload, as the name suggests, is reloading. It can express the polymorphism of a class. It can have the same function name in a function but the parameter name, return value, and type cannot be the same; or it can change the parameters, type, The return value but the function name remains unchanged.
b. It means ride (rewrite). When the subclass inherits the parent class, the subclass can define a method with the same name and parameters as its parent class. When the subclass calls this function, it will be automatically called. Methods of subclasses, while parent classes are equivalent to being overridden (overridden).

8. The difference between abstract classes and interfaces

a. A class can only inherit a single class, but can implement multiple interfaces
b. Interfaces emphasize the implementation of specific functions, while abstractions Classes emphasize ownership relationships
c. All methods in abstract classes do not have to be abstract. You can choose to implement some basic methods in abstract classes. The interface requires that all methods must be abstract

9. Principles and characteristics of several ways to parse XML: DOM, SAX, PULL

a.DOM: memory consumption: first read the xml document into the memory, and then use the DOM API to Access the tree structure and get data. This is very simple to write, but it consumes a lot of memory. If the data is too large and the phone is not powerful enough, the phone may crash directly
b.SAX: high parsing efficiency, small memory usage, event-driven: more simply put, it sequentially scans the document. When the document is scanned ( The event processing function is notified when the start and end of document, the start and end of element, the end of document, etc., and the event processing function takes corresponding actions, and then continues the same scan until the end of the document.
c.SAX: Similar to SAX, it is also event-driven. We can call its next() method to get the next parsing event (that is, start document, end document, start tag, end tag). When at a certain When there is an element, you can call the getAttributte() method of XmlPullParser to get the value of the attribute, or you can call its nextText() to get the value of this node.

10. The difference between wait() and sleep()

sleep comes from the Thread class, and wait comes from the Object class
During the process of calling the sleep() method, the thread will not release the object Lock. The thread that calls the wait method will release the object lock
sleep does not give up system resources after sleeping. Wait gives up system resources and other threads can occupy the CPU
sleep(milliseconds) needs to specify a sleep time, and it will automatically wake up when the time is up

11. The difference between heap and stack in JAVA, let’s talk about Java’s memory mechanism

a. Basic data types, variables and object references are all allocated on the stack
b. Heap Memory is used to store objects and arrays created by new
c. Class variables (variables modified by static), the program allocates memory for class variables in the heap when it is loaded, and the memory address in the heap is stored in the stack
d. Instance variables: When you use the java keyword new, the system opens up a continuous space in the heap and allocates it to the variable. It is based on the scattered heap memory address and is converted into a long length through the hash algorithm. A string of numbers to represent the "physical location" of this variable in the heap, the life cycle of the instance variable - when the reference to the instance variable is lost, it will be included in the recyclable "list" by the GC (garbage collector), but it is not Release the memory in the heap immediately
e. Local variables: Declared in a method or a certain code segment (such as a for loop), memory is allocated on the stack when it is executed. Once the local variable goes out of scope , the memory is released immediately

12. Implementation principle of JAVA polymorphism

a. Abstractly speaking, polymorphism means that the same message can use multiple different methods depending on the sending object. Behavior. (Sending a message is a function call)
b. The implementation principle is dynamic binding. The method called by the program is dynamically bound during runtime. Tracing the source code can find that the JVM finds the appropriate method through automatic transformation of parameters.

13.JAVA garbage collection mechanism

a. Mark recycling method: traverse the object graph and record reachable objects in order to delete unreachable objects. Generally, single thread work is used and memory may be generated. Fragment
b. Mark - Compression Recycling Method: The initial stage is the same as the first method, with just one more step, compressing all surviving objects to one end of the memory, so that the memory fragments can be synthesized into a large piece of reusable memory. Area, improves memory utilization
c. Copy recycling method: Divide the existing memory space into two parts. When gc is running, it copies the reachable objects to the other half of the space, and then clears all objects in the space being used. This method is suitable for short-lived objects. Continuous copying of long-lived objects will lead to reduced efficiency.
d. Generational recycling: Divide the memory space into two or more domains, such as the young generation and the old generation. The characteristic of the young generation is that objects will be recycled quickly, so the use efficiency in the young generation is relatively high. algorithm. When an object still survives after several recycling, the object will be put into the memory space called the old generation, and the old generation adopts the mark-compression algorithm
e. Reference counting (the simplest and oldest method): refers to the resource The process of saving the number of references (can be an object, memory or disk space, etc.) and releasing it when the number of references becomes zero
f. Object reference traversal (the method used by most JVMs now) : Object reference traversal starts from a set of objects and recursively determines reachable objects along each link on the entire object graph. If an object is not reachable from one (at least one) of these root objects, it is collected as garbage
g. What is a garbage collector: freeing memory for objects that no longer hold references
h.How Determine whether an object needs to be collected?
i. Several garbage collection mechanisms

14. How many types of collections are there in Java and what are the differences?

a.HashTable is older and is implemented based on the Dictionary class, while HashTable is implemented based on the Map interface.
b.HashTable is thread-safe, while HashMap is thread-unsafe.
c.HashMap can make You use the null value as the key or value of a table entry. The difference between ArrayList, LinkedList, and Vector: ArrayList and Vector use arrays to store data at the bottom layer. Vector uses the synchronized method (thread safety), so its performance is better. Worse than ArrayList, LinkedList uses a doubly linked list for storage, and random access is slower.
e. The underlying source code implementation of HashMap: When we put elements into HashMap, we first recalculate the hash value based on the hashCode of the key. It is worth getting the position (i.e. subscript) of this element in the array. If there are other elements stored at this position in the array, then the elements at this position will be stored in the form of a linked list, and the newly added ones will be placed at the head of the chain. The one added first is placed at the end of the chain. If there is no element at that position in the array, the element is directly placed at that position in the array.
f.Fail-Fast mechanism: If other threads modify the map while using the iterator, ConcurrentModificationException will be thrown. This is the so-called fail-fast mechanism. This mechanism is implemented in the source code through the modCount field. modCount, as the name implies, is the number of modifications. Modifications to the HashMap content will increase this value. Then this value will be assigned to the expectedModCount of the iterator during the iterator initialization process. During the iteration process, determine whether modCount and expectedModCount are equal. If they are not equal, it means that other threads have modified Map.
g. The difference between HashMap and HashTable.

Attention, students learning Java! ! !

The above is the detailed content of Summary of some classic Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn