web123456

2021 Java Raid Interview Questions

Article Directory

  • Preface
  • Interview question series article portal
  • Spring Raid Interview Question Content
    • 1. What are the aspects of object-oriented features?
    • 2. What is the mechanism for implementing polymorphism in Java?
    • 3. What is the difference between JDK and JRE?
    • 4. What is the difference between == and equals() method?
    • 5. How to compile and run Java files?
    • 6. What are the basic data types in Java?
    • 7. What is the difference between accessing modifiers public, private, protected and not writing (defualt)?
    • 8. What is the difference between static variables and normal variables?
    • 9. What is the difference between this and super?
    • 10. What is wrong with short s1= 1; s1 = s1+1? short s1 = 1; s1 += 1; What is wrong with short s1 = 1; s1 += 1;
    • 11. Is float type float f=3.4 correct?
    • 12. Tell me the difference between & &&?
    • 13. Is there a length() method for arrays? Is there a length() method for String?
    • 14. What are value passing and reference passing?
    • 15. When modifying a variable with final keyword, is the reference not changed, or is the referenced object not changed?
    • 16. What is the difference between final, finally and finalize?
    • 17. What are the ways to write comments in Java?
    • 18. Is it possible to issue a call to a non-static method from within a static method?
    • 19. 2 * 8 What is the most efficient calculation method?
    • 20. What is the difference between void and Void?
    • 21. Can a ".java" source file include multiple classes that are not internal classes? What are the restrictions?
    • 22. What is the use of static keywords?
    • 23. What is the difference between Integer and int?
    • 24. What are the usages of final keywords?
    • 25. What is the difference between (method overload) Overload and (method overwrite) Override? Can the Overloaded method change the type of the return value?
    • 26. Can abstract methods be static, native and synchronized at the same time?
    • 27. What is (11.5) equal to? What is (-11.5) equal to?
    • 28. What is the difference in syntax between abstract class and interface?
    • 29. Why does byte value range from -128 to 127?
    • 30. Can a Chinese character be stored in a char type variable?
    • 31. What is the difference between overloading and rewriting?
    • 32. Is there a goto in Java?
    • 33. What is the difference between String and StringBuffer?
    • 34. Can the switch statement act on byte, long, and String?
    • 35. How many objects are created in the following statement: String s="a"+"b"+"c"+"d"?
    • 36. Can an inner class reference its members of the containing class? Are there any restrictions?
    • 37. String s = new String("xyz"); How many String objects have been created? Is it possible to inherit the String class?
    • 38. There is a return statement in try {}. Will the code in finally{} immediately following this try be executed, when will it be executed, before or after return?
    • 39. Can int be cast to a variable of type byte? What happens if the value is greater than the range of type byte?
    • 40. What are the similarities and differences between runtime exceptions and general exceptions?
    • 41. What is the difference between List and Map?
    • 42. What are the characteristics of each of the three interfaces List, Map, and Set when accessing elements?
    • 43. Why is there no method like () to add elements to a collection?
    • 44. What is the difference between Iterator and ListIterator?
    • 45. What is the difference between error and exception?
    • 46. ​​Let’s briefly talk about the simple principles and applications of the exception handling mechanism in Java?
    • 47. What is the difference between heap and stack in Java?
    • 48. What are the similarities and differences between ArrayList and Vector?
    • 49. What is the difference between HashMap and HashTable?
    • 50. Tell the storage performance and characteristics of ArrayList, Vector, and LinkedList?
    • 51. What is the difference between Collection and Collections?
    • 52. The elements in the Set cannot be repeated, so what method should be used to distinguish whether they are repeated or not? Should I use == or equals()? What is the difference between them?
    • 53. What is an iterator?
    • 54. What is the difference between hashCode() method and equals() method?
    • 55. What is the difference between a byte stream and a character stream?
    • 56. What is java serialization and how to implement java serialization? (Please explain the role of the Serializable serialization interface?)
    • 57. How to divide streams according to implementation functions?
    • 58. What is the difference between throw and throws in Java?
    • 59. What does the write() method in the node stream (OutputStream) mean? What do the three parameters in the write(byte b[], int off, int len) mean?
    • 60. The stream generally needs to be closed. If it is closed, what method is used? It is generally better to close it in that code block. How to close the stream? If multiple streams call each other and pass it in, how to close it?
    • 61. What does the read() method in the byte input stream (InputStream) return, what does read(byte[] data) mean, and what value is returned?
    • 62. Let me talk about what common collections are?
    • 63. Why does the Map interface not inherit the Collection interface?
    • 64. What is the Collections class?
    • 65. What is the difference between Comparable and Comparator interfaces?
    • 66. How to read files in io streams?
    • 67. What are cookies? What is the difference between Session and Cookies?
    • 68. What is node flow, what is processing flow, what are their uses, and what are the characteristics of the creation of processing flows?
    • 69. Why doesn't Collection inherit from the Cloneable and Serializable interfaces?
    • 70. What different collection views does the Map interface provide?
    • 71. How to decide whether to choose HashMap or TreeMap?
    • 72. What is the difference between ArrayList and LinkedList?
    • 73. What is the working principle of HashMap in Java?
    • 74. What are the best practices for Java collection class frameworks?
    • 75. Java automatic boxing and unboxing?
    • 76. What is the difference between object-oriented and process-oriented?
    • 77. How many ways does Java create objects?
    • 78. What is the difference between a deep copy and a shallow copy of an object cloned?
    • 79. How many types of IO streams are divided in Java?
    • 80. Tell us about the difference between List, Set, and Map?
    • 81. How many ways are there to implement multithreading in Java?
    • 82. What is the use of multi-threading?
    • 83. What is the difference between the start() method and the run() method in the Thread class?
    • 84. What is the difference between Runnable interface and Callable interface?
    • 85. How to ensure the safety of multi-threaded operation in Java programs?
    • 86. What is the function of the volatile keyword?
    • 87. How does Java share data between two threads?
    • 88. What is the producer-consumption model?
    • 89. What is the role of the producer-consumer model?
    • 90. What is the use of ThreadLocal?
    • 91. Why do wait() and notify()/notifyAll() methods be called in synchronization methods or synchronization blocks?
    • 92. What is the difference between the wait() method and the notify()/notifyAll() method when releasing the object monitor?
    • 93. Why use thread pool?
    • 94. What is a thread pool?
    • 95. What are the advantages of thread pools?
    • 96. What are the common ways to create thread pools?
    • 97. What is the difference between sleep() method and wait() method in Java?
    • 98. How to stop a running thread in Java?
    • 99. What is the difference between notify() and notifyAll()?
    • 100. Why are wait(), notify() and notifyAll() methods not in the thread class?
    • 101. What is the difference between interrupted() method and isInterrupted() method in Java?
    • 102. What is the function of the yield() method in the Thread class?
    • 103. If the object's reference is set to null, will the garbage collector immediately release the memory occupied by the object?
    • 104. There are three threads T1, T2, and T3. How to ensure sequential execution?
    • 105. Tell me about your understanding of thread safety?
    • 106. What is the difference between synchronized and ReentrantLock in Java?
    • 107. What is the difference between submit() method and execute() method in Java thread pool?
    • 108. Java class loading process?
    • 109. Describe the principle and mechanism of JVM loading Class files?
    • 110. What is the difference between a process and a thread?
    • 111. What is GC? Why do you need GC?
    • 112. Briefly describe the Java garbage collection mechanism?
    • 113. What will () and () do?
    • 114. What are the advantages and principles of garbage recycling? And consider 2 recycling mechanisms?
    • 115. What is the basic principle of a garbage collector (object reference traversal)? Can the garbage collector recycle memory immediately? Is there any way to actively notify the virtual machine for garbage collection?
    • 116. Will there be a memory leak in Java? Please give a brief description?
    • 117. How to determine whether an object survives? (Or how to determine GC objects?)
    • 118. When is the finalize() method called? What is the purpose of destructor (finalization)?
    • 119. What is the difference between SynchronizedMap and ConcurrentHashMap?
    • 120. What is distributed garbage collection (DGC)? How does it work?
    • 121. What is the difference between a serial collector and throughput collector?
    • 122. In Java, when can objects be garbage collected?
    • 123. Let me talk about what garbage collection algorithms do JVM have?
    • 124. What is a class loader and what are class loaders?
    • 125. Classloader parent delegation model mechanism?
    • 126. Comparison of PrintStream, BufferedWriter, PrintWriter?
    • 127. Which is better, byte stream or character stream? How to choose?
    • 128. Briefly describe the java memory allocation and recycling rate, as well as Minor GC and Major GC?
    • 129. What is a buffer? What is its function?
    • 130. What kind of stream does BufferedReader belong to? What are its main uses for? What classic methods are there in it?


