2022 java streamlined interview questions

1.  What is the difference between JDK and JRE?

        jre is the java runtime environment, that is, the java runtime environment. When only java programs need to be run, the jre environment is sufficient. jdk is the java developomen kit java development toolkit, which includes not only the jre environment but also the java development environment.

2. What is the difference between == and equals?

        == For the basic type (byte short char float double int long boolean), it is value comparison; for the application type, the comparison is whether it is the same reference address, that is, whether the object opened in the memory is the same.

        In the java Object class, the equals function uses == to judge, but basically most objects rewrite equals, such as the String type, equals internally judges whether two strings are equal, and two identical strings in memory equals is true.

3. If the hashCode() of two objects is the same, then equals() must also be true, right?

        Both hashcode and equals can be rewritten, and the two are not directly related. In hashMap, hashTable, and HashSet, even if the hashcode value is the same, collision processing will be performed, and the same hashcode value will be converted into a linked list or more than 8 converted red-black trees.

4. What is the role of final in Java?

        The class modified by fianl cannot be inherited and has no subclasses; the modified method cannot be overridden, the modified variable must be initialized, and the value cannot be modified.

5. Does String belong to the basic data type?

Does not belong, belongs to the reference type. The eight basic types include byte boolean char short int float long double.

6. What are the classes for manipulating strings in Java? What's the difference between them?

        String, StringBuffer, StringBuilder. Frequent updates of String object values ​​open up new space in memory each time pointing to a different object. The other two will be modified on the initialized object, and the memory address is the same;

        StringBuffer is thread-safe, StringBuilder is not thread-safe.

7. Is String str="i" the same as String str=new String("i")?

        ="i" still looks in the constant pool to see if there is a value pointing to the constant, and no new one is opened; while new String("i") will directly open up a space in the heap memory.

8. What is the difference between a normal class and an abstract class?

        Ordinary classes can be directly new, but abstract classes cannot; ordinary classes cannot have abstract methods, and abstract classes can have abstract methods and ordinary methods.

9. Can an abstract class be decorated with final?

       No, an abstract class needs to be inherited by subclasses, and final means that the class cannot be inherited, and the editor will prompt an error of illegal modifier combination.

10. What is the difference between interface and abstract class?

        An interface defines some common methods common to some subclasses. An abstract class is a type of java class that is modified by abstract, and methods can have normal methods and abstract methods. The method modifiers in the abstract class can be arbitrary, and the method modifiers in the interface class are public.

11. What is the difference between BIO, NIO, and AIO?

        BIO is the abbreviation of Block IO and synchronous blocking IO. The characteristic mode is simple and convenient to use, and the concurrent processing capacity is low. If there is one write data, it corresponds to the only read data.

        NIO is the abbreviation of Non-Blocking IO, that is, synchronous non-blocking IO, which features multiplexing through Channel (channel) communication. Concurrency is better than BIO.

        AIO is asynchronous non-blocking IO, and the implementation of asynchronous IO is based on event and swap mechanism.

Example: BIO is similar to playing backgammon. There are two people on a chessboard one-on-one. When one person is playing chess, the other person must sit there and wait for the person to make a move before playing chess by himself. The words of NIO are similar to a master and three rookies playing chess at the same time. The master polls to see which chess table should be played by himself, and then goes to other chess tables to see if there are any opponents who should play chess. If not, continue to poll to see that there are tasks that can play chess by yourself on that table. AIO’s words are based on NIO’s basis. The master is busy with his own affairs. When the three rookies finish playing, they will call out. Tell him to play chess.

Container

12. What are the Java containers?

        Java containers are divided into two categories: Collection for storing objects and Map for storing job pairs. The collection is further divided into a List that stores ordered elements that can be repeated and a Set that stores unordered elements that cannot be repeated. The main implementations of List are ArrayList and LinkedList as well as Vector and Stack. The main implementations of Set are Hashset and TreeSet; the main implementations of Map are HashMap, LinkedHashMap, TreeMap, Hashtable (reserved class, not recommended), ConcurrentHashMap.

 13. What is the difference between Collection and Collections?

        Collection is an interface class, and Collections is a collection tool class. Similar to Collections are Arrays.

