Interview questions related to Java basics (2)

1. try catch finally, if there is return in try, will finally be executed?

Execution, and the execution of finally is earlier than the return in try

Conclusion:
1. Regardless of whether an exception occurs, the code in the finally block will be executed;
2. When there is return in try and catch , finally will still be executed;
3. Finally is executed after the expression after return is calculated (at this time, the calculated value is not returned, but the value to be returned is saved first Regardless of the code in finally, the returned value will not change and is still the previously saved value), so the function return value is determined before finally is executed;
4. It is best not to include return in finally, otherwise the program will exit early and the return value is not the return value saved in try or catch.

2. Excption and Error package structure

Java's throwable structures are divided into three types: checked exceptions (CheckedException), runtime exceptions (RuntimeException), and errors (Error).

1. Runtime exception
Definition: RuntimeException and its subclasses are called runtime exceptions.

Features: Java compiler will not check it. In other words, when this kind of exception may occur in the program, if it is neither "thrown through the throws statement" nor "caught with a try-catch statement", it will still be compiled and passed. For example, ArithmeticException is generated when the divisor is zero, IndexOutOfBoundsException is generated when the array is out of bounds, and ConcurrentModificationException is generated by the fail-fast mechanism (all collection classes under the java.util package fail fast, and "fast failure" means Fail-fast is an error detection mechanism for Java collections. When multiple threads perform structural changes to the collection, a fail-fast mechanism may occur. Remember that it is possible, not certain. For example : Suppose there are two threads (Thread 1, Thread 2). Thread 1 is traversing the elements in set A through Iterator. At some point, thread 2 modifies the structure of set A (a modification of the structure, not a simple modification). The content of the collection element), then the program will throw a ConcurrentModificationException exception at this time, resulting in a fail-fast mechanism. This error is called a concurrent modification exception. Failsafe, all classes under the java.util.concurrent package are safe to fail. During the traversal process, if the contents of the array that have been traversed change, the iterator will not throw a ConcurrentModificationException exception. If the contents of the array that has not been traversed changes, it may be reflected in the iteration process. This is ConcurrentHashMap iteration The performance of weak consistency in the device. The weak consistency of ConcurrentHashMap is mainly to improve efficiency, which is a trade-off between consistency and efficiency. To become strong consistency, you have to use locks everywhere, even global locks, which is different from Hashtable Same as the synchronized HashMap.), etc., are all runtime exceptions.

Five common runtime exceptions:
ClassCastException (class conversion exception)
IndexOutOfBoundsException (array out of bounds)
NullPointerException (null pointer exception)
ArrayStoreException (data storage exception, the operation array is of inconsistent type)
BufferOverflowException

2. Checked exception
Definition: The Exception class itself, as well as other subclasses of Exception except "runtime exception", are all checked exceptions. .

Features: Java compiler will check it. Such exceptions must either be declared and thrown through throws, or caught and processed through try-catch, otherwise they cannot pass compilation. For example, CloneNotSupportedException is a checked exception. When an object is cloned through the clone() interface, and the class corresponding to the object does not implement the Cloneable interface, a CloneNotSupportedException exception will be thrown. Checked exceptions are usually recoverable. For example:
IOException
FileNotFoundException
SQLException

The checked exception applies to error conditions that are not caused by the program, such as: the file does not exist when reading the file.
FileNotFoundException. However, unchecked exceptions are usually caused by poor programming, such as NullPointerException caused by not ensuring that the object is not null when referencing it.

3. Error
Definition: Error class and its subclasses.
Features: Like runtime exceptions, the compiler will not check for errors.
An error occurs when insufficient resources, constraint failure, or other conditions occur that prevent the program from continuing to run. The program itself cannot fix these errors. For example, VirtualMachineError is an error. This error will cause the program to terminate. OutOfMemoryError, ThreadDeath.
The Java virtual machine specification stipulates that the memory of the JVM is divided into several blocks, such as heap, stack, program counter, method area, etc.

3. What situations have you encountered in OOM, and what situations have you encountered in SOF?