Preface

As a fresh graduate, I am looking for a job. The interview questions that were just sorted out in February this year were too fast to sort by module classification. In short, the order is quite chaotic, I hope everyone will be patient. If you really mind, please let me know about it and I will make changes depending on the situation. In addition, if you think the answer I am looking for is not clear enough, you are welcome to send a private message or comment only, and I will modify it if I see it!


Interview question series article portal

2021 Backend Development Interview Questions Compilation


Spring Raid Interview Question Content

1. What are the aspects of object-oriented features?

Object-oriented features include abstraction, inheritance, encapsulation, and polymorphism.

  1. Abstract: Abstract is the process of summarizing the common characteristics of a class of objects into constructing classes, including data abstraction and behavior abstraction. Abstraction only focuses on what attributes and behaviors the object has, and does not pay attention to what the details of these behaviors are.
  2. Inheritance: Inheritance is the process of obtaining inherited information from existing classes to create new classes. The class that provides inherited information is called the parent class, and the class that obtains inherited information is called the child class.
  3. Encapsulation: Encapsulation is to bind data to the method of operating data, and access to data can only be achieved through the defined interface.
  4. Polymorphism: Polymorphism allows objects of different subtypes to respond differently to the same message, which can be divided into compile-time polymorphism and run-time polymorphism.

2. What is the mechanism for implementing polymorphism in Java?

  1. Polymorphism refers to pointing to a subclass by reference to the parent class or interface, thereby realizing the characteristics of an object having multiple forms.
  2. The reference of the parent class dynamically points to a specific instance when the program is running. When calling the referenced method, it is not run based on the method defined in the type of the reference variable, but based on the specific instance method.
  3. The mechanisms for implementing polymorphism in Java include inheritance, abstract classes, interfaces, method overloading, method rewriting, etc. Overloading of polymorphism usage methods at compile time, overwriting of polymorphism usage methods at runtime.

3. What is the difference between JDK and JRE?

JRE is the Java runtime environment and the Java program that will be executedVirtual Machine, and also includes browser plug-ins required for executing the program.
JDK is a complete Java software development toolkit that includes JRE, which allows developers to develop, compile and execute Java applications.

4. == andequals() The difference between methods?

== : Its function is to judge whether the addresses of two objects are equal and whether the two objects are equal. The basic data type compares the value through ==, and the reference data type compares the memory address through ==.
equals() method: Its function is to judge whether two objects are equal. There are generally two usage situations:
The class does not override the equals() method. When comparing two objects of the class through the equals() method, it is equivalent to comparing by "==".
The class overrides the equals() method, and compares whether the contents of two objects are equal by the equals() method. If their contents are equal, return true, otherwise false.

5. How to compile and run Java files?

Use the javac command to compile .java files (for example), and after running, the corresponding files will be produced
Use Java commands to run java files

6. What are the basic data types in Java?

Integer types include byte, short, int, long, floating point types include float, double, character types include char, boolean

7. Access modifier public,privateThe difference between protecting and not writing (defualt)?

In Java, access modifiers can be used to protect access to classes, variables, methods and constructors, and supports 4 different access permissions.

  1. private: visible within the same class, use objects: variables, methods, and cannot modify external classes
  2. default: visible in the same package, without using any modifiers, uses objects: classes, interfaces, variables, methods.
  3. protected: It is visible to classes and all subclasses in the same package. Objects: variables, methods, and external classes cannot be modified.
  4. public: visible to all classes, using objects: classes, interfaces, variables, methods

8. Static (static) What is the difference between a variable and a normal variable?

  1. Different targets: static variables belong to the class variables, ordinary variables belong to the object variables
  2. Different storage areas: static variables are stored in the static area of ​​the method area, and ordinary variables are stored in the heap area
  3. Different life cycles: Static variables are loaded as the class is loaded and disappear as the class disappears. Normal variables are loaded as the object is loaded and disappear as the object disappears.
  4. Different calls: static variables can only be called through class names, ordinary variables can only be called through objects

9. What is the difference between this and super?

this: represents the current object itself, super: represents the parent class of the current object.

10. What is wrong with short s1= 1; s1 = s1+1? short s1 = 1; s1 += 1; What is wrong with short s1 = 1; s1 += 1;

For s1=s1+1, because 1 is an int type, when s1+1 performs operations, the result will be automatically upgraded and converted to int type. And s1 is a short type, and a type conversion error will be reported. In addition, since s1+=1 contains casting, it will not be wrong.

11. Is float type float f=3.4 correct?

The accuracy is inaccurate and should be cast. For example float f=(float)3.4

12. Tell me the difference between & &&?

& is a bit operator, representing bitwise and operation, && is a logical operator, representing logic and

13. Is there a length() method for arrays? Is there a length() method for String?

The array does not have a length() method, but has a length attribute. String has the length() method

14. What are value passing and reference passing?

Value transfer is for variables of the basic data type. It is passed a copy of the variable. Changing the copy does not affect the original variable. It is generally believed that passing in java is all value passing.
Reference transfer is for object-type variables. It is passed a copy of the object address, not the original object itself. Therefore, operating on the reference object will change the original object at the same time.

15. When modifying a variable with final keyword, is the reference not changed, or is the referenced object not changed?

When modifying a variable with the final keyword, it means that the reference variable cannot be changed, and the content in the object pointed to by the reference variable can be changed. In short, for a final variable, if it is a variable of the basic data type, its value cannot be changed after initialization; if it is a variable of reference type, it cannot point to another object after initialization.

16. What is the difference between final, finally and finalize?

  1. Final can modify classes, variables, and methods. When modifying a class, it means that the class cannot be inherited, when modifying a method, it means that the method cannot be rewritten, and when modifying a variable, it means that the variable is a constant and cannot be reassigned.
  2. Finally generally acts in the try-catch code block. When handling exceptions, the code that must be executed is usually placed in the finally code block. It means that no matter whether an exception occurs, the code block will be executed, and is generally used to store some code that closes the resource.
  3. finalize is a method of the Object class, which is used to implement garbage collection. When the garbage collector executes, the finalize() method of the recycled object will be called. This method can be overridden to realize the recycling of other resources.

