Java interview finishing one - basic knowledge

1. short s1 = 1; s1 = s1 + 1; wrong? short s1 = 1; s1 += 1; wrong?
For short s1 = 1; s1 = s1 + 1; since 1 is of type int, the result of the operation of s1+1 is also of type int, which needs to be cast to the type
and short s1 = 1; s1 += 1; can be compiled correctly because s1+= 1; Equivalent to s1 = (short)(s1 + 1); which has an implicit cast
2. Difference between & and &&?
The & operator can be used in two ways: (1) bitwise AND; (2) logical AND. The && operator is a short-circuit AND operation.
The difference between logical and and short-circuit and is very huge, although both require that the Boolean values ​​on the left and right ends of the operator are both true. The value of the entire expression is true.
The reason why && is called a short-circuit operation is that if the value of the expression on the left of && is false, the expression on the right will be directly short-circuited and no operation will be performed.
3. Can swtich work on byte, long, and String?
In switch(expr), expr supports byte, short, char, int, enum, string (1.7)
4. Two objects have the same value (x.equals(y) == true), but can have different hash codes, Is this sentence right?
Answer: No, if two objects x and y satisfy x. equals(y) == true, their hash codes should be the same. Java stipulates the equals method and the hashCode method as follows: (1) If the two objects are the same (the equals method returns true), then their hashCode values ​​must be the same; (2) If the hashCode of the two objects is the same, they are not must be the same.
5. Regarding the equals and hashCode methods, the
equals method must satisfy
reflexivity (x.equals(x) must return true) and
symmetry (when x.equals(y) returns true, y.equals(x) must also return true ),
transitivity (when both x.equals(y) and y.equals(z) return true, x.equals(z) must also return true)
consistency (when the object information referenced by x and y has not been modified, Multiple calls to x.equals(y) should get the same return value)
6. The difference between Overload and Override. Can overloaded methods be differentiated by return type?
Overloading: The number or types of parameters of the same method in a class are different, and there is no requirement for the return value
Override : It is required that the overridden method of the subclass has the same return type, is more accessible than the method overridden by the parent class, and cannot be compared to the parent class. Overridden methods have more exceptions.
7. How to implement object cloning?
1). Implement the Cloneable interface and rewrite the clone() method in the Object class;
2). Implement the Serializable interface, realize cloning through object serialization and deserialization, and realize true deep cloning
public static <T> T clone (T obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);
        return (T) ois.readObject();
        }
Clone based on serialization and deserialization Not only deep cloning, but more importantly, through generic qualification, you can check whether the object to be cloned supports serialization. This check is done by the compiler, not throwing an exception at runtime. This is an obvious advantage of the solution. Use the clone method of the Object class to clone an object. Having problems exposed at compile time is always better than leaving them at runtime.
8. The calling sequence
of the object Allocate storage space for the object
Start constructing the object Initialize the static members
from the superclass to the subclass
The superclass member variables are initialized in order, and the constructor of the superclass is recursively
called Subclass member variables are in order Initialization, subclass constructor call
9. ArrayList and linkedList
ArrayList is based on dynamic array implementation, fast query, slow insertion and deletion
LinkedList is implemented based on linked list, fast insertion and deletion, slow query
10. hashSet, LinkedHashSet, TreeSet
hashSet: based on hashMap Unordered, cannot contain duplicate elements, not thread-safe
LinkedHashSet: A subclass of HashSet that uses a linked list to maintain the order of elements. Ordered, non-thread-safe
TreeSet: implemented using red-black tree structure, it is the only implementation class of the sortedSet interface, which can ensure that the elements in the set are in an orderly state
11. HashMap, LinkedHashMap, TreeMap
HashMap: encapsulate key-value into a Entry[] performs processing and stores data according to the hashcode value of the key value.
LinkedHashMap: Inherited from HashMap, a linked list is added inside to store the order of elements, sorting based on the entry order of elements
TreeMap: Implements the SortMap interface and can save it The records are sorted according to the key
12. concurrentHashMap
ConcurrentHashMap provides better write concurrency capabilities on the basis of thread safety, but at the same time makes extensive use of volatile, final, CAS and other lock-free technologies to reduce the impact of lock competition on performance and reduce
In Jdk1.7, the core of concurrenthashMap is segment lock technology, which reduces lock competition while sacrificing the requirements for consistency. In
Jdk1.8, the core of concurrentHashMap is volatile variable + CAS, which is compared and exchanged , the implementation mechanism of optimistic locking.
13. The volatile modifier
ensures the visibility of different threads operating on this variable. When adding the volatile keyword, there will be an additional lock prefix instruction.
Application scenarios: state variables under high concurrency programming, one-time safe release (double locking problem)

