Alibaba JAVA Development interview FAQ Summary 4

Source: Internet
Author: User
Tags object serialization rehash

Alibaba JAVA Development interview FAQ Summary 4
Three main features of java

Encapsulation, inheritance, and Polymorphism

Differences between abstract classes and interfaces

Java Abstract class:
Classes modified using the abstract keyword are called abstract classes.
Abstract methods are called abstract methods.
Features:
1. Classes containing abstract methods must be declared as abstract classes (whether or not they contain other general methods) (otherwise, they cannot be compiled );
2 abstract classes can have no abstract methods, but common methods.
3. abstract classes must be inherited and abstract methods must be overwritten:
If the subclass is still an abstract class, it does not need to be overwritten; otherwise, it must be overwritten ).
Abstract classes cannot be instantiated (an object of this class cannot be constructed directly );

Abstract method:
There is no method body in the class (Abstract METHODS only need to be declared without implementing some functions );
Abstract methods must be implemented;
If a subclass does not implement the abstract method in the parent class, the subclass also becomes an abstract class;

Virtual method:
The existence of virtual functions is for polymorphism.
Java does not have the concept of virtual functions. Its common functions are equivalent to the virtual functions of c ++, and dynamic binding is the default behavior of java. If java does not want a function to have the virtual function feature, you can add the final keyword to convert it to a non-virtual function.

Java interface:
Is the declaration of a series of methods.
1. Only declarations are not implemented;
2. Different methods are implemented in different classes;

Commonalities

1. interfaces and abstract classes cannot be instantiated. They are located at the top of the inheritance tree and used for implementation and inheritance by other classes.
2. Both interfaces and abstract classes can contain abstract methods. The methods must be implemented to implement interfaces or inherit ordinary subclasses of abstract classes.

Differences

1. An interface can only contain abstract methods and default methods, and cannot provide method implementation for common methods. abstract classes can completely contain common methods.
2. Static methods cannot be defined in Interfaces. Static methods can be defined in abstract classes.
3. The interface can only define static constants, but cannot define common member variables. In an abstract class, both common member variables and static constants can be defined.
4. The interface does not contain constructors. The abstract class can contain constructors. The constructors in the abstract class are not used to create objects, instead, let its subclass call these constructor to complete initialization of the abstract class.
5. The interface cannot contain initialization blocks, but the abstract class can completely contain the initialization blocks.
6. A class can have at most one direct parent class, including an abstract class. However, a class can directly implement multiple interfaces. By implementing multiple interfaces, you can make up for the shortcomings of Java single inheritance.

Stack memory and heap memory, reference and value transfer stack memory, heap memory

Some of the basic types of variables defined in the function and the referenced variables of the object are allocated in the function stack memory.When a variable is defined in a code block, java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.
Heap memory is used to store objects and arrays created by new.The memory allocated in the heap is managed by the Java Virtual Machine automatic garbage collector. When the array and object do not reference the variable to point to it, it becomes garbage and cannot be used again, but still occupies the memory, and is released by the garbage collector at an uncertain time. This is also the main reason why java accounts for memory usage.

Reference and value transfer

Value Transfer: When a method is called, the actual parameter passes its value to the corresponding form parameter. The change of the form parameter value during method execution does not affect the actual value of the parameter.

Reference transfer: Also known as transfer address. When a method is called, the reference (address rather than the value of the parameter) of the actual parameter is passed to the corresponding formal parameter in the method. During method execution, the operation on the formal parameters is actually the operation on the actual parameters. Changing the value of the formal parameter during the execution of the method will affect the actual value of the parameter.

Singleton mode and Benefits

The constructor is private and uses a static method to obtain the object instance.

Features:
1) A singleton class can only have one instance.
2) The Singleton class must create its own unique instance.
3) The Singleton class must provide this instance to all other objects.
Main advantages:
1) controlled access to a unique instance is provided.
2) because only one object exists in the system memory, system resources can be saved. The single-instance mode of some objects that require frequent creation and destruction can undoubtedly improve the system performance.
3) Allow variable target instances.