17. What are the ways to write comments in Java?

Single line comment //
Multi-line comment/* comment…/
Multi-line comments for commenting documents/
* Comments… */

18. Is it possible to issue a call to a non-static method from within a static method?

Non-static methods cannot be called directly within the static method, because there is no need to create an object when the static method is called, and the non-static method needs to create an object before it can be called. To call a non-static method inside a static method, you can create an object inside the static method and then call the non-static method through the object.

19. 2 * 8 What is the most efficient calculation method?

Since bit operators are directly supported by CPU and are most efficient, the most efficient way to calculate 2 * 8 is 2 << 3 (read as right shift 3 bits or 2 two less than signs 3)

20. What is the difference between void and Void?

void method definition for no return value
Void is a wrapping method of void. Unlike other basic types of wrapping methods, Void cannot be instantiated. Void can also be used for methods or generics that always return null.

21. Can a ".java" source file include multiple classes that are not internal classes? What are the restrictions?

It can contain multiple classes that are not internal classes, but only one class name is the same as the file name.

22. What is the use of static keywords?

The static keyword can be used to modify inner classes, class member methods, class member variables, and static static code blocks.

23. What is the difference between Integer and int?

  1. Integer is a wrapper class for int, and int is one of the basic data types of Java. Integer variables must be instantiated before they can be used, while int variables do not.
  2. Integer is a reference to an object. When new an Integer, it actually generates a pointer to point to this object, while int directly stores the data value.
  3. The default value of Integer is null, and the default value of int is 0

24. What are the usages of final keywords?

The final keyword can modify classes, variables, and methods. When modifying a class, it means that the class cannot be inherited, and the modification method means that the method cannot be rewritten. When modifying a variable, it means that the variable is a constant and cannot be reassigned.

25. What is the difference between (method overload) Overload and (method overwrite) Override? Can the Overloaded method change the type of the return value?

Rewriting and overloading are different manifestations of Java polymorphism. Rewriting means that the subclass has the same name and parameters as the parent class. Overloading means that multiple methods with the same name are defined in a class but the parameters returned are different. The Overloaded method cannot change the return value type

26. Can abstract methods be static, native and synchronized at the same time?

None.

  1. abstract refers to abstract methods. Only method declarations do not implement methods and cannot be called directly.
  2. static is a class method. It can be called directly by the class without generating instances of the class. The abstract method cannot be called, so static and abstract cannot be used at the same time.
  3. native is used to declare local methods, which are generally used for the interaction between Java and external environment. It is similar to abstract methods, only method declarations do not implement methods, native and abstract themselves conflict, so they cannot be used at the same time.
  4. Synchronized is a synchronization method, but synchronization requires specific operations to be implemented. However, abstract only has method declarations and cannot achieve synchronization, so static and synchronized cannot be used at the same time.

27. What is (11.5) equal to? What is (-11.5) equal to?

The method means "rounding", that is, add the original number 0.5 and then round it downwards, so the result of (11.5) is 12, and the result of (-11.5) is -11.

28. What is the difference in syntax between abstract class and interface?

  1. Abstract classes can contain constructors, but interfaces cannot contain constructors;
  2. An abstract class can contain ordinary member variables, and the interface cannot contain ordinary member variables; an abstract class can contain non-abstract ordinary methods, and all methods in the interface must be abstract.
  3. The access type of abstract methods in abstract classes can be public or protected, but the abstract methods in the interface can only be public type, and default to public abstract type.
  4. Abstract classes can contain static methods, and interfaces cannot contain static methods.
  5. Both abstract classes and interfaces can contain static member variables. The access type of static member variables in abstract classes is arbitrary, but the static member variables in interfaces can only be public static final types.

29. Why does byte value range from -128 to 127?

In Java, the byte type is 1 byte, and 1 byte accounts for exactly 256 numbers in 8 bits, and -128 to 127 are also 256 numbers.

30. Can a Chinese character be stored in a char type variable?

In Java, unicode is encoded, and a char type variable accounts for 16 bytes, so it is no problem to put a Chinese text.

31. What is the difference between overloading and rewriting?

Both overloading and rewriting are ways to implement polymorphism. The difference is that overloading implements compile-time polymorphism, while rewriting implements run-time polymorphism.

32. Is there a goto in Java?

goto is a reserved word in the java language and is not used in java at present.

33. What is the difference between String and StringBuffer?

  1. Once declared, the content of the String class is unchangeable. All it changes is the memory pointing, while the object content of the StringBuffer class can be changed.
  2. A String object cannot be modified means that the object itself cannot be modified, rather than a reference cannot be modified.
  3. For StringBuffer, object instantiation cannot be done directly by assignment like String, but must be done by constructing methods. When performing string processing, the StringBuffer class does not generate new objects, which is better than the String class in memory usage. When using it in practice, if you often need to modify a string, such as insertion, deletion, etc., it is more suitable to use StringBuffer.

34. Can the switch statement act on byte, long, and String?

The switch can act on byte, int, String and enum types, and cannot act on long types.

35. How many objects are created in the following statement: String s="a"+"b"+"c"+"d"?

Only one object is created, and the expressions that directly add string constants are optimized during compilation are not necessary to wait until the runtime to perform addition operations. Instead, remove the plus signs during compilation and directly compile it into a constant-concatenated result, such as String s = "abcd".

36. Can an inner class reference its members of the containing class? Are there any restrictions?

It's totally OK, if it's not a static inner class, there's no limit. If a static nested class is regarded as a special case of an inner class, in this case, the normal member variable of the outer class cannot be accessed, and only static member variables in the outer class can be accessed. There are 4 internal categories.

  1. Static inner classes are modified with static keywords. In terms of access restrictions, only member variables or methods modified by static keywords in external classes can be accessed.
  2. Member inner class is the most common inner class, which can unconditionally access all member properties and member methods of external classes (including private members and static members)
  3. Local inner classes are defined in methods of external classes and can access all members of external classes. However, local variables cannot be accessed casually unless the local variable is modified by the final keyword
  4. Anonymous internal classes are actually the abbreviation format of local internal classes and can only be used once.

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

Generate two objects. One is the string constant xyz stored in the constant pool, and the other is generated by new and stored in the heap. The String class is an immutable class and cannot be inherited.

38. There is a return statement in try {}. Will the code in finally{} immediately following this try be executed, when will it be executed, before or after return?

The code in finally behind the try will be executed, and the execution time is in front of the return.

39. Can int be cast to a variable of type byte? What happens if the value is greater than the range of type byte?

Can be converted. If the value of type int is greater than the range of type byte, the high bit of type int will be discarded.

40. What are the similarities and differences between runtime exceptions and general exceptions?

Checked exception is a general exception, such as IO exceptions and SQL exceptions. For this exception, the JAVA compiler enforces a try-catch.
Runtime exception is a runtime exception, and you can choose not to handle it. When such an exception occurs, it will always be taken over by the virtual machine. After a runtime exception occurs, the system will throw the exception to the upper layer and continue to encounter processing code. If there is no processing block, it will go to the upper layer. If it is multi-threaded, it will be thrown by the () method. If it is a single thread, it will be thrown by the main() method. If it is an exception thrown by the thread, the thread exits. If it is an exception thrown by the main program, the entire program also exits.

41. What is the difference between List and Map?

List: is a collection of data stored in single columns, and the stored data is ordered and repeatable.
Map: It is a collection of dual-column data. Data is stored through key-value pairs, and the stored data is disordered. The key value cannot be repeated, the value value can be repeated, and the key and value correspond one by one.

