Java background development interview questions to share three

The difference between Overload and Override. Can overloaded methods be distinguished based on the return type?

Overloading: the same class, the same method name, different parameter lists (the number, type and order of parameters are different); the constructor can be overloaded; the overloading of the method has nothing to do with the return value type and formal parameter variable name, it is recommended The return value types are preferably the same.
Override: The subclass overrides the method inherited from the parent class. The method name is the same, the parameter list is the same, and the return value type is the same. Starting from jdk 1.5, it supports returning the subclass type (if it is a generic type, the parent class can be the same as the subclass after erasing the generic type); method access rights cannot be changed Small; subclass methods cannot throw larger exceptions than the parent class; the two methods must be both static or non-static.


Why Type Transformation Integer[]=> Object[]Yes, but Integer[]=> int[]Not

Integer[]To Object[]is small to large array of reference type conversion reference type array, it can be automatically converted.

Integer[]To int[]be converted to an array of reference data type array of basic data types, strong direct transfer error, one needs to be converted through the array.


try-catch-finally-return execution order

Regardless of whether an exception occurs, the code in the finally block will be executed.

When there is a return statement in try and catch, the code of the finally block will still be executed.

If there is no return in finally and return is before finally, then no matter what the code in finally is, the returned value will not change, and it will still be the value saved in the previous return statement.

If there is a return in finally, the return of try and catch will be invalid.


What are the life cycles (states) of threads

New state (New): When the thread object is created, that is, into the new state, such as: Thread t = new MyThread().

Ready state (Runnable): When the start() method t.start() of the thread object is called, the thread enters the ready state. A thread in the ready state just means that the thread is ready and waiting for the CPU to schedule execution at any time, not that the thread will execute immediately after executing t.start().

Running state (Running): When the CPU starts to schedule a thread in the ready state, then the thread can actually execute, that is, it enters the running state. Note: The ready state is the only entry to the running state, that is, if a thread wants to enter the running state for execution, it must first be in the ready state.

Blocked: For some reason, the thread in the running state temporarily gives up the right to use the CPU and stops execution. At this time, it enters the blocked state. Until it enters the ready state, it has the opportunity to be called by the CPU again to enter To the running state. According to different causes of blocking, the blocking state can be divided into three types:

  1. Waiting for blocking-the thread in the running state executes the wait() method to make the thread enter the waiting for blocking state;

  2. Synchronous blocking-the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads), it will enter the synchronized blocking state;

  3. Other blocking-By calling the thread's sleep() or join() or issuing an I/O request, the thread will enter the blocking state. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread turns to the ready state again.

Dead: The thread finishes its execution or exits the run() method due to an exception. The thread ends its life cycle.


The difference between Runnable interface and Callable interface

1. The call() method of the Callable interface can have a return value (through the get() method of the Future interface, but this method is blocking), while the run() method of the Runnable interface has no return value.

2. The call() method of the Callable interface can declare to throw an exception, while the run() method of the Runnable interface cannot declare to throw an exception (the run method will directly throw an exception when an exception occurs, and print out the stack information, but it can be customized ThreadFactory method to catch exceptions).


Where is the security of Java

The security of the language level is mainly reflected in:

  1. Java uses "references" to replace powerful but dangerous pointers. Since the pointer can be moved, the pointer can point to a memory area, regardless of whether the area is available. This is dangerous, because the memory address may store important data or be occupied by other programs, and use pointers It is also prone to array out-of-bounds exceptions.
  2. Garbage collection mechanism: The programmer does not need to directly control the memory collection, and the garbage collector automatically collects the no longer used memory in the background. Avoid memory leaks caused by forgetting to recycle in time; avoid system crashes caused by program error reclaiming the memory of the program core library.
  3. Exception handling mechanism: Java exception mechanism mainly relies on five keywords: try, catch, finally, throw, and throws.
  4. Forced type conversion: Only when the forced conversion rules are met can the forced conversion succeed.

Underlying security: Java uses public-key cryptography in the transmission of bytecode.

Four levels of security protection mechanisms are provided in the operating environment: bytecode verifier, class loader, runtime memory layout, and file access restrictions.