OOM:
1. OutOfMemoryError exception
In addition to the program counter, OutOfMemoryError(OOM) occurs in several other runtime areas of the virtual machine memory. ) possible abnormality.
Java Heap overflow:
General exception information: java.lang.OutOfMemoryError:Java heap spaces.
The Java heap is used to store object instances. As long as we continue to create objects and ensure that there is a reachable path between GC Roots and objects to avoid the garbage collection mechanism clearing these objects, the number of objects will increase. A memory overflow exception occurs after reaching the maximum heap capacity limit.

When this kind of exception occurs, the general method is to first analyze the dumped heap dump snapshot through a memory image analysis tool (such as Eclipse Memory Analyzer). The focus is to confirm whether the objects in the memory are necessary and distinguish them first. Is it because of memory leak (MemoryLeak) or memory overflow (Memory Overflow).
If it is a memory leak, you can further use tools to view the reference chain from the leaked object to GCRoots. Then you can find out how the leaked object is associated with GC Roots and prevents the garbage collector from automatically recycling it.
If there is no leak, you should check whether the virtual machine parameters (-Xmx and -Xms) are set appropriately.

2, virtual machine stack and local method stack overflow
If the stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine, a StackOverflowError exception will be thrown.
If the virtual machine cannot apply for enough memory space when expanding the stack, an OutOfMemoryError exception will be thrown.
It should be noted here that when the size of the stack is larger, the amount of memory that can be allocated is The fewer threads there are.

3, runtime constant pool overflow
Exception information: java.lang.OutOfMemoryError:PermGenspace
If you want to add content to the runtime constant pool , the simplest way is to use the Native method String.intern(). The function of this method is: if the pool already contains a string equal to this String, return the String object representing this string in the pool; otherwise, add the string contained in this String object to the constant pool, and return this A reference to a String object. Since the constant pool is allocated in the method area, we can limit the size of the method area through -XX:PermSize and -XX:MaxPermSize, thereby indirectly limiting the capacity of the constant pool.

4, method area overflow
The method area is used to store Class-related information, such as class name, access modifier, constant pool, field description, method description, etc. It is also possible that the class objects saved in the method area have not been recycled in time or the memory occupied by the class information exceeds our configuration.
Exception information: java.lang.OutOfMemoryError:PermGenspace
Method area overflow is also a common memory overflow exception. If a class is to be recycled by the garbage collector, The judgment conditions are very stringent. In applications that often dynamically generate a large number of Classes, special attention should be paid to this point.

SOF (Stack Overflow):
Definition of StackOverflowError: This error is thrown when an application recurses too deeply and a stack overflow occurs.
Because the stack generally defaults to 1-2m, once an infinite loop or a large number of recursive calls occurs, during the continuous pushing process, the stack capacity will exceed 1m and cause overflow.
Causes of stack overflow: recursive calls, a large number of loops or infinite loops, too many global variables, and too large array, List, and map data.

4. Briefly describe the basic concepts of threads, programs, and processes. And what is the relationship between them?

threadSimilar to a process, but a thread is a smaller unit of execution than a process. A process can generate multiple threads during its execution. Different from a process, multiple threads of the same type share the same memory space and a set of system resources. Therefore, when the system generates a thread or switches between threads, the burden is much smaller than that of a process. Precisely because As such, threads are also called lightweight processes.

programIt is a file containing instructions and data, which is stored on a disk or other data storage device. That is to say, the program is static code.

processIt is an execution process of the program and the basic unit for the system to run the program, so the process is dynamic. Running a program on the system is the process from creation, operation to death of a process. Simply put, a process is an executing program. It executes instructions one after another in the computer. At the same time, each process also occupies certain system resources such as CPU time, memory space, files, and input and output devices. Rights of use, etc. In other words, when the program is executed, it will be loaded into memory by the operating system. Threads are smaller running units that a process is divided into. The biggest difference between threads and processes is that each process is basically independent, but each thread is not necessarily, because threads in the same process are very likely to affect each other. From another perspective, processes belong to the category of the operating system, mainly because more than one program can be executed at the same time within the same period of time, while threads can execute more than one program segment almost simultaneously within the same program.

5. What should I do if some fields do not want to be serialized in Java serialization?

For variables that do not want to be serialized, use the transient keyword to modify them.
The function of the transient keyword is to prevent the serialization of variables modified with this keyword in the instance; when the object is deserialized, the variable value modified by transient will not be persisted. and recovery. Transient can only modify variables, not classes and methods.