42. What are the characteristics of each of the three interfaces List, Map, and Set when accessing elements?

  1. List has an order of placement when accessing elements, and elements can be repeated
  2. When accessing elements of Map, it is stored by key-value pairs, and there is no order of placement.
  3. When the elements are accessed, there is no order of elements placed, and elements cannot be repeated.

43. Why is there no method like () to add elements to a collection?

Iterator cannot ensure the order of iterations, so add operations are required. ListIterator does not provide an add operation because it ensures the order of iterations.

44. What is the difference between Iterator and ListIterator?

  1. Iterator can traverse Set and List collections, while ListIterator can only traverse List collections.
  2. Iterator can only traverse forward, ListIterator can traverse in both directions.
  3. ListIterator inherits from the Iterator interface and has some additional features, such as adding an element, replacing an element, and getting the index position of the previous or subsequent elements.

45. What is the difference between error and exception?

Exception and Error are both inherited from the Throwable class. In Java, only instances of the Throwable type can be thrown or caught. It is the basic component type of the exception handling mechanism.
Exception is an expected exception during Java program operation, which can be obtained and processed outside of business.
Error is an unpredictable exception in Java program operation. After this exception occurs, it will directly lead to the JVM being unprocessed or unrecoverable, so this exception cannot be caught.

46. ​​Let’s briefly talk about the simple principles and applications of the exception handling mechanism in Java?

  1. Exceptions refer to abnormal situations or errors that occur when Java programs run. Java classifies exceptions, and different types of exceptions use different java classes, and the root class of all exceptions is. Throwable derives 2 subclasses: Error and Exception.
  2. Error indicates a serious error that the program itself cannot overcome and recover. Exception means that the program itself can overcome and recover exceptions. Exception is divided into system exceptions and ordinary exceptions.
  3. System exceptions are problems caused by defects in the software itself, that is, problems caused by inadequate consideration of software development problems, such as array out-of-bounds problems, null pointer exceptions, class conversion exceptions, etc. Users cannot overcome and restore this problem, but in this case, they can choose to keep the software running or stop running.
  4. Ordinary exceptions are problems caused by changes in the operating environment or abnormalities, and are problems that users can overcome, such as network disconnection, insufficient hard disk space, etc.

47. What is the difference between heap and stack in Java?

  1. Stack memory is used to store local variables and method calls, and heap memory is used to store objects in Java. Whether it is member variables, local variables or class variables, the objects they point to are stored in heap memory, and the stack memory is much smaller than the heap memory.
  2. Stack memory belongs to a single thread, each thread will have a stack memory, and the variables it stores can only be visible in the thread to which it belongs. Stack memory can be understood as the private memory of the thread.
  3. Objects in heap memory are visible to all threads and can be accessed by all threads.

48. ArrayList andVectorWhat are the differences and differences?

Similarities:
ArrayList and Vector are both index-based and are implemented through arrays internally, both implementing the List interface and allowing null values.
Both ArrayList and Vector maintain the order of insertion, and can obtain elements according to the order of insertion and access elements randomly according to the index value.
Differences:
Vector is synchronous and thread-safe, but ArrayList is not.
ArrayList performs faster than Vector because the thread synchronization of Vector affects performance to a certain extent.

49. What is the difference between HashMap and HashTable?

  1. HashMap allows key and value to be empty, but HashTable does not.
  2. The default capacity of HashTable is 11, and the default capacity of HashMap is 16.
  3. When HashTable expands capacity, change the capacity to the original 2 times plus 1. When HashMap expands capacity, change the capacity to the original 2 times.
  4. HashTable is synchronous and thread-safe, suitable for multi-threaded environments. HashMap is non-threaded and suitable for single-threaded environments.
  5. HashMap and HashTable are both implemented based on hash tables. Each element is a key-value key-value pair. The conflict problem is resolved internally through a single linked list, and both implement the Serializable serialization interface.

50. Tell the storage performance and characteristics of ArrayList, Vector, and LinkedList?

  1. ArrayList and Vector both use arrays to store data. The number of elements in this array is greater than the actual number of data stored in order to increase and insert elements. They all allow indexing elements directly by sequence numbers, but inserting elements involves memory operations such as array element movement, so indexing data is fast and inserting data is less efficient.
  1. Vector's performance is worse than ArrayList because it uses synchronized synchronization method.
  2. LinkedList uses a two-way linked list to store. Indexing data by sequence number requires forward or backward traversal, but when inserting data, only the front and back items of this item need to be recorded, so the insertion speed is faster.
  3. LinkedList is not thread-safe and provides some methods that enable LinkedList to be used as a heap, stack, and queue.

51. What is the difference between Collection and Collections?

  1. Collection is the upper-level interface of the collection class, and the interfaces inherited from it are mainly List and Set.
  1. Collections is a help class for collection classes, providing a series of static methods to implement search, sorting, thread-safe operations on various collections.
  2. The main methods of Collections are: Shuffling, Reverse, Fill, Copy, Sort, etc.

52. The elements in the Set cannot be repeated, so what method should be used to distinguish whether they are repeated or not? Should I use == or equals()? What is the difference between them?

Set is a subinterface of the Collection container. It does not allow duplicate elements to appear. Whether the elements are duplicated is determined using the equals() method.
(See the above for the difference between == and equals() method)

53. IteratorWhat is (Iterator)?

The iterator interface provides many methods to iterate on set elements, and each collection class contains iterative methods that can return iterator instances.
The iterator can delete elements of the underlying collection during iteration and delete them through the iterator's remove() method.

54. What is the difference between hashCode() method and equals() method?

The hashCode() method and the equals() method are both used to compare whether two objects are equal. The hashCode() method only needs to compare the hash values ​​of the two objects, which is relatively efficient. But the hashCode() method is unreliable, and the hash values ​​of two different objects are likely to be the same. Therefore, it is necessary to use the equals() method to make further equality judgment. If the equals() method is equal, the hashCode() method must be equal, while the hashCode() method is equal but the equals() method is not necessarily equal.

55. What is the difference between a byte stream and a character stream?

The byte stream will not use a buffer during operation, it is operated directly by the file itself, while the character stream uses a buffer during operation, and the file is operated through the buffer. The biggest advantage of character streams is that they can effectively process Chinese. If there is Chinese processing in daily development, they will use character streams. If there is no recommended use of byte streams.
(No need to memorize, the buffer used for auxiliary understanding can be simply understood as a memory area)

56. What is java serialization and how to implement java serialization? (Please explain the role of the Serializable serialization interface?)

Serialization is a mechanism used to process object flow, streaming the content of the object, allowing the streamed object to be read and written and transmitted between the network. Serialization is to solve the problems caused by object flow read and write operations. The implementation of serialization is to implement the Serializable interface to the class that needs to be serialized. This interface does not have a method to implement, but is just to mark the object that can be serialized. Then use an output stream (FileOutputStream) to construct an object stream (ObjectOutputStream) object, and the object of the parameter can be written out through the write() method of the object stream object

57. How to divide streams according to implementation functions?

  1. Streams are divided into node streams (OutputStream) and processing streams (OutputStreamWriter) according to their implementation functions.
  2. The node stream is directly connected to the data source and is used for input or output.
  3. Processing flow is based on node flow and some functions are extended.