14. What is the difference between HashMap and Hashtable?

        HashMap runs with empty key and value, but Hashtable does not allow it. HashMap is thread-unsafe, and Hashtable is thread-safe, but it is not recommended to use Hashtable now, and ConcurrentHashMap is recommended.

15. How to decide to use HashMap or TreeMap?

        Since the array storage used by the underlying key of HashMap calculates the hash value of the key to determine the storage location, so insertion, deletion, and query efficiency are relatively high. The key of TreeMap is stored in a red-black tree structure, so the efficiency of orderly traversal is higher. When orderly traversal is required, TreeMap is selected. Others can choose HashMap.

16. Tell me about the implementation principle of HashMap?

        Through source code analysis, the bottom layer of HashMap uses array storage, and the default length is 16. When storing the object, the Hash value is calculated by calculating the key. Then calculate the index position in the array according to the hash value. When the capacity in the array exceeds the default load factor of 0.75, the capacity will be doubled, and the storage location will be recalculated after expansion. When the storage positions of the two elements are the same, when the number of elements at the same position is less than 8, the eight elements are stored in the form of a linked list, and when there are more than eight, the structure is changed to a red-black tree structure.

17. Tell me about the implementation principle of HashSet?

        HashSet is implemented based on the operation principle of key in HashMap. The stored data is HashMap, the key is the added value, and the Value is a virtual fixed object. The add method of HashMap is called when there is an add operation. Delete the remove method of HashMap called by remove. HashSet does not allow adding duplicate key values.
18. What is the difference between ArrayList and LinkedList?

        The bottom layer of arrayList is implemented with a dynamic array, and LinkedList is implemented based on a doubly linked list. The efficiency of ArrayList is higher than that of LinkedList in terms of query efficiency, and the efficiency of linked list is higher than that of ArrayList in terms of adding and deleting operations.

19. How to realize the conversion between array and List?

        Use Arrays.asList(array) to convert an array to a list, and use the toArray() method that comes with List to convert a list to an array.

20. What is the difference between ArrayList and Vector?

        arrayList is thread-unsafe, vector is thread-safe, and the performance of arrayList is higher than vector. When the capacity needs to be expanded, the ArrayList can be expanded by 50% of the current capacity at a time, while the capacity of the vector can be doubled.

21. What is the difference between Array and ArrayList?

        Arrays can store basic types of data, while ArrayList can only store object types. Array is of fixed length, and ArrayList is dynamically expanded.

22. Which collection classes are thread safe?

        vector, Stack, HashTable, ConcurrentHashMap (replacement object of HashTable) are thread-safe. (String operation class StringBuffer is thread-safe)

23. What is iterator Iterator?

        Iterator is an iterator object in the collection class, returned by the collection.iterater() method. You can iterate through the it.hasNext() and it.next() methods to obtain elements, and you can delete the last obtained object through the it.remove() method. ConcurrentModificationException will be thrown when adding or deleting during iteration.

24. What is the difference between Iterator and ListIterator?

        Iterator can traverse all list and set collections, while ListIterrator can only traverse List collections. Iterator can only traverse in one direction, while listiterator can traverse in two directions, add elements, replace elements, and obtain the index positions of front and rear elements.

25. How to ensure that a collection cannot be modified?

        You can use the Collections.unmodifiiableCollection(Collection c) method to convert the collection back to a read-only collection, so that any operation that modifies the collection will throw a Java.lang.UnsupportedOperationException exception.

Multithreading

26. What is the difference between thread and process?

        A program can contain multiple processes. Each process can have multiple threads.

27. What is a daemon thread?

        The daemon thread is also a kind of thread. Unlike ordinary threads, the JVM program does not consider whether there is a running daemon thread when it exits. Conversely speaking, when the last non-daemon thread exits, the JVM exits (at this time, even if there is a daemon thread, Zhao still exits). The way to create a daemon thread in java is to pass thread.setDaemon(true) before the start method;

28. What are the ways to create threads?

        There are three ways to create threads.

        1. Inherit the Thread class to rewrite the run method;

        2. Implement the Runnable interface;

        3. Implement the Callable interface;

29. What is the difference between runnable and callable?

        To implement the runnable interface, you need to implement the run method, and to implement the callable interface, you need to implement the call method. The run method has no return value, and the call method has a return value. After implementing the call method, use the thread pool class method <T> Future<T> java.util.concurrent.ExecutorService#submit(java.util.concurrent.Callable<T>)