6. Talk about IO stream in Java

How many types of IO streams are there in Java?

  • According to the flow direction of the flow, it can be divided into input flow and output flow;
  • According to the operation unit, it can be divided into byte stream and character stream;
  • According to the role of the flow, it is divided into node flow and processing flow.

The Java Io flow involves a total of more than 40 classes. These classes look messy, but they are actually very regular and have very close connections with each other. The more than 40 classes of the Java I0 flow are derived from the following 4 abstract classes Derived from the base class.

  • InputStream/Reader: The base class of all input streams, the former is a byte input stream, and the latter is a character input stream.
  • OutputStream/Writer: The base class of all output streams, the former is a byte output stream, and the latter is a character output stream.

7. The difference between Java IO and NIO

NIO stands for New IO. This library was only introduced in JDK1.4. NIO and IO have the same function and purpose, but the implementation methods are different. NIO mainly uses blocks, so NIO is much more efficient than IO. Two sets of NIO are provided in the Java API, one is for standard input and output NIO, and the other is network programming NIO.

8. The working principle of java reflection

1. Definition:
The reflection mechanism is that at runtime, for any class, all properties and methods of this class can be known; for any object, it can be called any method. In Java, as long as the name of the class is given, all information about the class can be obtained through the reflection mechanism.

2. Where is the reflection mechanism used?
jdbc is a typical reflection

Class.forName('com.mysql.jdbc.Driver.class');//加载MySQL的驱动类

This is reflection. Frameworks such as hibernate and struts are implemented using reflection.

3. How to implement reflection:
Step 1: Get the Class object. There are 4 methods: 1) Class.forName ("path to class"); 2) Class Name.class 3) Object name.getClass() 4) For a basic type of packaging class, you can call the Type attribute of the packaging class to obtain the Class object of the packaging class

4. Classes that implement Java reflection:
1) Class: Represents the classes and interfaces in the running Java application. Note: All obtaining information about objects requires the Class class. accomplish. 2) Field: Provides attribute information about classes and interfaces, as well as dynamic access rights to it. 3) Constructor: Provides information about a single constructor method of the class and its access permissions 4) Method: Provides information about a method in the class or interface

5. Advantages and disadvantages of the reflection mechanism:
Advantages: 1) Ability to dynamically obtain instances of classes at runtime, improving flexibility; 2) Combined with dynamic compilation< a i=2> Disadvantages: 1) Using reflection has low performance and requires parsing bytecode and objects in memory. Solution: 1. Turn off the JDK security check through setAccessible(true) to improve reflection speed; 2. When creating instances of a class multiple times, it will be much faster with cache 3. ReflectASM tool class, speed up through bytecode generation Reflection speed 2) Relatively unsafe and destroys encapsulation (because private methods and properties are available through reflection)

9. Talk about the differences between List, Set and Map?

  • List (a good helper for dealing with order): The List interface stores a set of non-unique (there can be multiple elements referencing the same object), ordered objects.
  • Set (focus on unique properties): Duplicate sets are not allowed. There will be no more than one element referencing the same object.
  • Map (experts in searching by Key): Uses key-value storage. Map will maintain the value associated with Key. Two Keys can refer to the same object, but the Key cannot be repeated. A typical Key is a String type, but it can also be any object.

10. What are the common methods of Object? Let’s briefly talk about the meaning of each method.

java.lang.Object
Insert image description here

clone method
A protected method that implements shallow copying of objects. This method can only be called if the Cloneable interface is implemented, otherwise a CloneNotSupportedException exception will be thrown
, deep copy also needs to implement Cloneable, and its member variables that are reference types also need to implement Cloneable, and then rewrite the clone method.

finalize method
This method is related to the garbage collector. The last step to determine whether an object can be recycled is to determine whether this method has been overridden.

equals method
This method is used very frequently. Generally equals and == are different, but in Object they are the same. Subclasses generally override this method.