58. What is the difference between throw and throws in Java?

  1. throw and throws are both ways to passively handle exceptions, only throw or may throw exceptions, but the function will not handle exceptions. The real exception handling is handled by the upper-level call of the function.
  2. throw is used to throw a specific exception type. throws is a declared method and may throw an exception.
  3. throws appears in the method function header, throw appears in the method function body.
    1. throws indicates a possibility of an exception, which does not necessarily occur. throw must throw some exception.

59. What does the write() method in the node stream (OutputStream) mean? What do the three parameters in the write(byte b[], int off, int len) mean?

Write() method passes the specified bytes into the data source, the byte array represents data, the int off represents the beginning of the data offset, and the int len ​​represents the number of bytes written

60. The stream generally needs to be closed. If it is closed, what method is used? It is generally better to close it in that code block. How to close the stream? If multiple streams call each other and pass it in, how to close it?

Once the stream is opened, it must be closed. Use the close method to put it into the finally statement block to perform the closing. The process flow is called, and if multiple streams call each other, only the outermost stream is closed.

61. What does the read() method in the byte input stream (InputStream) return, what does read(byte[] data) mean, and what value is returned?

The read() method of InputStream stores the read bytes in the byte array, and returns the number of parameters passed in the array.

62. Let me talk about what common collections are?

  1. The sub-interfaces of the Collection interface include: Set interface and List interface;
  2. The main implementation classes of the Map interface are HashMap, TreeMap, HashTable, and ConcurrentHashMap.
  3. The main implementation classes of Set interface are: HashSet, TreeSet, LinkedHashSet
  4. The implementation classes of List interface are mainly: ArrayList, LinkedList, Stack, Vector

63. Why does the Map interface not inherit the Collection interface?

Because Map provides key-value pair mappings, while collection provides a set of arrays, the Map interface does not inherit the Collection interface.

64. What is the Collections class?

Collections is a help class for collection classes, providing a series of static methods to implement search, sorting, thread-safe operations on various collections.
The main methods of Collections are: Shuffling, Reverse, Fill, Copy, Sort, etc.

65. What is the difference between Comparable and Comparator interfaces?

The Comparable interface is used to provide natural sorting of objects, which can be used to provide sorting based on a single logic.
The Comparator interface is used to provide different sorting algorithms, and you can select the Comparator interface you need to use to sort a given object collection.

66. How to read files in io streams?

io stream uses File object to get file path, through character streamReaderAdd the file, use the character buffer stream BufferedReader to process the Reader, and finally define a string to loop through the output file.

67. What are cookies?SessionWhat is the difference between cookies?

  1. Cookies are one of the specifications of the HTTP protocol. They are a key-value pair and are data stored by the server on the client. Its process is that the server transmits the cookie to the client through a response header, and the client saves the cookie. When the client requests the same server again, add the cookie saved on the client in the request header and send it to the server.
  2. Session technology writes user data into user-owned sessions and saves them on the server.
  3. Cookies can only store text and their size is limited to 4KB. Session can save any type of data, but it will occupy server memory, so you should fully consider it when using it.

68. What is node flow, what is processing flow, what are their uses, and what are the characteristics of the creation of processing flows?

The node stream is directly connected to the data source and is used for input or output
Processing flow processing and some functions are expanded based on node flow
The constructor that processes the stream must pass into the subclass of the node stream

69. Why doesn't Collection inherit from the Cloneable and Serializable interfaces?

Collection means that a collection contains a set of objects, and how these objects are stored and maintained is determined by the specific implementation. Because the specific forms of a collection are diverse, for example, List collection allows elements to be repeated, Set collection does not. Collection is an abstract expression, and what is important is implementation. When dealing with specific implementations, cloning or serialization can only play a role. Whether the specific implementation class of Collection can be cloned or serialized should be determined by itself.

70. What different collection views does the Map interface provide?

  1. The Map interface provides three collection views, none of which supports add and addAll operations.
  2. Set type keySet() method: The map returned by this method contains a Set view of all keys,
  3. Collection type values() method: The map returned by this method contains a Collection view of all values.
  4. entrySet() method: The map returned by this method contains a collection view of all maps.

71. How to decide whether to choose HashMap or TreeMap?

HashMap is suitable for inserting, deleting and positioning elements in the map, and TreeMap is suitable for traversing an ordered collection of keys.

72. What is the difference between ArrayList and LinkedList?

ArrayList supports random access while LinkedList does not.
ArrayList is implemented through an array, and insertion and deletion will be affected by the element position and will cause shifts. LinkeList uses a two-way linked list to store data, and insertion and deletion are not affected by element location.
ArrayLIst will reserve a certain amount of space, and the actual space of the array is smaller than the storage space. The linkedlist will not reserve space. Only when the element is added will the corresponding memory space of this element be applied.
The frequent search efficiency of ArrayList is higher than that of LinkedList, and the frequent insertion and deletion efficiency of LinkedList is higher than that of Arraylist.

73. What is the working principle of HashMap in Java?

HashMap is based on the principle of hashing, using the put() method to store objects and using the get() method to obtain objects. When passing keys and values ​​to put() method, first call hashCode() method on the key, and the returned hashCode is used to find the bucket location to store the Entry object. HashMap is a bucket that stores key objects and value objects as.

74. What are the best practices for Java collection class frameworks?

If the size of the element is fixed and can be known in advance, Array instead of ArrayList should be used.
Some collection classes allow for specifying the initial capacity. If the number of stored elements can be estimated, the initial capacity can be set to avoid recalculating the hash value or expanding it.
In the case where the underlying collection is actually empty, return a set or array of length 0 instead of null, avoiding null pointer exceptions.

75. Java automatic boxing and unboxing?

Automatic boxing is to automatically convert the basic data type to the wrapper type, such as calling the valueOf() method of Integer to convert the int type to the Integer type
Automatic unboxing means automatically converting the wrapper type to the basic data type, such as calling Integer's intValue() method to convert the Integer type to the int type

76. What is the difference between object-oriented and process-oriented?

Process-oriented: It is a step to analyze and solve problems. Use functions to implement these steps step by step, and then call them one by one when used, which has higher performance.
Object-oriented: It is to break down the things that constitute the problem into various objects. The purpose of establishing an object is not to complete one step at a time, but to describe the behavior of a thing in the process of solving the entire problem. Object-oriented has encapsulation, inheritance, and polymorphic characteristics, so it is easy to maintain, reuse and expand. Object-oriented can design low-coupling systems, but their performance is lower than process-oriented.

77. How many ways does Java create objects?

  1. Create new object through new
  2. Through reflection mechanism
  3. Adopt clone mechanism
  4. Through the serialization mechanism

78. What is the difference between a deep copy and a shallow copy of an object cloned?

Shallow copy: When copying an object, only the variables of the object itself and the basic data type are copied, but not the variables of the reference type are copied.
Deep copy: When copying an object, not only the object itself, but also all variables (including variables of reference type)

79. How many types of IO streams are divided in Java?

  1. According to the flow direction of the IO stream, it can be divided into input stream and output stream;
  2. According to the operation unit of the IO stream, it can be divided into byte stream and character stream;
  3. According to the implementation functions of IO streams, they can be divided into node streams and processing streams.

80. Tell us about the difference between List, Set, and Map?

  1. The elements stored in the List collection are ordered and can be repeated.
  2. Set is a collection that does not allow elements to be repeated.
  3. Map collections are stored using key-value pairs. The key value cannot be repeated, the value value can be repeated, and the key and value correspond one by one.