Main disadvantages:
1) because there is no abstraction layer in the single-profit mode, it is very difficult to expand the single-instance class.
2) the responsibilities of the singleton class are too heavy, which violates the "single Responsibility Principle" to a certain extent ".
3) Misuse of Singleton may cause some negative problems. For example, designing database connection pool objects as Singleton classes to save resources may lead to excessive programs sharing connection pool objects and connection pool overflow; if the instantiated object is not used for a long time, the system will regard it as garbage and be recycled, which will lead to the loss of the object state.

Reload and rewrite

Overload: Overloading
(1) Java method overloading means that multiple methods can be created in the class. They have the same name, but have different parameters and different definitions. When calling a method, the number and type of different parameters passed to them are used to determine which method to use. This is polymorphism.
(2) During overload, the method name must be the same, but the parameter type and number are different. The return value type can be the same or different. Return types cannot be used as the criteria for distinguishing heavy-duty functions.

Rewrite: Overriding
Note: When you want to Override the parent class method, use the @ Override label to remind the compiler to check whether the code is overwritten, rather than reload the original method.
(1) The polymorphism between the parent class and the Child class, and the function of the parent class is redefined. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). In Java, subclasses can inherit the methods in the parent class without re-writing the same method. But sometimes the subclass does not want to inherit the parent class from the original method, but wants to make some modifications, which requires method rewriting. Method override is also called method override.
(2) If the method in the subclass has the same method name, return type, and parameter table as a method in the parent class, the new method overwrites the original method. If you need the original method of the parent class, you can use the super keyword, which references the parent class of the current class.
(3) The access modification permission of subclass functions cannot be less than that of the parent class.

Conversion and construction sequence between child classes and parent classes

Conversions between child classes and parent classes:
Subclass can be automatically converted to the parent class type.
When creating a subclass object:
① The constructor of the subclass is called first.
② The constructor of the parent class is called.
③ Execute the constructor of the parent class
④ Executed the constructor of the subclass.

Final, finally, finalize

Final is used to declare attributes. Methods and classes indicate that attributes are unchangeable, methods cannot be overwritten, and classes cannot be inherited.
Finally is a part of the structure of the exception handling statement, indicating that it is always executed.
Finalize is a method of the Object class. This method is called when the garbage collector is executed. It can overwrite this method to collect other resources during garbage collection, such as closing files.

Differences between Synchronized and volatile

Volatile only applies to variables that can be shared among multiple threads. If a field is declared as volatile, the java thread memory model ensures that all threads see the same value for this variable. If the Volatile variable modifier is used properly, it costs less than synchronized because it does not cause thread context switching and scheduling.
Synchronized acquires and releases the monitor-if two threads use the same object lock, the monitor can force the code block to be executed by only one thread at a time-this is a well-known fact. However, synchronized also synchronizes the memory: in fact, synchronized synchronizes the memory of the entire thread in the "master" memory area.
Therefore, volatile only synchronizes the value of a variable between the thread memory and the "master" memory, while synchronized synchronizes the value of all variables by locking and unlocking a monitor. Obviously, synchronized consumes more resources than volatile.

1) volatile essentially tells the jvm that the value of the current variable in the register (Working Memory) is uncertain and needs to be read from the main memory without mutex lock. synchronized locks the current variable, only the current thread can access this variable, and other threads are blocked.
2) volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level.
3) volatile only synchronizes the value of a variable between the thread memory and the "master" memory, while synchronized synchronizes the value of all variables by locking and unlocking a monitor; obviously, synchronized consumes more resources than volatile.
4) volatile will not cause thread blocking; synchronized may cause thread blocking.
5) variables marked by volatile are not optimized by the compiler; variables marked by synchronized can be optimized by the compiler.

Set

Collection: represents a group of objects, each of which is its child element.
Set: a Collection that does not contain duplicate elements.
List: an ordered Collection that can contain duplicate elements.
Map: You can Map a key to a value object. The key cannot be repeated.

The reason why the set class does not implement the Cloneable and Serializable Interfaces

