Three major features of Java
Encapsulation, inheritance, polymorphism
The difference between an abstract class and an interface
Java Abstract class:
Classes that use the keyword abstract adornment are called abstract classes.
The method of modifying with abstract is called abstract method.
Characteristics:
1 classes containing abstract methods must be declared as abstract classes (whether or not they contain other general methods) (otherwise compiled);
2 Abstract classes can have no abstract methods and can have common methods.
3 abstract classes must be inherited, and abstract methods must be rewritten:
If the subclass is still an abstract class, you do not need to rewrite it, otherwise you will have to override (override).
An abstract class cannot be instantiated (an object of that class cannot be constructed directly);
Abstract method:
There is no method body in the class (abstract methods only need to be declared, without implementing certain functions);
Abstract methods in abstract classes must be implemented;
If a subclass does not implement an abstract method in the parent class, then the subclass becomes an abstract class;
Virtual method:
The existence of virtual functions is for polymorphism.
There is no concept of virtual functions in Java. Its normal function is equivalent to the virtual function of C + +, and dynamic binding is the default behavior of Java. If you do not want a function in Java to have a virtual function attribute, you can add the final keyword to a non-virtual function.
Java interface:
is a declaration of a series of methods.
1 only declarations are not fulfilled;
2 different methods are implemented in different classes;
Common
1. Interfaces and abstract classes cannot be instantiated, they are located at the top of the inheritance tree and are implemented and inherited by other classes.
2. Interfaces and abstract classes can contain abstract methods, and ordinary subclasses that implement interfaces or inherit abstract classes must implement these methods.
Different points
1, the interface can only contain abstract methods and default methods, can not provide methods for ordinary methods implementation; Abstract classes can completely contain common methods.
2. Static methods cannot be defined in interfaces, and static methods can be defined in abstract classes.
3, the interface can only define static constants, can not define ordinary member variables; Abstract classes can define either ordinary member variables or static constants.
4, the interface does not contain a constructor, the abstract class can contain constructors, the constructor in the abstract class is not used to create objects, but rather let its subclasses call these constructors to complete the initialization of the abstract class.
5. The interface cannot contain initialization blocks, but abstract classes can completely contain initialization blocks.
6. A class can have at most one direct parent class, including abstract classes, but a class may implement multiple interfaces directly, and by implementing multiple interfaces can compensate for the lack of Java single inheritance.
Stack memory and heap memory, reference and value pass stack memory, heap memory
some basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function. when a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another.
heap memory is used to hold objects and arrays created by new. the memory allocated in the heap is managed by the Java Virtual Machine automatic garbage collector. In arrays and objects, when no reference variable points to it, it becomes garbage, can no longer be used, but still occupies memory and is freed by the garbage collector at a later indeterminate time. This is also the main reason why the Java comparison occupies memory.
Reference, value passing
Value passing: When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the change of the formal parameter value in the method execution does not affect the value of the actual parameter.
Reference delivery: Also known as a pass-through address. When a method is called, the reference to the actual parameter (the address, not the value of the parameter) is passed to the corresponding formal parameter in the method, and in the execution of the method, the operation of the formal parameter is actually the operation of the actual parameter, and the change of the parameter value in the execution of the method will affect the value of the actual parameter.
Single-case patterns and benefits
The constructor is privatized, and a static method is used to obtain the object instance.
Characteristics:
1) A singleton class can have only one instance.
2) A singleton class must create its own unique instance.
3) The Singleton class must provide this instance to all other objects.
Key Benefits:
1) provides controlled access to a unique instance.
2) due to the existence of only one object in system memory, it can save system resources, and for some object singleton patterns that need to be created and destroyed frequently can improve the performance of the system.
3) allow a variable number of instances.
Main disadvantages:
1) Since there is no abstraction layer in the simple interest mode, the expansion of the Singleton class is very difficult.
2) The responsibilities of a single class are too heavy to a certain extent contrary to the "single duty Principle".
3) Abuse of the singleton will bring some negative problems, such as to save resources to the database connection pool object design as a singleton class, may result in the Sharing connection pool object is too many programs and a connection pool overflow, if the instantiated object is not exploited for a long time, the system will be considered garbage and recycled, which will result in the loss of object state.
Overloading and overriding
Reload: Overloading
(1) Java's method overloading is the ability to create multiple methods in a class that have the same name but have different parameters and different definitions. The method is called polymorphism by the number of different arguments passed to them and by the type of parameter to determine which method to use.
(2) When overloading, the method name is the same, but the parameter type and number are different, the return value type can be the same or different. The return type cannot be used as a distinguishing criterion for overloaded functions.
Rewrite: overriding
Note: When you want to override the parent class method, use the @override tag to remind the compiler to check if the code is overridden, rather than overloading the original method.
(1) The polymorphism between the parent class and the child class, redefining the function of the parent class. If you define a method in a subclass that has the same name and arguments as its parent class, we say that the method is overridden (overriding). In Java, subclasses can inherit methods from the parent class without having to rewrite the same method. But sometimes subclasses do not want to inherit the parent class's methods, but want to make some changes, which requires a method of rewriting. Method overrides are also called method overrides.
(2) The method in the Kawai class has the same method name, return type, and parameter table as a method in the parent class, and the new method overwrites the original method. If you need a method from the parent class, you can use the Super keyword, which references the parent class of the current class.
(3) The access adornment permission of a subclass function cannot be less than the parent class.
The transformation and construction order between subclasses, parent classes
Transitions between subclasses and parent classes:
Subclasses can be automatically converted to the parent class type.
When creating child class objects:
① called the constructor of the subclass first
② called the constructor of the parent class
③ executes the constructor of the parent class
④ executes the constructor of the subclass
Final, finally, finalize
Final is used to declare properties, methods, and classes, respectively, that the property is immutable, that the method is not overridden, and that the class is not inheritable.
Finally is part of the exception-handling statement structure, which indicates that it is always executed.
Finalize is a method of the object class that, when executed by the garbage collector, calls this method of the reclaimed object, and can override this method to provide garbage collection of other resource recycles, such as closing the file, etc.
The difference between synchronized and volatile
Volatile is used only as a variable that can be shared among multiple threads. If a field is declared as a Volatile,java thread, the memory model ensures that all threads see that the value of this variable is consistent. The volatile variable modifier, if used appropriately, is less expensive to use and execute than synchronized because it does not cause thread context switching and scheduling.
Synchronized get and release 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-a well-known fact. However, synchronized also synchronizes memory: in fact, synchronized synchronizes the entire thread's memory in the "primary" memory area.
so volatile is simply synchronizing the value of a variable between the thread memory and the "primary" memory, while the synchronized synchronizes the values of all variables by locking and unlocking a monitor. Obviously synchronized consumes more resources than volatile.
1) volatile nature is telling the JVM that the value of the current variable in the register (working memory) is indeterminate, needs to be read from main memory, there is no mutex, synchronized is locking the current variable, and other threads are blocked only if the variable is accessible to the thread.
2) volatile can only be used at variable levels; synchronized can be used in variables, methods, and class-level
3) volatile is simply synchronizing the value of a variable between the thread memory and the "primary" memory, while synchronized synchronizes the values of all variables by locking and unlocking a monitor, apparently synchronized consumes more resources than volatile.
4) volatile does not cause thread blocking, and synchronized can cause thread blocking.
5) Volatile tagged variables are not optimized by the compiler; Synchronized tagged variables can be optimized by the compiler.
Collection
Collection: Represents a set of objects, each of which is its child element.
Set: A collection that does not contain duplicate elements.
List: A sequence of collection, and can contain repeating elements.
Map: You can map a key (key) to an object with a value, and the key cannot be duplicated.
The collection class does not implement the cloneable and serializable interfaces
The collection interface specifies a set of objects, which are the elements of the object. How to maintain these elements is determined by the specific implementation of collection. For example, some collection implementations such as list allow repeating elements, while others such as set are not allowed. Many collection implementations have a public clone method. However, it is meaningless to put it in all implementations of the collection. This is because collection is an abstract representation. It is important to realize.
When dealing with specific implementations, the semantics and meaning of cloning or serialization only work. Therefore, a specific implementation should decide how to clone or serialize it, or whether it can be cloned or serialized.
Authorizing cloning and serialization in all implementations ultimately leads to less flexibility and more restrictions. A particular implementation should determine whether it can be cloned and serialized.
Where does the importance of the hashcode () and Equals () methods manifest?
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 the values from the HashMap. If these methods are not implemented correctly, in this case, two different keys may produce the same hashcode () and Equals () outputs, HashMap will think they are the same, then overwrite them instead of storing them in different places. Similarly, all collection classes that do not allow the storage of duplicate data use Hashcode () and Equals () to find duplicates, so it is important to implement them correctly.
Implementations of Equals () and hashcode () should follow these rules:
(1) if O1.equals (O2), then o1.hashcode () = = O2.hashcode () is always true.
(2) if o1.hashcode () = = O2.hashcode (), does not mean that o1.equals (O2) will be true.
HashMap in Java uses the hashcode () and Equals () methods to determine the index of key-value pairs, which are used when the values are obtained by key. If these two methods are not implemented correctly, two different keys may have the same hash value, and therefore may be considered equal by the collection. Moreover, these two methods are also used to discover duplicate elements. So the realization of these two methods is very important to the accuracy and correctness of hashmap.
The difference between HashMap and Hashtabel
HashMap and Hashtable both implement the map interface, so many features are very similar. However, they have the following different points:
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, while HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multithreaded environments.
3) HashMap provides a collection of keys that are available for application iterations, so HashMap is a quick failure. On the other hand, Hashtable provides an enumeration of keys (enumeration).
Hashtable is generally considered to be a legacy class.
Comparable and comparator interfaces
Comparable and comparator are used to implement sorting in the collection, except that comparable is the sort of method implementation defined within the collection, comparator is the sort implemented outside the collection, so, if you want to implement sorting, It is necessary to define the method of the comparator interface outside the collection compare () or the method CompareTo () that implements the comparable interface within the collection.
Comparable is to support self-comparison, while the latter is to support external comparisons;
Comparable is an interface that the object itself has implemented to support self-comparison (such as String, integer itself can do the comparison size operation)
While comparator is a dedicated comparator, you can write a comparator to compare the size of two objects when the object does not support self-comparison or the self-comparison function does not meet your requirements.
This means that when you need to compare an array or set of a custom class, you can implement the comparable interface, and when you need to compare an array or set of an existing class, you must implement the comparator interface. In addition, these two interfaces support generics, so we should define the comparison type while implementing the interface.
How does hashmap in Java work?
HashMap in Java is a key-value pair (Key-value) that stores elements. HashMap requires a hash function that uses the hashcode () and Equals () methods to add and retrieve elements to the collection/collection. When the put () method is called, HashMap calculates the hash value of the key and stores the key-value pair on the appropriate index in the collection. If the key already exists, value is updated to the new value. Some of the important features of HashMap are its capacity (capacity), load factor (payload factor) and expansion limit (threshold resizing).
1) HashMap has an inner class called entry, which is used to store key-value pairs.
2) The entry object above is stored in a entry array called table.
3) The Index of table is logically called a bucket, which stores the first element of the list.
4) Key's Hashcode () method is used to find the bucket where the entry object resides.
5) If two keys have the same hash value, they will be placed in the same bucket in the table array.
6) The Equals () method of key is used to ensure uniqueness of key.
7) the Equals () and Hashcode () methods of the value object have no use at all.
Key Content
Put: Determines the index of key in the entry array based on the hash value computed by the Hashcode () method of key.
Get: Finds an element in an array by hashcode entry
The realization of Hashcode
The general agreement of Hashcode is:
During Java application execution, when the Hashcode method is called 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 has not been modified. The 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, calling the Hashcode method on each object in two objects must produce the same integer result.
When the Equals method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code.
The difference between String, Stringbffer, StringBuilder
1) variable and non-variable
The string class uses a character array to hold strings, as follows, because there is a "final" modifier, so you know that the string object is immutable.
Private final char value[];
Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in the Abstractstringbuilder, they are also used to hold strings in a character array, as follows, that both of these objects are mutable.
Char[] value;
2) Whether multithreaded security
The objects in string are immutable and can be understood as constants, apparently thread-safe.
Abstractstringbuilder is the common parent of StringBuilder and StringBuffer, and defines some basic operations for strings, such as expandcapacity, append, insert, indexof, and other public methods.
StringBuffer a synchronous lock on a method or a synchronous lock on a calling method, it is thread-safe
The difference between HashMap, HashSet and Hashtable
The difference between HashSet and HashMap
1) HashSet is an implementation class for set, HashMap is an implementation class for map, and HashMap is a substitute for Hashtable.
2) HashSet an object as an element, and hashmap a set of objects (Key-value) as elements, And HashSet refuses to accept duplicate objects. HashMap can be viewed as three views: the set of the collection,entry of the set,value of a key. HashSet is actually a view of HashMap.
HashSet internal is implemented using HASHMAP, unlike HashMap, which does not require a key and value two values.
Inserting objects into the hashset is actually just an internal thing.
Public boolean Add (Object o) {
Return Map.put (o, PRESENT) ==null;
}
The difference between hasttable and HashMap:
1) Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2.
2) This difference is the most important point: The method in Hashtable is synchronous, and the HashMap method (by default) is not synchronous. That is, in a multithreaded application, it is safe to use Hashtable without specialized operations, and for HashMap, an additional synchronization mechanism is required.
3) Only HashMap can let you use NULL as the key or value of an entry for a table. Only one record in HashMap can be an empty key, but any number of entries can be empty value. This means that if a search key is not found in the table, or if a search key is found, but it is an empty value, then get () returns NULL. If necessary, use the Containkey () method to differentiate between the two cases.
Thread-Safe Hashmap--java.util.concurrent.concurrenthashmap
Concurrenthashmap adds Segment layers, each Segment principle equivalent to a Hashtable, concurrenthashmap as an array of Segment.
Inserting data into the Concurrenthashmap or reading the data, first of all to the corresponding Key mapping to the corresponding Segment, so do not lock the entire class, as long as the single Segment operation to lock the operation is possible. In theory, if there are N Segment, the concurrent access of n threads can be supported at the same time, which greatly improves the efficiency of concurrent access. In addition, the rehash () operation is also performed on a single Segment, so the cost of rehash due to the increased amount of data in the MAP is also relatively low.
Attach a blog: HashMap implementation method and principle of thread safety
http://liqianglv2005.iteye.com/blog/2025016
The difference between ArrayList and Lingkedlist
1) ArrayList: List of the underlying array implementation
Features: High efficiency of query, and deletion efficiency low lightweight thread insecure
2) LinkedList: List of the underlying with a bidirectional circular list
Features: Low query efficiency, high efficiency and deletion
Garbage collection mechanism
Java's garbage collection mechanism is the ability of a Java virtual machine to dynamically reclaim the memory space occupied by objects without any references in an idle time, in an unscheduled manner.
It is important to note that garbage collection reclaims the memory space occupied by objects without any reference, not the object itself.
Two common methods are reference counts and object reference traversal.
reference count: in this method, each object (not a reference) in the heap has a reference count. When an object is created, and the object is 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 added 1 (a = B, then B refers to object +1), but the reference count of the object is reduced by 1 when a reference to an object exceeds the life cycle or is set to a new value. Any object with a reference count of 0 can be garbage collected. When an object is garbage collected, it refers to any object count minus 1.
Object reference traversal: starts with a set of objects, recursively determines the reachable (reachable) object, along each link on the entire object graph. If an object cannot arrive from one (at least one) of these root objects, it is garbage collected.
Serialization and deserialization
Serialization is the process of converting an object's state into a format that can be persisted or transmitted. Relative to serialization is deserialization, which transforms a stream into an object. Together, these two processes make it easy to store and transfer data.
Purpose of serialization
1. Persist the custom object in some form of storage;
2. Transfer objects from one place to another.
3, make the program more maintenance
When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the object.
The process of converting an object to a sequence of bytes is called serialization of an object.
The process of reverting a sequence of bytes to an object is called deserialization of the object.
More directly, the purpose of serialization is to pass formatted data across processes.
What mechanism is the flexibility of Java?
Reflection mechanism
The difference between sleep and wait
1, Sleep () method, belongs to the thread class. The wait () method is part of the object class.
2. In the process of calling the sleep () method, the thread does not release the object lock. When the Wait () method is called, the thread discards the object lock.
The sleep () method causes the program to pause execution for a specified time, yielding the CPU to other threads, but his monitoring state remains intact and will automatically resume when the specified time has elapsed. When the Wait () method is called, the thread discards the object lock, enters the waiting lock pool waiting for the object, and the thread only enters the object lock pool when the Notify () method is called for this object.
IO and NiO
1, IO is flow-oriented, NIO is buffer-oriented.
The Java io-oriented stream means that one or more bytes are read from the stream every time, until all bytes are read, and they are not being slowed anywhere. In addition, it cannot move data in the stream back and forth. If you need to move the data read from the stream before and after it, you need to cache it to a buffer first. Java NiO has a slightly different buffer-oriented approach. The data is read to a buffer that it processes later, and can be moved back and forth in the buffer if needed. This increases the flexibility of the process. However, you also need to check if the buffer contains all the data that you need to process. Also, make sure that when more data is read into the buffer, do not overwrite the data that has not been processed in the buffer.
2. Various streams of Java IO are blocking, non-blocking mode of Java NiO.
The various streams of Java Io are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read, or the data is fully written. The thread can no longer do anything during this time. The non-blocking mode of Java NIO enables a thread to send requests to read data from a channel, but it can only get the data that is currently available and will not get anything if no data is available. Instead of keeping the thread blocked, the thread can continue to do other things until the data becomes readable. The same is true for non-blocking writes. A thread requests to write some data to a channel, but does not have to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).
3. The Java NiO selector allows a single thread to monitor multiple input channels, you can register multiple channels using a selector, and then use a separate thread to "select" the channel: these channels already have inputs that can be processed, or select the channels that are ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels. and Java IO has no selectors.
Scoket
For a full-featured socket, the following basic structure is included, and the work process consists of the following four basic steps:
(1) Create socket;
(2) Open the input/output stream connected to the socket;
(3) Read/write the socket according to certain protocol;
(4) Close the socket.
Refer to the blog:
Http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html
Deep cloning, shallow cloning
Shallow copy copies only the objects that you are considering, not the objects that it refers to.
Deep copy copies the objects that are referenced by the object being copied again.
There is only single inheritance in Java, and if you want to give a class A new attribute, it is usually implemented using an interface.
Multi-inheritance is supported in C + +, allowing a subclass to have interfaces and features of more than one parent class at a time.
UDP and TCP
Both UDP and TCP belong to the Transport layer protocol.
TCP protocol: Connection-oriented, reliable, byte-based throttling
UDP protocol: No connection, unreliable, message-based
1, the TCP protocol contains a special delivery guarantee mechanism, when the data receiver receives the sender's message, it will automatically send a confirmation message to the sender, the sender only after receiving the acknowledgement message to continue to transmit other information, or will wait until the confirmation message is received.
Unlike TCP, the UDP protocol does not provide a guarantee mechanism for data transfer. If the datagram is lost during delivery from the sender to the receiver, the protocol itself is not capable of making any detection or prompting. Therefore, the UDP protocol is often referred to as an unreliable transport protocol.
2, compared to the TCP protocol, the other difference of UDP protocol is how to receive a burst of multiple datagrams. Unlike TCP,UDP, there is no guarantee of the order in which data is sent and received.
Red and black Trees
is a self-balancing binary search tree, red and black trees is a very interesting balance of the search tree, each time the insertion of the calculation to ensure the balance of the binary tree; if there is 2 of the n-th data magnitude, query only need to query n times.
We have added 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 child nodes of each red node are black. (no two consecutive red nodes can be found on 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 enforce the key properties of the red-black tree: The longest possible path from the root to the leaf is no more than twice times longer than the shortest possible path. The result is that the tree is broadly balanced.
Reflection
The reflection mechanism refers to the information that the program can acquire itself at run time.
The reflection mechanism is used to increase and check the database data.
Rationale: When you save the data, remove all the property values of the objects that you want to save and then piece together the SQL statements, and when you query, wrap the data you query 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. and the name of the Pojo class is the same as the name of the table, the property name is the same as the field name, and the capitalization is not related, 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-time handshake: First the client sends a connection request message, the Server section accepts the connection and replies to the ACK message, and allocates resources for this connection. After the client receives an ACK message, it sends an ACK message to the server segment and allocates resources so that the TCP connection is established.
Four-time handshake:
Because TCP connections are full-duplex, each direction must be closed separately. The principle is that when a party completes its data sending task, it can send a fin to terminate the connection in this direction. Receiving a fin only means there is no data flow in this direction, and a TCP connection can still send data after receiving a fin. The first party to close will perform an active shutdown, while the other side performs a passive shutdown.
(1) The TCP client sends a fin to shut down the client-to-server data transfer.
(2) The server receives this fin, it sends back an ACK, confirms that the serial number is the received sequence number plus 1. As with Syn, a fin will occupy a sequence number.
(3) The server shuts down the client connection and sends a fin to the client.
(4) The client sends back ACK message confirmation and sets the confirmation sequence number to receive the serial number plus 1.
Equals () and = =
1. The difference value type of equals and = = in Java is a stack stored in memory (the stack), whereas a variable of a reference type is simply the address of the reference type variable stored in the stack, which itself is stored in the heap.
2, = = Operation compares the value of the two variables is equal, for the reference variable represents the two variables stored in the heap is the same address, that is, the contents of the stack is the same.
3. Whether the two variables represented by the equals operation are references to the same object, that is, whether the contents of the heap are the same.
4, = = compares the address of 2 objects, while equals compares the contents of 2 objects, obviously, when equals is true, = = is not necessarily true.
Ali Java Development interview Frequently asked Questions summary 4