Return the Future object after submission, and wait for the result to be returned through the get method (blocking method) of the object.

30. What are the states of a thread?

        The 7 states are 1 new state (New), 2 ready state (Runnable), 3 running state (Running), 4 blocking state (Blocked), 5 waiting state (Waiting), 6 sleep waiting state (timed Waiting), 7 Terminated state (terminated)

Process: After a new thread is created, it is in the newly created state. When a thread is started, the thread enters the ready state. When the thread acquires the resource, it enters the running state, and when the thread is in the blocked state while waiting for the lock, it enters the ready state after acquiring the lock. When the thread executes the wait operation, it enters the waiting state. After being woken up by other threads or after the wait time is up, it enters the ready state to obtain resources and then enters the running state. After executing the sleep operation, the thread enters the sleep waiting state. When the thread finishes running, it enters the terminated state.

31. What is the difference between sleep() and wait()?

        sleep is the method of the thread object, enters the sleep waiting state after execution, and enters the ready state after the sleep time is over. wait is the method of the Object object, and the thread is in the waiting state after execution. Need to be woken up by notify()/notifyAll().

        sleep does not release the lock, wait releases the lock.

32. What is the difference between run() and start() of a thread?

        The start method is used to start the thread, and the run method is used to execute the thread runtime code. The run method can be called repeatedly, but the start method can only be called once.

33. What are the ways to create a thread pool?

        Use ThreadPoolExecutor to create direct submission task queues, bounded task queues, unbounded task queues, and priority task queues according to different parameters.

        In addition, you can use the encapsulated method Executors.newSingleThreadExecutor(), newCachedThreadPool(), newFixedThreadPool(int nThreads), newSingleThreadScheduledExecutor(), newScheduledThreadPool(), newWorkStealingPool(int parallelism) to create;

34. What are the states of the thread pool?

        Running,Shutdown、Stop、Tidying、Terminated

35. What is the difference between submit() and execute() methods in thread pool?

        execute can only execute Runnable type tasks, and submit can execute Runnable or Callable tasks.

36. How to ensure the safety of multi-threaded operation in Java programs?

        Use a lock mechanism, such as a synchronized automatic lock, or manually add a Lock object. And use more class objects under java.util.concurrent.

36. The difference between strong and weak virtual reference types in java

Strong reference: The new object written in the general code is a strong reference, unless null is assigned to the object, it will be recycled by the garbage collection mechanism. Even OOM won't be recycled.

Soft reference (SoftReference): SoftReference<byte[]> softReference = new SoftReference<>(new byte[1024 * 1024 * 10]); Use softReference.get() to obtain. Recycling occurs when memory is insufficient.

Weak Reference (WeakReference): The writing method is the same as soft reference, except that when the garbage collector finds that it is a weak reference, it will be recycled.

Phantom Reference (PhantomReference): It may be recycled by the garbage collection mechanism at any time.

37. What is deadlock? How to prevent deadlock?

        When two threads hold the lock resource that the other is waiting to release, and both are waiting for the other to release the lock, both threads enter a deadlock state. To prevent deadlock, you can use code for synchronization code management such as the Lock interface. And try to set the expiration time when locking.

38. What is ThreadLocal? What are the usage scenarios?

       threadLocal is a thread-private container created on each thread. A thread variable tool that can set and obtain variable information during the entire statement cycle of the thread. Users can pass and obtain parameters in different places inside each thread, and prevent thread safety problems caused by multi-threaded operations on the same data.

        Scenario: When multi-threading operates the database, each thread has its own connection connection information; session management in the web.

39. What is the difference between synchronized and volatile?

        synchronized can modify methods and code blocks. volatile can only modify variables. Synchronized can guarantee visibility atomicity, while volatile can only guarantee visibility.

 40. What is the difference between synchronized and Lock?

        synchroizd can lock the code block of the method (ordinary method and static method), Lock can only lock the code block (using lock to add the effect at the beginning and end of the method is the same as adding a method), synchronized does not need to consider releasing the lock, Lock needs to be manually removed Release to unlock.

41. What is the difference between synchronized and ReentrantLock?

        Synchronized is a modifier that automatically controls locking, and ReentrantLock is an implementation class of Lock, which requires manual code locking and unlocking.