The Collection interface specifies a group of objects, which are their elements. How to maintain these elements is determined by the specific implementation of Collection. For example, some Collection implementations such as List allow repeated elements, while others such as Set do not. Many collections have a public clone method. However, it is meaningless to put it in all implementations of the set. This is because Collection is an abstract representation. Implementation is important.
When dealing with specific implementations, the semantics and meaning of cloning or serialization play a role. Therefore, the specific implementation should determine how to clone or serialize it, or whether it can be cloned or serialized.
Authorization of cloning and serialization in All implementations leads to less flexibility and more restrictions. The specific implementation should determine whether it can be cloned or serialized.

Where is the importance of hashCode () and equals () Methods reflected?

HashMap uses the hashCode () and equals () Methods of the Key object to determine the index of the key-value pair. These methods are also used when we try to get values from HashMap. If these methods are not correctly implemented, two different keys may generate the same hashCode () and equals () outputs, and HashMap will think they are the same, they are then overwritten, rather than stored in different places. Similarly, all collection classes that do not allow repeated data storage use hashCode () and equals () to find duplicates, so it is very important to implement them correctly.
The implementation of equals () and hashCode () should follow the following rules:
(1) If o1.equals (o2), o1.hashCode () = o2.hashCode () is always true.
(2) If o1.hashCode () = o2.hashCode (), it does not mean that o1.equals (o2) will be true.
HashMap in Java uses the hashCode () and equals () methods to determine the index of the key-value pair. These two methods are also used when the value is obtained based on the key. If the two methods are not correctly implemented, the two different keys may have the same hash value, so they may be considered equal by the set. The two methods are also used to find duplicate elements. Therefore, the implementation of these two methods is crucial to the accuracy and correctness of HashMap.

Differences between HashMap and HashTabel

HashMap and Hashtable both implement the Map interface, so many features are very similar. However, they have the following differences:
1) HashMap allows the key and value to be null, while Hashtable does not allow the key or value to be null.
2) Hashtable is synchronous, but HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is more suitable for multi-threaded environments.
3) HashMap provides a set of key that can be supplied with iterations. Therefore, HashMap fails quickly. On the other hand, Hashtable provides Enumeration ).
Hashtable is generally considered as a legacy class.

Comparable and Comparator Interfaces

Both Comparable and Comparator are used to sort the set, but Comparable is the sorting implemented by the methods defined inside the set, and Comparator is the sorting implemented outside the set. Therefore, if you want to sort the set, you need to define the Comparator interface method compare () outside the set or the compareTo () method that implements the Comparable interface in the set ().
Comparable supports self-comparison, while the latter supports external comparison;
Comparable is an interface that the object itself supports for self-comparison (for example, the String and Integer operations can be performed by itself)
Comparator is a dedicated Comparator. When this object does not support auto-comparison or the auto-comparison function cannot meet your requirements, you can write a Comparator to compare the sizes of two objects.
That is to say, when you need to compare an array or set of a custom class, you can implement the Comparable interface, when you need to compare an existing array or set of classes, you must implement the Comparator interface. In addition, these two interfaces support generics, so we should define the comparison type while implementing the interfaces.

What is the working principle of HashMap in Java?

In Java, HashMap stores elements in the form of key-value pairs. HashMap requires a hash function that uses the hashCode () and equals () Methods to add and retrieve elements to/from a set. When the put () method is called, HashMap calculates the hash value of the key and stores the key-value pairs on the appropriate indexes in the set. If the key already exists, the value is updated to the new value. Some important features of HashMap are its capacity, load factor, and threshold resizing ).
1) HashMap has an internal class called Entry, which is used to store key-value pairs.
2) The above Entry object is stored in an Entry array called table.
3) The table index is logically called a bucket, which stores the first element of the linked list.
4) The hashcode () method of the key is used to locate the bucket where the Entry object is located.
5) If two keys have the same hash value, they will be placed in the same bucket of the table array.
6) The equals () method of the key is used to ensure the uniqueness of the key.
7) The equals () and hashcode () Methods of the value object are useless at all.
Key Content
Put: The index of the key in the Entry array is determined based on the hash value calculated by the hashcode () method of the key.
Get: Use hashcode to find an element Entry in the array.