hashCode method
This method is used for hash search. Rewriting the equals method generally requires rewriting the hashCode method. This method is used in some Collections with hash functions. .
Generally must satisfy obj1.equals(obj2)==true. It can be deduced that obj1.hashCode()==obj2.hashCode(), but
equal hashCode does not necessarily satisfy equals. However, in order to improve efficiency, the above two conditions should be made as close to equivalent as possible.

  • JDK 1.6 and 1.7 return random numbers by default;
  • JDK 1.8 defaults to a random number obtained by using Marsaglia’s xorshiftscheme random number algorithm through a random number + three determined values ​​related to the current thread.

wait method
Used with synchronized, the wait method makes the current thread wait for the object's lock. The current thread must be the owner of the object, that is, it has the lock of the object. The wait() method waits until it acquires the lock or is interrupted. wait(long timeout) sets a timeout interval and returns if the lock is not obtained within the specified time.
After calling this method, the current thread enters sleep state until the following events occur.

  1. Other threads called the object's notify method;
  2. Other threads called the object's notifyAll method;
  3. Other threads call interrupt to interrupt this thread;
  4. The time interval has arrived.

At this point, the thread can be scheduled. If it is interrupted, an InterruptedException will be thrown.

notify method
Used with synchronized, this method wakes up a thread in the waiting queue on the object (the thread in the synchronization queue is for the thread that preempts the CPU, and the thread in the waiting queue The thread refers to the thread waiting to be awakened).
The notifyAll method is used with synchronized. This method wakes up all threads waiting in the queue on this object.

Summary
As long as you are familiar with the above methods, there is no need to discuss the toString and getClass methods. This question tests the familiarity with Object. Many methods that are used in daily life are still used without looking at their definitions, such as: wait() method, equals() method, etc.

Class Object is the root of the class hierarchy.Every class has Object as a
superclass. All objects, including arrays, implement the methods of this class.

Rough meaning: Object is the root of all classes and the parent class of all classes. All objects, including arrays, implement the methods of Object.

11. How many ways are there to create objects in Java?

1. Use the new keyword, which is also the most commonly used way to create objects. Example:

User user=new User();

2. Use reflection to create objects and use newInstance(), but you have to handle two exceptions: InstantiationException and IllegalAccessException:

User user=User.class.newInstance();
Object object=(Object)Class.forName("java.lang.Object").newInstance()

3. Use the clone method. In the previous question, clone is a method of Object, so all objects have this method.

4. Use deserialization to create an object and call the readObject() method of the ObjectInputStream class.
When we deserialize an object, the JVM will create a separate object for us. The JVM does not call any constructors when creating objects. If an object implements the Serializable interface, the object can be written to a file and the object can be created by reading the file.

5. Summary, keywords for creating objects: new, reflection, clone copy, deserialization.

12. What are the ways to obtain a Class object?

Be clear about class objects and instance objects, but they are all objects.

The first one: Obtain it through the getClass() method of the class object. Anyone who is careful knows that this getClass is a method in the Object class.

User user=new User();
//clazz就是一个User的类对象
Class<?> clazz=user.getClass();

The second type: represented by static members of the class, each class has an implicit static member class.

//clazz就是一个User的类对象
Class<?> clazz=User.class;

The third method: Obtain through the static method forName() method of the Class class.

Class<?> clazz = Class.forName("com.tian.User");

13. What are the differences between ArrayList and LinkedList?

ArrayList

  • Advantages: ArrayList implements a data structure based on dynamic arrays. Because the addresses are continuous, once the data is stored, the query operation efficiency will be relatively high (it is stored continuously in the memory).
  • Disadvantages: Because the addresses are continuous, ArrayList needs to move data, so the insertion and deletion operations are relatively inefficient.

LinkedList

  • Advantages: LinkedList is based on the linked list data structure, and the address is arbitrary, so there is no need to wait for a continuous address when opening up memory space. For add and delete operations, LinkedList is more advantageous. LinkedList is suitable for scenarios where you want to operate head to tail or insert at a specified position.
  • Disadvantages: Because LinkedList needs to move the pointer, the query operation performance is relatively low.

Applicable scenario analysis

  • When random access to data is required, use ArrayList.
  • When data needs to be added, deleted and modified multiple times, LinkedList is used.

If the capacity is fixed and will only be added to the end without causing capacity expansion, ArrayList is preferred.
Of course, in most business scenarios, using ArrayList is enough, but care needs to be taken to avoid ArrayList expansion and non-sequential insertion.