81. How many ways are there to implement multithreading in Java?

  1. Inherit the Thread class;
  2. Implement the Runnable interface;
  3. Implement the Callable interface;

82. What is the use of multi-threading?

  1. Take advantage of multi-core CPU
  2. Prevent thread blocking
  3. Easy to model

83. What is the difference between the start() method and the run() method in the Thread class?

A thread is started by starting() method. At this time, the thread is in a ready state and can be scheduled and executed by the JVM. During the scheduling process, the JVM completes business logic by calling the run() method. The thread will terminate at the same time as the run() method ends, so the purpose of multi-threading can be achieved through the start() method.
If the run() method is called directly, it will be called as an ordinary method, and there is still only the main thread in the program. The code is still executed synchronously. You must wait for the code in the run() method of a thread to be executed before another thread can execute the code in its run() method, which cannot achieve the purpose of multi-threading.

84. What is the difference between Runnable interface and Callable interface?

Similarities: both the runnable interface and the callable interface can write multi-threaded programs, and both use the () method to start threads.
Differences:
The run() method of the Runnable interface has no return value, and can only throw a runtime exception and cannot be caught and processed.
The call() method of the Callable interface has a return value, allowing exceptions to be thrown, and exception information can be obtained.

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

  1. Use security classes, such as the AtomicInteger class.
  2. Use automatic locks, such as synchronized.
  3. Use manual lock, Lock.

86. What is the function of the volatile keyword?

There are three characteristics in Java multi-threading development: atomicity, visibility and orderliness. The main function of the volatile keyword is to ensure memory visibility and prevent instruction reordering. Variables modified with volatile keyword ensure visibility between multiple threads, that is, the volatile variables read each time must be the latest data. The volatile keyword can also be combined with CAS to ensure atomicity, such as the AtomicInteger class.

87. How does Java share data between two threads?

Abstract the data to be shared into a class, and take the operation of shared data as a method of this class, and then add the synchronized keyword to the method.
Use the Runnable object as the inner class of a class and the shared data as the member variable of this class. Each thread encapsulates the operation method of the shared data in the external class. In order to achieve synchronization and mutual exclusion of various operations of the data, these methods of the external class are called as various Runnable objects of the inner class.

88. What is the producer-consumption model?

Take products as an example. When the queue space is full, the producer needs to wait for the queue to have free space before continuing to put products into it. During the waiting period, the producer must release the right to occupy critical resources. If the producer does not release critical resources, the consumer will be unable to consume the goods in the queue, and the queue will not have spare space, and the producer will wait infinitely. Therefore, when the queue space is full, the producer will hand over the occupancy rights of critical resources and enter a suspended state, and then wait for the consumer to consume the product and notify the producer of the queue to have free space. When the queue has free space, consumers must also wait for the producer's notification to consume the goods. This process of communication with each other is the producer-consumer model.
(No need to remember: critical resources are queues)

89. What is the role of the producer-consumer model?

This is the most important role of the producer-consumer model by balancing the production capacity of producers and consumers' consumption capacity to improve the operating efficiency of the entire system.
Decoupling, decoupling means that there are fewer connections between producers and consumers, but the fewer connections, the more they can develop on their own without being restricted by each other. This is the role of the producer-consumer model.

90. What is the use of ThreadLocal?

ThreadLocal is a practice of exchanging space for time. One is maintained in each Thread to isolate the data. If the data is not shared, there will naturally be no thread safety issues.

91. Why do wait() and notify()/notifyAll() methods be called in synchronization methods or synchronization blocks?

Because when a thread calls the wait() method of an object, the thread must have the lock of the object, and then it will release the lock and enter the waiting state until other threads call the notify() method on the object. When a thread needs to call the object's notify() method, it will release the object's lock, and other threads waiting for this object can get the object lock. Since both the wait() method and the notify()/notifyAll() method require the thread to hold the object's lock and can only be implemented through synchronization, they can only be called in the synchronization method or the synchronization block.

92. What is the difference between the wait() method and the notify()/notifyAll() method when releasing the object monitor?

The wait() method immediately releases the object monitor
The notify()/notifyAll() method will wait for the remaining code of the thread to be executed before releasing the object monitor.

93. Why use thread pool?

Using thread pools can avoid frequent creation and destruction of threads.
Using thread pools allows you to flexibly control the number of concurrency based on your project.

94. What is a thread pool?

A thread pool is to create multiple executable threads in advance and put them into a container. When needed, it is obtained from the container without creating it yourself. When threads are used, they do not need to destroy threads but put them back into the container, thereby reducing the overhead of creating and destroying thread objects.

95. What are the advantages of thread pools?

  1. Reduce resource consumption, reuse existing threads, and reduce the overhead of creating and destroying threads.
  2. Effectively control the maximum number of concurrent threads to improve response speed and system resource utilization.
  3. Threads are scarce resources. If created without limitations, they will not only consume system resources, but also reduce system stability. Using thread pools can uniformly allocate, tune and monitor resources, improving thread manageability.
  4. Provides functions such as timed execution, regular execution, single threading, concurrent number control, etc.

96. What are the common ways to create thread pools?

  1. newSingleThreadExecutor method: This method creates a single-thread thread pool. There is only one thread working in this thread pool, which is equivalent to a single-thread serial execution of all tasks. If this unique thread ends due to an exception, a new thread will be replaced. This thread pool ensures that the execution order of all tasks is executed in the order of the task submission.
  2. newFixedThreadPool method: This method creates a fixed-size thread pool. Each time a task is submitted, a thread is created until the number of threads reaches the maximum value of the thread pool. The thread pool size remains the same once it reaches its maximum value. If a thread ends due to an execution exception, the thread pool will add a new thread.
  3. newCachedThreadPool method: This method creates a cacheable thread pool. If the size of the thread pool exceeds the thread required to process the task, some of the free threads will be recycled. When the number of threads required by a task increases, new threads can be intelligently added to handle the task. This thread pool does not limit the thread pool size, which depends entirely on the maximum number of threads that the operating system can create.
  4. newScheduledThreadPool method: This method creates a thread pool with unlimited size, which supports thread execution or regular execution.

97. What is the difference between sleep() method and wait() method in Java?

Both the sleep() method and the wait() method can pause the execution of the thread, the difference is:

  1. Different classes: The sleep() method is a static method of the Thread thread class, and the wait() method is a method of the Object class.
  2. Whether to release the lock: the sleep() method does not release the lock; the wait() method releases the lock.
  3. Different uses: the wait() method is usually used for communication between threads, and the sleep() method is usually used to pause execution.
  4. Different usages: After the wait() method is called, the thread will not automatically wake up before timeout, unless another thread calls the notify() method or notifyAll() method on the same object. After the sleep() method is executed, the thread will automatically wake up.

98. How to stop a running thread in Java?

  1. After waiting for the run() method to complete, the thread will terminate.
  2. Use the stop() method to force the thread to terminate, but it is not recommended because the stop() method is an expired method.
  3. Use interrupt() method to interrupt the thread.

99. What is the difference between notify() and notifyAll()?