Implementation of Hashcode

The general protocol of hashCode is:
During Java application execution, when calling the hashCode method multiple times on the same object, the same integer must be returned consistently, provided that the information used in the equals comparison on the object is not modified. This integer does not need to be consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals (Object) method, the hashCode method must be called on each Object of the two objects to generate the same integer result.
When the equals method is overwritten, it is usually necessary to override the hashCode method to maintain the conventional protocol of the hashCode method. This Protocol declares that equal objects must have equal hash codes.

Differences between String, StringBffer, and StringBuilder

1) mutable and immutable
In the String class, use a character array to save the string, as shown in the following figure. Because there is a "final" modifier, we can know that the String object is immutable.
Private final char value [];
Both StringBuilder and StringBuffer are inherited from the AbstractStringBuilder class. In AbstractStringBuilder, character arrays are used to save strings. The following shows that the two objects are variable.
Char [] value;
2) is multithreading secure?
The objects in the String are unchangeable and can be understood as constants. Obviously, the thread is secure.
AbstractStringBuilder is a common parent class of StringBuilder and StringBuffer. It defines some basic string operations, such as expandCapacity, append, insert, indexOf and other public methods.
StringBuffer adds a Synchronous lock to the method or a Synchronous lock to the called method, so it is thread-safe.

Differences between HashMap, HashSet, and HashTable

Differences between HashSet and HashMap
1) HashSet is an implementation class of set, hashMap is an implementation class of Map, and hashMap is a substitute for hashTable.
2) HashSet uses objects as elements, while HashMap uses a group of objects (key-value) as elements, and HashSet rejects repeated objects. hashMap can be viewed as three views: key Set, value Collection, and Entry Set. HashSet is actually a view of HashMap.

HashSet is implemented using Hashmap internally. Unlike Hashmap, it does not need two values: Key and Value.
Inserting Objects into a hashset is actually just done internally.
Public boolean add (Object o ){
Return map. put (o, PRESENT) = null;
}

Differences between hastTable and hashMap:
1) Hashtable is based on the obsolete Dictionary class, And HashMap is an implementation of the Map interface introduced by Java 1.2.
2) This is the most important difference: the methods in Hashtable are synchronous, while the HashMap method (by default) is not synchronous. That is to say, Hashtable can be safely used in multi-threaded applications without special operations. For HashMap, additional synchronization mechanisms are required.
3) Only HashMap allows you to use a null value as the key or value of a table entry. Only one record in HashMap can be an empty key, but any number of entries can be empty values. That is to say, if no search key is found in the table, or if a search key is found but it is an empty value, get () returns null. If necessary, use the containKey () method to differentiate the two cases.

Thread-safe HashMap -- java. util. concurrent. ConcurrentHashMap
ConcurrentHashMap adds the Segment layer. The principle of each Segment is equivalent to a Hashtable, and ConcurrentHashMap is an array of Segment.
To insert or read data into ConcurrentHashMap, you must first map the corresponding Key to the corresponding Segment, so you do not need to lock the entire class, you only need to lock a single Segment operation. Theoretically, if there are n segments, a maximum of n threads can be concurrently accessed, which greatly improves the efficiency of concurrent access. In addition, the rehash () operation is performed on a single Segment, so the rehash cost caused by the increase in the data volume in the Map is also relatively low.

Differences between ArrayList and LingkedList

1) ArrayList: List implemented by arrays at the underlying layer
Features: High query efficiency, low addition/deletion efficiency, low lightweight thread security
2) Sort List: List implemented by two-way circular linked List at the underlying layer
Features: Low query efficiency and high addition and deletion Efficiency

Garbage Collection Mechanism