14. Have you ever used ArrayList? Tell me what are its characteristics?

Anyone who is engaged in Java will definitely answer "used". So, answer the second half of the question - the characteristics of ArrayList. You can answer from these aspects:

One of the Java collection frameworks stores element data of the same type. It is a variable-length collection class, implemented based on a fixed-length array. When data is added to a certain extent, it will automatically expand, that is, expand the array size.

The bottom layer is implemented using an array to add elements.

  • If add(o) is added to the end of the array, if the amount of data to be added is large, the ensureCapacity() method should be used. The function of this method is to pre-set the size of the ArrayList, which can greatly improve the initialization speed.
  • If you use add(int,o) to add to a certain position, a large number of array elements may be moved and the expansion mechanism may be triggered.

In high concurrency situations, threads are not safe. Multiple threads operating ArrayList at the same time will cause unpredictable exceptions or errors.

ArrayList implements the Cloneable interface, indicating that it can be copied. Note: The clone() copy in ArrayList is actually a shallow copy.

15. Why do we need to create an ArrayList when we already have an array?

Usually when we use it, if we don't know how much data to insert, ordinary arrays are very awkward because you don't know what size the array needs to be initialized. However, ArrayList can use the default size. When the number of elements reaches After a certain level, the capacity will be automatically expanded.

It can be understood this way: the array we often say is a fixed array, but ArrayList is a dynamic array.

16. What is fail-fast?

The fail-fast mechanism is an error mechanism in Java collections. When multiple threads operate on the contents of the same collection, fail-fast events may occur.

For example: when a thread A traverses a collection through an iterator, if the content of the collection is changed by other threads, then when thread A accesses the collection, a ConcurrentModificationException exception will be thrown and a fail-fast event will occur. The operations here mainly refer to add, remove and clear, which modify the number of collection elements.

Solution: It is recommended to use "classes under the java.util.concurrent package" to replace "classes under the java.util package".

It can be understood this way: before traversing, write down modCount as expectModCount, and then compare expectModCount with modCount. If they are not equal, it proves that it has been concurrent and has been modified, so a ConcurrentModificationException exception is thrown.

17. Talk about the difference between Hashtable and HashMap

  1. The birth versions are different. Hashtable was born in JDK 1.0, the first version released by Java, and HashMap was born in JDK1.2.
  2. All implement Map, Cloneable, and Serializable (current JDK version 1.8).
  3. HashMap inherits AbstractMap, and AbstractMap also implements the Map interface. Hashtable inherits Dictionary.
  4. Most of the public modified ordinary methods in Hashtable are modified with synchronized fields and are thread-safe. HashMap is not thread-safe.
  5. The key of Hashtable cannot be null, and the value cannot be null. This can be seen from the put method in the Hashtable source code. If the value is null, a null pointer exception will be thrown directly. There is no previous calculation of the hash value of the key in the put method. If the key is determined to be null, it means that if the key is null at this time, a null pointer exception will still be thrown.
  6. Both the key and value of HashMap can be null. When calculating the hash value, there is a judgment. If key==null, then its hash=0; as for whether the value is null, there is no judgment at all.
  7. Hashtable uses the hash value of the object directly. The hash value is an int type value calculated by JDK based on the object's address, string, or number. Then use the division-leaving-remainder method to get the final position. However, division operations are very time-consuming and very inefficient. In order to improve calculation efficiency, HashMap fixes the size of the hash table to a power of 2, so that when taking the modulo budget, there is no need to perform division, only bit operations are required. Bit operations are much more efficient than division.
  8. Both Hashtable and HashMap use Iterator. Due to historical reasons, Hashtable also uses Enumeration.
  9. By default, the initial capacity is different. The initial length of Hashtable is 11. After each expansion, the capacity becomes the previous 2n+1 (n is the last length). The initial length of HashMap is 16. After each expansion, it becomes the original length. twice.

In addition, there is this sentence in the Hashtable source code comments:

Hashtable is synchronized. If a thread-safe implementation is not needed, it is
recommended to use HashMap in place of Hashtable . If a thread-safe highlyconcurrent implementation is desired, then it is recommended to use
ConcurrentHashMap in place of Hashtable.