Let’s talk about two concepts first: lock pool and waiting pool
Lock pool: Assume that thread A already owns the lock of an object, and other threads must first obtain ownership of the lock of the object before calling a synchronized method of this object. However, the lock of the object is owned by thread A, so these threads enter the lock pool of the object to compete.
Waiting pool: Suppose thread A calls the wait() method of an object, and after thread A releases the lock of the object, it enters the waiting pool of the object.
The difference between notify() method and notifyAll() method:
If the thread calls the wait() method of the object, the thread will be in the waiting pool of the object, and the thread in the waiting pool will not compete for the lock of the object.
If the thread calls the object's notify() method or notifyAll() method, the awakened thread will enter the object's lock pool, and the thread in the lock pool will compete for the object's lock. That is to say, after calling the notify() method, as long as there is a thread, it will enter the lock pool from the waiting pool, and the notifyAll() method is to move all threads in the waiting pool to the lock pool, waiting for lock competition.

100. Why are wait(), notify() and notifyAll() methods not in the thread class?

Simply put, since wait(), notify() and notifyAll() methods are lock-level operations, they are defined in the Object class because the lock belongs to the object.

101. What is the difference between interrupted() method and isInterrupted() method in Java?

  1. The main difference between interrupted() and isInterrupted() is that the former will interrupt the state while the latter will not.
  2. When the interrupt thread calls the static method () to check the interrupt state, the interrupt state will be cleared.
  3. The non-static method isInterrupted() is used to query the interrupt state of other threads and does not change the interrupt state identification.

102. What is the function of the yield() method in the Thread class?

The yield() method can pause the currently executing thread object and allow other threads with the same priority to execute. It is a static method that can only ensure that the current thread gives up CPU usage and cannot guarantee that other threads can occupy CPU. Therefore, the thread executing yield() may be executed immediately after entering the paused state.

103. If the object's reference is set to null, will the garbage collector immediately release the memory occupied by the object?

The memory occupied by the object is not immediately released because this object can be recycled in the next garbage collection cycle. In other words, it will not be recycled immediately by the garbage collector, but will only release the memory occupied by the object during the next garbage collection.

104. There are three threads T1, T2, and T3. How to ensure sequential execution?

To ensure that the three threads of T1, T2, and T3 are executed sequentially, you can use the join() method of the Thread thread class.

105. Tell me about your understanding of thread safety?

When multiple threads access an object, if the behavior of calling this object does not require additional synchronization control or other coordination operations, the correct result can be obtained, then the object is thread-safe.

106. What is the difference between synchronized and ReentrantLock in Java?

Similarities:
synchronized and ReentrantLock are both locked and synchronized, and they are both blocking.
the difference:

  1. When synchronized competes for lock, it will wait; ReentrantLock can try to acquire the lock and get the result.
  2. synchronized cannot set the timeout time for acquiring the lock; ReentrantLock can set the timeout time for acquiring the lock;
  3. Synchronized cannot achieve fair lock; ReentrantLock can satisfy fair lock, fair lock means waiting first to acquire the lock first
  4. synchronized controls waiting and wake-up requires combining wait(), notify() and notifyAll() methods of locked objects; ReentrantLock controls waiting and wake-up requires combining await(), signal() and signalAll() methods of Condition's await(), signal() and signalAll() methods;
  5. synchronized is implemented at the JVM level; ReentrantLock is implemented at the JDK code level;
  6. Synchronized will automatically release the lock when the lock code block is executed or an exception occurs; ReentrantLock will not automatically release the lock, and it needs to be released in the finally code block.

107. What is the difference between submit() method and execute() method in Java thread pool?

  1. Both the submit() method and the execute() method can submit tasks to the thread pool.
  2. The return type of execute() method is void, which is defined in the Executor interface.
  3. The submit() method can return the Future object holding the calculation result. It is defined in the ExecutorService interface and extends the Executor interface.

108. Java class loading process?

  1. Loading: Compile the .java file into a .class file and generate a Class object
  2. Verification: Verify the accuracy of bytecode
  3. Preparation: Allocate memory to the static variables of the class and assign default values
  4. Analysis: Symbol references and dynamic links become direct references
  5. Initialization: Initialize the static variable of the class to the specified value, and execute the static code block

109. Describe the principle and mechanism of JVM loading Class files?

All classes in Java need to be loaded into the JVM by the class loader before they can run. The class loader itself is also a class, and its job is to read the class file from the hard disk to memory.
There are two types of class loading methods:

  1. Implicit loading: When a program generates objects through new or other methods during running, the class loader is implicitly called to load the corresponding class into the JVM.
  2. Explicit loading: explicitly load the required class through methods such as (). The loading of Java classes is dynamic. It does not load all classes at once and then run, but ensures that the basic classes that the program runs are fully loaded into the JVM. As for other classes, they are loaded when needed to save memory overhead.

110. What is the difference between a process and a thread?

A process is a running application, and a thread is an execution sequence inside a process, and a process can have multiple threads.

111. What is GC? Why do you need GC?

GC means garbage collection, and memory processing is a place where programmers are prone to problems. Forgot or incorrect memory recycling will lead to instability and even crashes in the program or system. The GC function provided by Java can automatically monitor whether the object exceeds the scope to achieve the purpose of automatically reclaiming memory. Java does not provide a display operation method to free allocated memory, so don't worry.Memory management, because the garbage collector will be managed automatically.

112. Briefly describe the Java garbage collection mechanism?

When a program creates objects of reference type such as objects, arrays, etc., the system will allocate a memory area in the heap memory, and the object is saved in the memory area. When the memory is no longer referenced by any reference variable, the memory becomes garbage and is waiting for the garbage collection mechanism to recycle.

113. What will () and () do?

The () method and the () method are used to prompt the JVM to perform garbage collection. The JVM decides whether to start immediately or delay garbage collection.

114. What are the advantages and principles of garbage recycling? And consider 2 recycling mechanisms?

Garbage collection can effectively prevent memory leakage and effectively use memory, which makes Java programmers no longer need to consider memory management when writing programs. The garbage collector is usually run as a separate low-level background thread, and unpredictable objects that have died or have not been used for a long time in the memory heap. Programmers cannot call the garbage collector in real time to garbage collect one or all objects. The recycling mechanism includes reference counting and object reference traversal.

115. What is the basic principle of a garbage collector (object reference traversal)? Can the garbage collector recycle memory immediately? Is there any way to actively notify the virtual machine for garbage collection?

When an object is created, GC begins to monitor the address, size and usage of the object, and usually uses directed graphs to record and manage all objects in the heap memory. In this way, which objects are "reachable" and which objects are "unreachable". When GC determines that some objects are "unreachable", it is the responsibility to reclaim the memory space of these objects. The garbage collector cannot recycle memory immediately. Programmers can manually execute the () method to notify GC to run, but it does not guarantee that GC will execute it.

116. Will there be a memory leak in Java? Please give a brief description?

Memory leaks are when objects or variables that are no longer used are always occupied in memory. Theoretically, Java has a GC garbage collection mechanism, that is, objects that are no longer used will be automatically recycled by GC and automatically cleared from memory. However, even so, Java still has memory leaks. The reason why Java causes memory leaks is clear: if long-life cycle objects hold references to short-life cycle objects, memory leaks are likely. Although short-life cycle objects are no longer needed, they cannot be recycled because long-life cycle objects hold their references. This is the scenario where memory leaks occur in Java.

117. How to determine whether an object survives? (Or how to determine GC objects?)

There are two ways to determine whether an object survives:

  1. Reference counting method: The so-called reference counting method is to set a reference counter for each object. Whenever there is a place to reference this object, the counter is increased by one. When the reference fails, the counter is reduced by one. When the reference counter of an object is zero, it means that the object is not referenced, that is, the "dead object" and will be garbage collected. One of the flaws of the reference counting method is that it cannot solve the problem of circular reference. That is, when object A refers to object B and object B refers to object A, then the reference counters of objects A and B are not zero at this time, which makes it impossible to complete garbage collection, so mainstream virtual machines do not use this algorithm.
  2. Accessibility algorithm (reference chain method): The idea of ​​this algorithm is to search downward from an object called GC Roots. If an object does not have any reference chain connected to GC Roots, it means that the object is not available.