What are the ways to create a thread pool

  1. newFixedThreadPool(int nThreads) Create a fixed-length thread pool; every time a task is submitted, a thread is created until the maximum number of the thread pool is reached, then the thread size will no longer change; when one of the threads ends up due to an unexpected error, the thread The pool will add a new thread.
  2. newCachedThreadPool() Create a cacheable thread pool; if the size of the thread pool exceeds the processing demand, idle threads will be automatically recycled, and when the demand increases, new threads can be automatically added; there is no limit to the size of the thread pool.
  3. newSingleThreadExecutor() This is a single-threaded Executor; it creates a single worker thread to perform tasks, and if this thread ends abnormally, it will create a new one to replace it; its feature is to ensure that tasks are executed serially in the order of the queue.
  4. newScheduledThreadPool(int corePoolSize) A fixed-length thread pool is created, and tasks are executed in a delayed or timed manner, similar to Timer.

The difference between Synchronized and Lock

Original composition

  • Synchronized is a keyword and belongs to the JVM level. The bottom layer is completed by monitorenter and monitorexit, which depends on the monitor object. Since the wait/notify method also depends on the monitor object, these methods can only be called in a synchronized block or method.
  • Lock is under the java.util.concurrent.locks.lock package and is an API-level lock.

Instructions

  • Synchronized does not require the user to manually release the lock. After the code is completed, the system automatically lets the thread release the lock.
  • ReentrantLock requires the user to manually release the lock. Failure to manually release may lead to deadlock.

Wait whether it can be interrupted

  • Synchronized cannot be interrupted unless an exception is thrown or normal operation is completed.
  • ReentrantLock can be interrupted. One is to pass tryLock(long timeout, TimeUnit unit), the other is to put lockInterruptibly() in the code block and call the interrupt() method to interrupt.

Is locking fair

  • Synchronized is an unfair lock
  • ReentrantLock is a non-fair lock by default. You can pass a boolean value in the constructor. True represents a fair lock, and false represents an unfair lock.

Lock multiple conditions

  • Synchronized has only one blocking queue and can only wake up one thread randomly or all threads.
  • ReentrantLock is used to realize group wake-up and can wake up accurately.

String s = new String("xyz");How many objects were created? Is it possible to inherit the String class?

Two or one. "Xyz" corresponds to an object. This object is placed in the string constant pool. The constant "xyz" is the one in the string constant pool no matter how many times it appears; and every time new String is written, a new object is created. Use the constant "xyz" to create a new String object. If an "xyz" has been created before, then it is taken directly from the string constant pool, and only a StringObject is created at this time; but if the "xyz" has not been created before, then an "xyz" constant object will be created and placed Enter the string constant pool, and then create a new object pointing to "xyz" in new String. In this case, create two objects.

As for whether the String class inherits, the answer is no, because the String class uses final modification, it is not inheritable.


The use and principle of HashSet (hashCode() and equals())

  1. The bottom layer of HashSet is implemented through HashMap, and the bottom layer of HashMap uses hash tables for data management. The query speed of the hash table is extremely fast, and the time complexity is O(1). The hash table needs to use the hash code hashcode, which is an integer value representing the characteristics of the object. address = hash(hashcode), where hash is the hash function and address is the storage address of the hash table data. To judge whether two elements are duplicated in Java's hash table, hashCode() and equals() are used. hashCode() determines the storage location of the data in the table, and equals() determines whether the same data exists.
  2. If you want to put a custom class into the HashSet collection, you must override hashCode(). If the custom class is not rewritten, it calls the hashCode() of the Object, but the hashCode() of the Object is actually the address of the referenced object. In addition, the system class has already covered the hashCode() method and does not need to be rewritten.
  3. The element added by HashSet is stored in the key position of HashMap, while the value of HashMap takes the default constant PRESENT, which is an empty object.
  4. The add method of HashSet is implemented by the put method of HashMap: first calculate the hash code of the object to be added, and obtain a location to store the current object according to the value. If there is no object at that position, then the set considers that the object does not exist in the set and adds it directly. If there is an object at this position, then compare the object to be added to the collection with the object at that position with the equals method; if the equals method returns false, the collection considers that the object does not exist in the collection, and then the object Insert by means of linked list or red-black tree; if the equals method returns true, it means that the element is repeated.

Want to know more, welcome to follow my WeChat public account: Renda_Zhang

Guess you like

Origin blog.csdn.net/qq_40286307/article/details/108890773