Java's garbage collection mechanism is the capability provided by the Java Virtual Machine. It is used to dynamically reclaim the memory space occupied by non-referenced objects in an irregular manner during idle time.
Note that garbage collection is the memory space occupied by objects without any reference, rather than the object itself.
Two common methods are reference count and Object Reference traversal.
Reference count:In this method, each object (not referenced) in the heap has a reference count. When an object is created and assigned to a variable, the variable count is set to 1. When any other variable is assigned a reference to this object, the count is incremented by 1 (a = B, then the object referenced by B + 1 ), however, when a reference of an object exceeds the lifecycle or is set as a new value, the reference count of the object is reduced by 1. Any object with 0 reference count can be collected as garbage. When an object is garbage collected, the number of objects it references is reduced by 1.
Object Reference traversal:Starting from a group of objects, recursively determine the reachable objects along each link in the entire object graph. If an object cannot be reached from one (at least one) of these root objects, it is collected as garbage.

Serialization and deserialization

Serialization is the process of converting the object state to a format that can be maintained or transmitted. In contrast to serialization, deserialization converts a stream into an object. These two processes can be combined to easily store and transmit data.
Serialization Purpose
1. Make the custom object persistent in a certain storage form;
2. transfer an object from one place to another.
3. Make the program more maintainability
When two processes perform remote communication, they can send different types of data to each other. Regardless of the type of data, it is transmitted on the network in the form of binary sequence. The sender needs to convert the object to a byte sequence before it can be transmitted over the network. The receiver needs to restore the byte sequence to an object.
The process of converting an object to a byte sequence is called object serialization.
The process of restoring a byte sequence to an object is called object deserialization.
The purpose of serialization is to pass formatted data across processes.

What mechanisms does Java's flexibility reflect?

Reflection mechanism

Sleep and wait

1. The sleep () method belongs to the Thread class. The wait () method belongs to the Object class.
2. When the sleep () method is called, the thread does not release the object lock. When the wait () method is called, the thread will discard the object lock.
The sleep () method causes the program to pause the execution at the specified time, giving the cpu to other threads, but the monitoring status remains unchanged. When the specified time reaches, the program will automatically resume running. When the wait () method is called, the thread will discard the object lock and enter the waiting lock pool for this object. Only notify () is called for this object () this thread enters the object lock pool for preparation.

IO and NIO

1. IO is stream-oriented, while NIO is buffer-oriented.
Java IO stream orientation means that one or more bytes are read from the stream each time until all bytes are read, and they are not cached anywhere. In addition, it cannot move data in the stream before and after. If you need to move the data read from the stream before and after, you must first cache it to a buffer zone. The buffer-oriented method of Java NIO is slightly different. The data is read to a buffer that will be processed later. When necessary, it can be moved before and after the buffer. This increases the flexibility in the processing process. However, you also need to check whether the buffer contains all the data you need to process. In addition, make sure that when more data is read into the buffer, do not overwrite the unprocessed data in the buffer.
2. Various Java IO streams are blocked, and Java NIO non-blocking mode.
Various Java IO streams are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read or completely written. This thread can no longer do anything during this period. The non-blocking mode of Java NIO enables a thread to send requests from a channel to read data, but it can only obtain currently available data. If no data is available, you won't get anything. Instead of keeping the thread congested, the thread can continue to do other things until the data becomes readable. This is also true for non-blocking writes. A thread requests to write some data to a channel, but does not need to wait for it to write completely. This thread can also do other things. Threads usually use the idle time of non-blocking IO to execute IO operations on other channels, so a separate thread can now manage multiple input and output channels ).
3. the Java NIO selector allows a single thread to monitor multiple input channels. You can register multiple channels and use one selector, and then use a separate thread to "select" the channel: there are input that can be processed in these channels, or select the channel to be written. This selection mechanism makes it easy for a single thread to manage multiple channels. Java IO has no selector.

Scoket

For a fully functional Socket, it must contain the following basic structure. The working process includes the following four basic steps:
(1) create a Socket;
(2) Open the input/output stream connected to the Socket;
(3) perform read/write operations on the Socket according to certain protocols;
(4) Disable Socket.
 

Deep cloning and shortest cloning