118. When is the finalize() method called?DestructorWhat is the purpose of (finalization)?

When the garbage collector decides to recycle an object, it will call the finalize() method of the object. If the memory is always sufficient in Java, then garbage collection may never be carried out, that is, filailize() may never be executed. Obviously, it is unreliable to expect it to do the finishing work. Its main purpose is to recycle memory applied by special channels. Java programs have garbage collectors, so in general, programmers don't have to worry about memory issues. But there is a JNI call a non-Java program, and the job of finalize() is to recycle this part of the memory.

119. What is the difference between SynchronizedMap and ConcurrentHashMap?

  1. SynchronizedMap locks the entire table at once to ensure thread safety, so there can only be one thread to access and use segmented locks to ensure performance under multi-threads.
  2. In ConcurrentHashMap, one bucket is locked at a time. ConcurrentHashMap divides the hash table into 16 buckets by default. Common operations such as get, put, remove, etc. only lock the buckets currently used. In this way, it used to be possible to only one thread enter, but now there are 16 write threads to execute at the same time, and the improvement in concurrency performance is obvious.
  3. In addition, ConcurrentHashMap uses a different iteration method. In this iterator, when the set changes again after iterator is created, it no longer throws an exception. Instead, it changes new data so as not to affect the original data. After the iterator completes, it replaces the header pointer with the new data. In this way, the iterator thread can use the original old data, and the write thread can also complete the change concurrently.

120. What is distributed garbage collection (DGC)? How does it work?

DGC is called distributed garbage collection. Remote method calls (RMI) use DGC for automatic garbage collection. Because RMI contains references to remote objects across virtual machines, garbage collection is difficult. DGC uses reference counting algorithms to provide automatic memory management to remote objects.

121. What is the difference between a serial collector and throughput collector?

Throughput collectors use parallel versions of the next generation of garbage collectors, which are used for applications with medium-sized and large-scale data. Serial collectors are enough for most small applications (need about 100M of memory on modern processors).

122. In Java, when can objects be garbage collected?

When an object becomes unreachable to the application currently using this object, the object can be recycled.

123. Let me talk about what garbage collection algorithms do JVM have?

  1. Mark-clearing algorithm: mark useless objects and then clean up. Disadvantages: Not efficient and cannot remove garbage debris.
  2. Copy algorithm: divide two memory areas of equal size according to capacity. When one piece is used up, copy the alive object to another piece, and then clean up the used memory space at one time. Disadvantages: The memory usage rate is not high, only half of the original one.
  3. Mark-organization algorithm: mark useless objects, let all surviving objects move to one end, and then directly clear the memory outside the end boundary.
    Generation algorithm: divide memory into several pieces according to the different object survival cycles. Generally, the new generation and the old generation basically adopts a copy algorithm, and the old generation uses a marking and sorting algorithm.

124. What is a class loader and what are class loaders?

The code block that implements the acquisition of the binary byte stream of the class through the permission name of the class is called a class loader.
There are four main types of loaders:

  1. Startup class loader: used to load java core class library and cannot be directly referenced by java programs.
  2. Extension class loader: It is used to load Java extension libraries. The implementation of the Java virtual machine will provide an extension library directory. This class loader looks for and loads Java classes in this directory.
  3. System class loader: It loads Java classes based on the classpath (CLASSPATH) of the Java application. Generally speaking, Java application classes are loaded by it. It can be obtained through ().
  4. User-defined class loader: implemented by inheriting classes.

125. Classloader parent delegation model mechanism?

When a class receives a class loading request, it will not load the class first, but delegate it to the parent class and load it by the parent class. If the parent class cannot be loaded at this time, it will be fed back to the subclass, and the subclass will complete the loading of the class.

126. Comparison of PrintStream, BufferedWriter, PrintWriter?

  1. The PrintStream class supports wrapping the output stream into PrintStream and output text content. PrintStream will never throw an IOException, and supports automatic refresh and checking whether an exception occurs through the checkError method.
  2. The BufferedWriter class will support text writing character output streams, buffering individual characters to provide efficient writing of single characters, arrays, and strings. BufferedWriter can output the obtained characters through the write() method, and then perform line breaking operations through newLine(). A character stream in a BufferedWriter must be called to flush the flow, and the BufferedWriter can only operate on the character stream. If you want to operate on byte streams, use BufferedInputStream
  3. The println method of the PrintWriter class automatically adds line breaks and does not throw exceptions. If you care about exceptions, you need to call the checkError method to see if any exceptions occur. The constructor of the PrintWriter can specify parameters to automatically refresh the cache.

127. Which is better, byte stream or character stream? How to choose?

In most cases, it would be better to use byte streams, because most of the time IO operations are directly manipulating disk files, so these streams are transmitted in bytes (pictures, etc. are stored by bytes). If you use a character stream for the operation that requires frequent processing of strings in memory through IO, because the character stream has a buffer, which improves performance.

128. Briefly describe the java memory allocation and recycling rate, as well as Minor GC and Major GC?

Memory allocation:

  1. Stack area: The stack can be divided into Java virtual machine and local method stack
  2. Heap area: The heap is shared by all threads and is created when the virtual machine is started. It is the only purpose of storing object instances. It is the main area of ​​gc. It can usually be divided into two blocks, young generation and old generation. The younger generation can be divided into Eden area, mainly to place newly created objects. From survivor and To survivor save the objects that survived after gc, each accounting for 8:1:1 by default.
  3. Method area: Shared by all threads, used to store information, constants, static variables, etc. that have been loaded by the virtual machine. It is a logical part of the heap described by the Java virtual machine as. Habits are called permanent generations.
  4. Program counter: It is the line number indicator executed by the current thread. The jump instructions, etc. all rely on this to complete, and the thread is private.
    Recycling strategies and Minor GC and Major GC (Full GC):
  5. Objects are assigned in the Eden area of ​​the heap first.
  6. Large objects enter the old age directly.
  7. Long-term surviving objects will directly enter the old age. When there is not enough space for allocation in the Eden area, the execution of the virtual machine usually occurs in the Eden area of ​​the new generation. In this area, the object life is short, and the Gc often occurs at a higher frequency and the recycling speed is relatively fast. Full Gc/Major GC occurs in the elderly. Generally speaking, Minor GC will not be triggered when triggering the elderly GC, but through configuration, Minor GC can be performed before the Full GC, which can speed up the recycling speed of the elderly.

129. What is a buffer? What is its function?

A buffer is a special memory area. In many cases, when a program needs to frequently operate a resource (such as a file or a database), its performance will be very low. Therefore, in order to improve performance, part of the data can be temporarily read and written to the cache area, and then read and write data directly from this area, which significantly improves the quality. Operations for Java character streams are all operated in buffers, so if we want to actively flush the buffer to the file in character stream operations, we can use the flush() method to operate.

130. What kind of stream does BufferedReader belong to? What are its main uses for? What classic methods are there in it?

A buffered stream in a processing stream, which can store the read content in memory, with the readLine() method, which is used to read a line


If you have any questions, please send a private message/comment pointing out. Thank you for watching, I hope it will be helpful to you!
/