interview questions preparation

Interview is something that each of us has to go through, most of them more than once, here is a summary of the latest interview questions in 2016, so that everyone can do more with less when looking for a job.

 

1. Can Switch use strings as parameters?

 

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

 

2. The difference between equals and ==:

 

a.== is to judge whether two variables or instances point to the same memory space equals is to judge whether the value of the memory space pointed to by two variables or instances is the same

 

3. What are the public methods of Object?

 

a. The method equals tests whether two objects are equal 

b. The method clone performs object copying 

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

d. The methods notify, notifyall, and wait are all used to perform thread synchronization on a given object

 

4. Four kinds of references in Java, strong and weak, used scenarios

 

a. Use 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 cached image objects occupied by these objects. space, thus effectively avoiding the problem of OOM 

b. The cache of Java objects is realized through the soft accessible object retrieval method: for example, we create an Employee class, if we need to query the information of an employee each time. Even if it is just queried a few seconds ago, it takes a lot of time to rebuild an instance. We can use the combination of soft reference and HashMap. First, save the reference: use a soft reference to reference an instance of an Employee object 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 take out the reference, whether there is a soft reference to the Employee instance in the cache, and if so, get 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 collected by the garbage collector. Even if the current memory space is insufficient, the JVM will not reclaim it, but 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, so that the JVM will recycle the object at the right time 

d. Soft references: When using soft references, if the memory space is sufficient, the soft references can continue to be used without being reclaimed by the garbage collector. Only when the memory is insufficient, the soft references will be reclaimed by the garbage collector. 

e. Weak References: Objects with weak references have a shorter lifetime. Because when the JVM performs garbage collection, once a weak reference object is found, regardless of whether the current memory space is sufficient, the weak reference will be recycled. However, since the garbage collector is a low-priority thread, weakly referenced objects may not be found quickly 

f. Virtual reference: As the name implies, it is just in name only. If an object only holds a virtual reference, it is equivalent to no reference and may be reclaimed by the garbage collector at any time. 

g. Usage scenarios:

 

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

 

a. It is also used to identify whether two objects are equal. There are two types of java collections: list and set. Among them, set does not allow repeated implementation of elements. For this method that does not allow repeated implementation, if you use equal to compare, if there is 1000 When you create a new element, you need to call equal 1000 times to compare with them one by one whether they are the same object, which will greatly reduce the efficiency. The hashcode is actually the storage address of the returned object. If there is no element in this position, the element is stored directly on it. If there is an element in this position, the equal method is called at this time to compare with the new element. Saved, hashed to another address

 

6. The difference between String, StringBuffer and StringBuilder

 

The main performance difference between a.String type and StringBuffer type is that String is an immutable object 

b. The bottom layer of StringBuffer and StringBuilder is implemented by char[] array 

c.StringBuffer is thread safe while StringBuilder is thread unsafe

 

7. The meaning of Override and Overload is different

 

a.Overload, as the name implies, is reloading. It can express the polymorphism of the class. It can be that the function can have the same function name but the parameter name, return value, and type cannot be the same; or it can change the parameter, type, and return value but the function The name remains the same. 

b. It means ride (override). When a 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, the subclass will automatically be called. method, and the parent class is equivalent to being overridden (overridden).

 

8. Difference between abstract class and interface

 

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

b. The interface emphasizes the implementation of specific functions, while the abstract class emphasizes the ownership relationship 

c. All the methods in the abstract class do not have to be abstract, you can choose to implement some basic methods in the abstract class. The interface requires that all methods must be abstract

 

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

 

a.DOM: consumes memory: first read the xml document into the memory, and then use the DOM API to access the tree structure and obtain the data. This is simple to write, but 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, low memory usage, event-driven: More simply, it scans the document sequentially. When the scan reaches the start and end of the document, the start and end of the element, ) ends and so on, notify the event handler function, and the event handler will do the corresponding action, and then continue 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 in an element You can call the getAttribute() method of XmlPullParser to get the value of the attribute, and you can also 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 

In the process of calling the sleep() method, the thread will not release the object lock. And calling the wait method thread will release the object lock 

sleep does not give up system resources after sleep, wait gives up system resources and other threads can occupy the CPU 

sleep(milliseconds) needs to specify a sleep time, it will wake up automatically when the time is up

 

11. The difference between heap and stack in JAVA, talk about the memory mechanism of java

 

a. Basic data types than variables and object references are allocated on the stack 

b. Heap memory is used to store objects and arrays created by new 

c. Class variables (static modified variables), when the program is loaded, it allocates memory for class variables in the heap, and the memory address in the heap is stored in the stack 

d. Instance variables: When you use the java keyword new, the system does not necessarily open up continuous space in the heap and allocates it to the variable. It is based on the scattered heap memory addresses and is converted into a long string of numbers by a hash algorithm. Represents 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 the heap will not be released immediately medium memory 