14. Tell me about several common sorting algorithms and their respective complexities.
Sorting Worst Time Analysis Average Time Complexity Stability Space Complexity
Bubble Sort O(n2) O(n2) Stable O(1)
Quick Sort O(n2) O(n*log2n) Unstable O(log2n)~ O(n)
Selection Sort O(n2) O(n2) Stable O(1)
Binary Tree Sort O(n2) O(n*log2n) Unstable O(n)
Insertion Sort O(n2) O(n2) Stable O( 1)
Heap sort O(n*log2n) O(n*log2n) unstable O(1)
15. Describe the chain storage structure.
In sequential storage, the storage addresses of adjacent data elements are also adjacent (logically and physically unified); it is required that the addresses of available storage units in memory must be consecutive.
Advantages: high storage density (=1), high storage space utilization.
Disadvantage: Inconvenient when inserting or removing elements.
In chain storage, adjacent data elements can be stored at will, but the storage space occupied is divided into two parts, one part stores the node value, and the other part stores the pointer representing the relationship between the nodes.
Advantages : It is very convenient to insert or delete elements, and it is flexible to use. .
Disadvantages: low storage density (<1), low storage space utilization.
16. How to traverse a binary tree?


Pre-order traversal: The traversal order rule is [root left and right] ABCDEFGHK
In-order traversal: The traversal order rule is [left root right] BDCAEHGKF
Post-order traversal: The traversal order rule is [left and right root] DCBHKGFEA
17. Invert a LinkedList.
Collections.reverse(list);
18. What is the difference between == and equals?
== is an operator, equals is a method
== is generally used for primitive type comparison, and equals is generally used for object comparison.
If == is used for object comparison, it returns true when the addresses referenced by two objects are the same
. 19. What does the hashCode method do?
The functions of the hashCode() method and the equal() method are actually the same. In Java, they are used to compare whether two objects are equal or not. Because the overridden equal() is generally more comprehensive and complicated, so the efficiency is relatively low , and use hashCode() for comparison, you only need to generate a hash value for comparison, which is very efficient. Whenever you need to compare, first use hashCode() to compare, if hashCode() is different, it means this The two objects are definitely not equal (that is, there is no need to use equal() to compare again). If the hashCode() is the same, then compare their equal() at this time. If the equal() is also the same, it means that the two objects It is really the same, which can greatly improve the efficiency and ensure the absolute correctness of the comparison!
20. How to ensure the thread safety of HashMap?
//synchronizedMap is essentially similar to hashTable
Map<String, String> synchronizedHashMap = Collections.synchronizedMap(new HashMap<String, String>());
//Hashtable uses synchronized to ensure thread-safe
Map<String, String> hashtable = new Hashtable <>();
//ConcurrentHashMap
Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();
21. How many bytes does a character occupy in Java?
"Byte" is byte, "bit" is bit; 1 byte = 8 bit; Java uses unicode to represent characters
1 byte: byte , boolean
2 bytes: short , char
4 bytes: int , float
8 bytes : long , double
22. What are the methods to create an object instance?
a) New
b) Using reflection, newInstance() of Java.lang.class or java.lang.reflect.Constructor class
c) Calling clone of the object
d) Deep cloning by deserialization
23. The difference between Session/Cookie ?
Session is a data structure saved on the server to track the state of the user. This data can be saved in clusters, databases, and files;
Cookie is a mechanism for the client to save user information, which is used to record some information about the user. It is also a way to implement Session.
24. The difference between String/StringBuffer/StringBuilder
a) String is a character constant; stringBuffer and StringBuilder are character variables;
b) Execution speed Stringbuilder>StringBuffer>String
c) The methods and functions of StringBuffer and StringBuilder are completely equivalent. Both are inherited from AbstractStringBuilder. A char array is used to store the string that needs to be appended. The char array has an initial size. When the length of the appended string exceeds the current char array When the capacity is reached, the char array is dynamically expanded. It's just that most of the methods in StringBuffer are modified with the synchronized keyword, so they are thread-safe.