42. Tell me about the principle of atomic?

       atomic mainly uses CAS (Compare And Wwap) and volatile and native methods to ensure atomic operations, thereby avoiding the high overhead of synchronized and greatly improving execution efficiency.

43. What is reflection?

        During the running of the program, you can obtain all the properties and methods of a class, as well as related annotation information through the code, and create an object instance through the class object. And set properties or execute methods through instance objects. This way of manipulating classes and object instances through code is called the reflection mechanism of the Java language.

44. What is Java serialization? When is serialization required?

        Serialization refers to converting the data information, object data type, and object type information in an object into a sequence of bytes. This process is called serialization. Generally, after byte serialization, it can be written to a file or transmitted over the network. Reversely generate objects from serialized byte information, and the reverse generation process is called deserialization.

It needs to be serialized (socket) when writing to a file and when transmitting over the network. (The http request will also be serialized (the one used by RestTemplate is serialized by jackson))

45. What is a dynamic proxy? What are the applications?

         Generate a proxy class for the proxied object during operation. The aspect implementation of spring aop is realized through dynamic proxy (different objects use different processing methods, jdk dynamic proxy or CGLib proxy).

46. ​​How to implement dynamic proxy?

        JDK's native dynamic proxy (Proxy.newProxyInstance) implemented through the interface. Or by inheriting the dynamic proxy of the CGLib method implemented by the current class subclass

47. Why use cloning?

        All attribute values ​​of the new object are initialization values. When we need to create a new object and make its attributes consistent with the current object attributes, it can be achieved by cloning.

48. How to implement object cloning?

        1. By implementing the Cloneable interface, and then rewriting the clone() interface in the interface. 2 Cloning is achieved through serialization and deserialization.

49. What is the difference between deep copy and shallow copy?

         After the deep copy is copied, the reference object in the object is also re-opened for copying. The shallow copy only copies the properties of itself and the basic type, while the properties of the reference type still point to the same reference object as the properties in the copied object. 

       JavaWeb

50. What is the difference between session and cookie?

        Session is server technology stored on the server, while cookie is client technology stored on the browser. A cookie is the cookie information that is set on the browser side before the browser carries the current website when requesting a website. A session is a session information that will be created after the user requests the website for the first time using a browser, and then the information can be read, written and stored in the server session.

There are restrictions on the capacity and size of cookies, but there is no size limit on sessions.

The security of cookies is general, there are forged and modified, common csrf request cross-site forgery problem.

51. Tell me about the working principle of session?

When the user visits a website for the first time, after the page initiates a request to the background, the background judges that there is a session_id, and if not, it will create a session_id and store it in the user's cookie. When the next request comes in, it will carry the session_id previously returned and stored in the cookie. The background will obtain the previous session information according to the session_id in the memory or other configured storage areas for storing sessions, and perform read and write operations.

52. If the client prohibits cookies, can the session still be used?

        Yes, when the user disables the browser cookie, as long as the foreground adds the sessionid parameter to the request parameter when sending the request, the background can also recognize and perform session read and write operations.

53. How to avoid SQL injection?

        Use preprocessing PreparedStatement, such as mybatis's #{} compiled implementation. Special character filtering is performed at the logic layer of the background code.

54. What is an XSS attack and how to avoid it?

        xss is a cross-site scripting attack. The user inserts some scripts and other content into the background database through forms and other methods, and parses the malicious code when the user's input content is displayed on the page, resulting in damage to the page structure or executing js scripts for redirection or other dangerous operations. Preventing XSS requires filtering the content passed in by the user in the back-end interface.

55. What is a CSRF attack and how to avoid it?

        The whole process of csrf is cross-site gold request forgery. Generally, the user logs in to the website A with vulnerabilities, opens the dangerous website B, and there is a malicious request for website A on the page of website B. When the request for website A background is initiated on website B It will carry the cookie information of website A. According to the cookie information, website A cannot know that the current request is initiated by the page of website B, which constitutes a request forgery operation.

To avoid CSRF, you can verify the source referer of the request in the background. Or add token information verification when implementing front-end and back-end interactions.

Guess you like

Origin blog.csdn.net/liuhenghui5201/article/details/125902584