e. Local variable: It is declared in a method or in a code segment (such as a for loop), and memory is opened up on the stack when it is executed. When the local variable is out of scope, the memory is released immediately

 

12. The realization principle of JAVA polymorphism

 

a. In abstract terms, polymorphism means that the same message can adopt multiple different behaviors depending on the sending object. (Sending a message is a function call) 

b. The principle of implementation is dynamic binding. The method called by the program is dynamically bound at runtime. If you trace the source code, you can find that the JVM finds a suitable method through the automatic transformation of parameters. 

 

 

13. JAVA garbage collection mechanism

 

a. Marking and recycling method: traverse the object graph and record reachable objects in order to delete unreachable objects, generally using single-threaded work and may generate memory fragmentation 

b. Marking-compression recovery method: The early stage is the same as the first method, but one more step is to compress all surviving objects to one end of the memory, so that the memory fragments can be synthesized into a large reusable memory area, which improves the memory utilization 

c. Copy recovery method: Divide the existing memory space into two parts. When gc runs, it copies the reachable objects to the other half of the space, and then clears all the objects in the space being used. This method is suitable for short-lived objects, and continuous replication of long-lived objects leads to inefficiency. 

d. Generational recycling: Divide the memory space into two or more domains, such as the young generation and the old generation. The young generation is characterized by the fact that objects will be recycled quickly, so a more efficient algorithm is used in the young generation. When an object is still alive after several collections, the object will be put into a memory space called old age, and the old age uses a mark-compression algorithm 

e. Reference counting (the simplest and oldest method): refers to the process of saving the number of references to resources (which can be objects, memory or disk space, etc.) and releasing them when the number of references becomes zero 

f. Object reference traversal (the method used by most jvms today): Object reference traversal starts from a set of objects and recursively determines the 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 garbage collected 

g. What is a garbage collector: freeing memory for objects that no longer hold references 

h. How to judge whether an object needs to be collected? 

i. Several garbage collection mechanisms

 

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

 

a. HashTable is relatively old and is implemented based on Dictionary class, while HashTable is implemented based on Map interface 

b.HashTable is thread-safe, HashMap is thread-unsafe 

c.HashMap allows you to use a null value as the key or value of a table entry 

d. The difference between ArrayList, LinkedList, and Vector: The bottom layer of ArrayList and Vector uses arrays to store data. Vector uses a synchronized method (thread safety), so its performance is worse than ArrayList. LinkedList uses a doubly linked list for storage and random access comparison. slow 

e. The underlying source code implementation of HashMap: When we put an element into HashMap, we first recalculate the hash value according to the hashCode of the key, and obtain the position (ie, subscript) of this element in the array according to the hash value. If other elements are already stored, then the elements in this position will be stored in the form of a linked list, the newly added elements are placed at the head of the chain, and the first added elements are placed at the end of the chain. If there is no element at this position in the array, the element is placed directly at that position in this array. 

f.Fail-Fast mechanism: In the process of using the iterator, if other threads modify the map, ConcurrentModificationException will be thrown, which is the so-called fail-fast mechanism. The implementation of this mechanism in the source code is through the modCount field. As the name implies, modCount is the number of modifications. Any modification 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. In the iterative process, it is judged whether modCount and expectedModCount are equal. If they are not equal, it means that other threads have modified the Map. 

The difference between g.HashMap and HashTable.

 

 It contains three explicit reference types (that is, three subclasses of the Reference class):

  SoftReference

  WeakReference

  PhantomReference

 

  A reference object (that is, an object of the above three reference types) encapsulates a reference to another object (called a referent ).

  Reference objects provide clean and get operations on referents, but not set operations.

  The reference object itself can be inspected and manipulated like any other normal object.

 

  The three types of references define three different levels of accessibility, ordered from strong to weak as follows:

  SoftReference > WeakReference > PhantomReference

  The weaker means the less restrictive the garbage collector is, and the easier the object is to be collected.

 

SoftReference

  SoftReference is used to implement some memory-sensitive caches (Soft references are for implementing memory-sensitive caches), as long as there is enough memory space, the object will remain uncollected.

  Conversely, when the memory space of the host process is insufficient, the object will be reclaimed by the GC.

  So SoftReference means: hold on until you can't.

WeakReference

  WeakReference can be used to implement some normalized maps ( WeakHashMap ), where keys or values ​​can be automatically recycled when they are no longer referenced.

  When you want to refer to an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, then you use weak references.

  This reference does not have any additional effect on the garbage collection decision of the object.

PlantomReference

  Like WeakReference, PlantomReference does not intervene in the life cycle of the referenced object.

  PhantomReference is used to schedule some pre-emptive cleanup actions, providing a more flexible processing method than the Java cleanup mechanism. (Phantom references are for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.)

  PlantomReference is special, its get method always returns null, so you can't get the object it refers to.

  It holds the track in the ReferenceQueue .

  It allows you to know when an object is removed from memory.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326444854&siteId=291194637