The general meaning: Hashtable is thread-safe, and it is recommended to use HashMap instead of Hashtable; if thread-safe and high concurrency is required, it is recommended to use ConcurrentHashMap instead of Hashtable.

40. Can we use any class as key in HashMap?

Usually, the most commonly used thing is to use String as the key of HashMap, but now we want to use a custom class as the key of HashMap, so we need to pay attention to the following points:

  • If a class overrides the equals method, it should also override the hashCode method.
  • All instances of the class need to follow the rules related to equals and hashCode.
  • If a class doesn't use equals, you shouldn't use it in hashCode.
  • The best practice for our custom key class is to make it immutable, so that the hashCode value can be cached and have better performance. Immutable classes also ensure that hashCode and equals will not change in the future, thus solving issues related to mutability.

18. Why is the length of HashMap 2 to the Nth power?

In order to make HashMap store and retrieve data more efficiently, the collision of hash values ​​should be reduced as much as possible, that is to say, the data should be distributed as evenly as possible, and the length of each linked list or red-black tree should be as equal as possible.

We may first think of the % modulo operation to implement it.
The following is the key point of the answer

If the divisor in the remainder (%) operation is a power of 2, it is equivalent to the AND (&) operation of subtracting one from its divisor (that is to say
hash % The premise of length == hash &(length - 1) is that length is 2 to the nth power). Moreover, using the binary
positioning operation & can improve the operation efficiency compared to %.

19. Similarities and differences between HashMap and ConcurrentHashMap

  1. They are all stored data in the form of key-value;
  2. HashMap is thread-unsafe, and ConcurrentHashMap is thread-safe under JUC;
  3. The underlying data structure of HashMap is array + linked list (before JDK 1.8). After JDK 1.8, there is array + linked list + red-black tree. When the number of elements in the linked list reaches 8, the query speed of the linked list is not as fast as that of the red-black tree, and the linked list will be converted into a red-black tree, and the query speed of the red-black tree is faster;
  4. The initial array size of HashMap is 16 (default). When expansion occurs, it will be expanded by 0.75 * array size;
  5. ConcurrentHashMap used segment locks to implement Segment + HashEntry before JDK 1.8.
    The default Segment array size is 16, 2 to the nth power; after JDK 1.8, Node is used + CAS + Synchronized to ensure concurrency safety

20. What are the characteristics of red-black trees?

(1) Each node is either black or red.
(2) The root node is black.
(3) Each leaf node (NIL) is black. [Note: The leaf node here refers to the leaf node that is empty (NIL or NULL)! ]
(4) If a node is red, its child nodes must be black.
(5) All paths from a node to the descendant nodes of this node contain the same number of black nodes.

21. Tell me how you usually handle Java exceptions.

try-catch-finally

  • The try block is responsible for monitoring code that may cause exceptions
  • The catch block is responsible for catching possible exceptions and handling them
  • The finally block is responsible for cleaning up various resources and will be executed regardless of whether an exception occurs.
  • The try block is required, and there is at least a standard exception handling process for catch and finally.

Insert image description here

Throw an exception → catch the exception → catch successfully (when the exception type of catch matches the thrown exception type, the catch is successful) → the exception is handled and the program continues to run throw exception → catch the exception → catch fails (when the exception type of catch When the type of exception thrown does not match, the capture fails) → the exception is not handled and the program is interrupted.

Custom exceptions are used during the development process. Under normal circumstances, the program rarely throws exceptions by itself, because the class name of the exception usually also contains useful information about the exception, so when choosing to throw an exception, you should Choose the appropriate exception class so that the exception can be clearly described, so this time it is often a custom exception.

Custom exceptions are usually inherited from the java.lang.Exception class. If you want to customize Runtime exceptions, you can inherit the java.lang.RuntimeException class and implement a parameterless constructor and a parameterized constructor with string parameters.

In business code, custom exceptions can be used in a targeted manner. For example: the user does not have certain permissions, has insufficient balance, etc.

I have prepared complete interview materials for 2023 for the students~
How to get it: Follow the public account below and reply: Interview

Insert image description here

The article is continuously updated. You can follow the official account below or search "Last Rosemary" on WeChat and reply "Interview" to obtain complete interview information.

Guess you like

Origin blog.csdn.net/qq_38374397/article/details/135016430
Recommended