Shortest copies only the objects to be considered, instead of the objects referenced by it.
Deep replication copies all the objects referenced by the objects to be copied.

In java, only single inheritance is required. To assign a class a new feature, an interface is usually used for implementation.
In c ++, multiple inheritance is supported. A subclass can have multiple parent class interfaces and functions at the same time.

UDP and TCP

Both UDP and TCP belong to the transport layer protocol.
TCP protocol: connection-oriented, reliable, and byte-based stream
UDP protocol: connectionless, unreliable, and packet-based
1. the TCP protocol includes a special Transfer Guarantee Mechanism. When the data receiver receives the message from the sender, it will automatically send a confirmation message to the sender; the sender continues to transmit other information only after receiving the confirmation message. Otherwise, the sender waits until the confirmation message is received.
Unlike TCP, UDP does not provide a data transmission guarantee mechanism. If a data packet is lost during transmission from the sender to the receiver, the Protocol itself cannot detect or prompt. Therefore, UDP is often called an unreliable transmission protocol.
2. Compared with the TCP protocol, another difference of UDP protocol is how to receive burst data packets. Unlike TCP, UDP does not guarantee the order in which data is sent and received.

Red/black tree

It is a self-balancing binary search tree, and the red/black tree is an interesting balanced search tree. computing is required each time a binary tree is inserted to ensure the balance of the binary tree; if there is 2 n data, you only need to query it N times.
We add the following requirements to any valid red/black tree:
1. the node is red or black.
2. The root is black.
3. All leaves (external nodes) are black.
4. The two subnodes of each Red node are black. (There cannot be two consecutive red nodes in all paths from each leaf to the root)
5. All paths from each leaf to the root contain the same number of black nodes.
These constraints force the key attribute of the red/black tree: the longest possible path from the root to the leaf is no more than twice the shortest possible path. The result is that the tree is roughly balanced.

Reflection

The reflection mechanism means that the program can obtain its own information at runtime.
The reflection mechanism is used to add and query database data.
Basic principle: when saving data, extract all the attribute values of the objects to be saved and splice SQL statements. During the query, all the queried data is packaged into a java object.
1) Each table in the database corresponds to a pojo class, and each field in the table corresponds to an attribute in the pojo class. In addition, the pojo class name is the same as the table name, the attribute name and field name are the same, and the case sensitivity is irrelevant, because the database is generally case insensitive.
2) add standard set and get methods for each attribute in the pojo class.

Three handshakes and four waves

Three-way handshake: first, the Client sends a connection request message. The Server segment replies to the ACK packet after accepting the connection and allocates resources for the connection. After the Client receives the ACK packet, it also sends the ACK packet to the Server segment and allocates resources so that the TCP connection is established.

Four handshakes:
Because the TCP connection is full-duplex, each direction must be closed separately. This principle is that when one party completes its data sending task, it can send a FIN to terminate the connection in this direction. Receiving a FIN only means that there is no data flow between the two parties. a tcp connection can still send data after receiving a FIN. First, the party that closes the service will take the initiative to close the service, and the other party will passively close the service.
(1) The TCP client sends a FIN to disable data transmission from the client to the server.
(2) When the server receives the FIN, it sends back an ACK and confirms that the serial number is added to 1. Like SYN, a FIN occupies a sequence number.
(3) The server closes the client connection and sends a FIN to the client.
(4) the client sends back the ACK message for confirmation and sets the serial number to receive the serial number plus 1.

Equals () and =

1. The difference between equals and = in java is that the value type is stored in the memory stack (stack for short), and the reference type variable is only the address that stores the reference type variable in the stack, it is stored in the heap.
2. = The operation compares whether the values of the two variables are equal. For a referenced variable, it indicates whether the addresses of the two variables are the same in the heap, that is, whether the stack content is the same.
3. Whether the two variables represented by the equals operation reference the same object, that is, whether the content in the heap is the same.
4. = compares the addresses of two objects, while equals compares the content of two objects. Obviously, when equals is true, = is not necessarily set to true.

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.