Network -related
1. Three-way handshake for TCP connection establishment
The first handshake: the client sends a syn packet (syn=j) to the server.
The second handshake: The server receives the syn packet and must confirm the client's SYN (ack=j+1), and also sends an ASK packet (ask=k).
The third handshake: The client receives the SYN+ACK packet from the server and sends an ACK (ack=k+1) confirmation packet to the server.
2. Four waves of TCP disconnection The
TCP client sends a FIN to close the data transfer from the client to the server. The
server receives this FIN, and it sends back an ACK, confirming that the serial number is the received serial number plus 1. The
server closes the client The connection of the terminal, send a FIN to the client The
client segment sends back an ACK message to confirm, and set the confirmation sequence number to the received sequence number plus 1
3. Reasons and solutions for a large number of TIME_WAIT
According to the three-way handshake disconnection rule defined by the TCP protocol, the socket that actively closes the socket will enter the TIME_WAIT state, and the TIME_WAIT state will last for 2 MSL (Max Segment Lifetime). For example, if the server side actively closes the client's socket connection, there will be a large number of sockets in the TIME_WAIT state on the server side. TIME_WAIT is a mechanism used by the TCP protocol to ensure that the reassigned socket will not be affected by the remaining delayed retransmission messages, and it is a necessary logical guarantee.
Solution: Adjust the kernel parameters
vi /etc/sysctl.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
and then execute /sbin/sysctl -p to let Parameter effective
net.ipv4.tcp_syncookies = 1 means enable SYN Cookies. When the SYN waiting queue overflows, enable cookies to prevent a small number of SYN attacks. The default value is 0, which means close;
net.ipv4.tcp_tw_reuse = 1 means enabling reuse. Allow TIME-WAIT sockets to be reused for new TCP connections, the default is 0, which means close;
net.ipv4.tcp_tw_recycle = 1 means that fast recycling of TIME-WAIT sockets in TCP connections is enabled, and the default is 0, which means close.
net.ipv4.tcp_fin_timeout Modify the default TIMEOUT time of the system
4. Header fields of the HTTP protocol
a) Common header fields
i. Cache-Control: specify the request and the corresponding caching mechanism to follow, the most common value is no-cache, indicating that the request and response messages cannot be cached;
ii. Connection: used for Specifies whether the client and server should continue to connect after processing this request/response.
iii. Transfer-Encoding: used to specify the transfer encoding method of the physical content.
b) Request header field
i. Accept: used to specify the MIME types that the client program can handle, separated by commas;
ii. Accept-Encoding: specify the compression method supported by the client program;
iii. Accept-Language: Specify which national language document the client expects to return;
iv. Accept-Charset: Specify the character set that the client program can use;
v. Host: Specify the host name and port number where the resource is located;
vi. Referer: Specify the source resource of the request uri The address, which is the URI from which the user comes, allows the server to generate a fallback list;
vii. User-Agent: browser client information, such as which browser is used;
viii. Cookie: information left by the server on the browser , which is one of the most important request header fields.
c) Response header field
i. Server: indicates the name of the response server, such as BWS/1.0 or Apache/1.3.27;
ii. Location: When responding to a 302 redirect page, with There is a Location indicating the destination address of the jump;
iii. Set-Cookie: The server sets a cookie to the browser
d) Entity header field
i. Content-Encoding: Indicates the compression method used for the entity content;
ii. Content-Length: Indicates the length of the entity content, in bytes;
iii . . Content-Type: Specifies the MIME type of the entity content;
iv. Expires: Specifies the time after which the entity content expires and is no longer cached.
5. HTTP response status code
1xx: information, request received, continue processing;
2xx: success, behavior was successfully accepted, understood and adopted;
3xx: redirection, further actions that must be performed in order to complete the request;
4xx: client Error, the request contains a syntax error or the request cannot be implemented;
5xx: Server error, the server cannot execute a correct request correctly.
200 The result is returned correctly
302 The page is redirected
304 The page has not changed
400 The request is wrong, does not conform to the protocol
404 The page is not found
405 The method is not allowed
501 Not used
503 The service is unavailable
6. The difference between HTTP, TCP and UDP
TCP/IP is a protocol group , can be divided into three layers: network layer, transport layer and application layer.
In the network layer there are IP protocol, ICMP protocol, ARP protocol, RARP protocol and BOOTP protocol
In the transport layer there are TCP protocol and UDP protocol
In the application layer, there are FTP, HTTP, TELNET, SMTP, DNS and other protocols
. Http protocol is implemented based on the TCP protocol.
Socket is the middle software abstraction layer for communication between the application layer and the TCP/IP protocol family. It is a set of interfaces.

Guess you like

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