124 interview questions for Java programmers (with answers)

124 interview questions for Java programmers (with answers)

Basic issues of multithreading, concurrency, and threads

1) Can a volatile array be created in Java?

Yes, an array of volatile type can be created in Java, but it is just a reference to the array, not the entire array. What I mean is that if you change the array pointed to by the reference, it will be protected by volatile, but if multiple threads change the elements of the array at the same time, the volatile identifier will not play the protective role before.

2) Can volatile make a non-atomic operation into an atomic operation?

A typical example is that there is a long type member variable in the class. If you know that the member variable will be accessed by multiple threads, such as counters, prices, etc., you'd better set it to volatile. why? Because reading a long variable in Java is not atomic, it needs to be divided into two steps. If one thread is modifying the value of the long variable, another thread may only see half of the value (the first 32 bits). But the reading and writing of a volatile long or double variable is atomic.

3) What is the practice of volatile modifier?

One practice is to modify long and double variables with volatile so that they can be read and written as atomic types. Both double and long are 64 bits wide, so the reading of these two types is divided into two parts. The first 32 bits are read for the first time, and then the remaining 32 bits are read. This process is not atomic. However, the reading and writing of volatile long or double variables in Java is atomic. Another function of the volatile fixer is to provide a memory barrier, such as in the application of a distributed framework. Simply put, before you write a volatile variable, the Java memory model inserts a write barrier (write barrier), and before reading a volatile variable, it inserts a read barrier (read barrier). This means that when you write a volatile field, you can ensure that any thread can see the value you write. At the same time, before writing, you can also ensure that any value update is visible to all threads because the memory barrier will All other written values are updated to the cache.

4) What guarantee does volatile variable provide?

Volatile variables provide order and visibility guarantees. For example, JVM or JIT reorders statements for better performance, but volatile variables will not be reordered with other statements even if they are assigned without synchronization blocks. Volatile provides a happens-before guarantee, ensuring that the modification of one thread is visible to other threads. In some cases, volatile can also provide atomicity. For example, when reading 64-bit data types, long and double are not atomic, but volatile double and long are atomic.

5) Which is easier to write synchronous code of 10 threads or 2 threads?

From the perspective of code writing, the complexity of the two is the same, because the synchronization code and the number of threads are independent of each other. But the choice of synchronization strategy depends on the number of threads, because more threads means greater competition, so you need to use synchronization techniques, such as lock separation, which requires more complex code and professional knowledge.

6) How do you call the wait() method? Use if blocks or loops? why?

The wait() method should be called in a loop, because when the thread gets the CPU to start execution, other conditions may not be met, so it is better to loop to check whether the conditions are met before processing. The following is a standard code that uses wait and notify methods:

//The standard idiom for using the wait method synchronized(obj) {while(condition does not hold) obj.wait();//(Releases lock, and reacquires on wakeup) ...//Perform action appropriate to condition}

7) What is false sharing in a multithreaded environment?

False sharing is a well-known performance problem in multi-threaded systems (each processor has its own local cache). Pseudo-sharing occurs on different processors. The modification of variables by threads on different processors depends on the same cache line, as shown in the following figure:

Java interview questions for experienced programmers

Pseudo-sharing is difficult to find because threads may access completely different global variables, but they happen to be in very close locations in memory. As with many other concurrency issues, the most basic way to avoid false sharing is to carefully review the code and adjust your data structure based on cache lines.

8) What is Busy spin? Why should we use it?

Busy spin is a technology that waits for events without releasing the CPU. It is often used to avoid losing data in the CPU cache (if the thread is suspended first, it will be lost after running on other CPUs). So, if your work requires low latency, and your threads currently do not have any order, then you can loop through the detection of new messages in the queue instead of calling the sleep() or wait() method. Its only advantage is that you only need to wait for a short time, such as a few microseconds or a few nanoseconds. The LMAX distributed framework is a high-performance inter-thread communication library. The library has a BusySpinWaitStrategy class based on this concept. It uses busy spin loop EventProcessors to wait for the barrier.

9) How to obtain a thread dump file in Java?

Under Linux, you can use the command kill -3 PID (the process ID of the Java process) to get the dump file of the Java application. Under Windows, you can press Ctrl + Break to get it. In this way, the JVM will print the thread dump file to the standard output or error file. It may be printed in the console or log file, depending on the configuration of the application. If you use Tomcat.

10) Is Swing thread safe?

No, Swing is not thread-safe. You cannot update Swing components such as JTable, JList or JPanel through any thread. In fact, they can only be updated through GUI or AWT threads. This is why Swing provides invokeAndWait() and invokeLater() methods to obtain GUI update requests from other threads. These methods put the update request into the thread queue of AWT, which can wait forever, or return the result directly through asynchronous update. You can also view and learn more detailed content in the reference answer.

11) What are thread local variables?

Thread local variables are variables confined to the inside of the thread, belong to the thread itself, and are not shared among multiple threads. Java provides the ThreadLocal class to support thread local variables, which is a way to achieve thread safety. But be careful when using thread-local variables in a management environment (such as a web server). In this case, the life cycle of a worker thread is longer than the life cycle of any application variable. Once any thread-local variables are not released after the work is completed, Java applications have the risk of memory leaks.

12) Use wait-notify to write a piece of code to solve the producer-consumer problem?

Please refer to the sample code in the answer. Just remember to call the wait() and notify() methods in the synchronized block. If it is blocked, test the wait condition through the loop.

13) Write a thread-safe singleton mode (Singleton) in Java?

Please refer to the sample code in the answer, which teaches you step by step to create a thread-safe Java singleton class. When we say thread safety, we mean that even if the initialization is in a multi-threaded environment, a single instance can still be guaranteed. In Java, using enumeration as a singleton is the easiest way to create a thread-safe singleton pattern.

14) The difference between sleep method and wait method in Java?

Although both are used to suspend the currently running thread, sleep() is actually just a short pause, because it will not release the lock, and wait() means conditional wait, which is why the method releases the lock because only In this way, other waiting threads can acquire the lock when the conditions are met.

15) What is an immutable object? How to create an immutable object in Java?

An immutable object means that once an object is created, its state cannot be changed. Any modification will create a new object, such as String, Integer and other wrapper classes. For details, see the answer, which guides you step by step to create an immutable class in Java.

16) Can we create an immutable object that contains mutable objects?

Yes, we can create an immutable object that contains a mutable object. You just need to be careful not to share the reference of the mutable object. If you need to change, return a copy of the original object. The most common example is that the object contains a reference to a date object.

Data types and Java basic interview questions

17) What data type should be used to represent prices in Java?

If you are not particularly concerned about memory and performance, use BigDecimal, otherwise use the double type with predefined precision.

18) How to convert byte to String?

You can use the String constructor that accepts byte[] parameters to perform the conversion. The point that needs to be paid attention to is the correct encoding to be used, otherwise the platform default encoding will be used. This encoding may be the same or different from the original encoding.

19) How to convert bytes to long type in Java?

You answer this question :-)

20) Can we cast int to byte type variable? If the value is greater than the byte type range, what will happen?

Yes, we can do coercion, but in Java, int is 32-bit and byte is 8-bit, so if the coercion is done, the upper 24 bits of the int type will be discarded, and the range of the byte type is from- 128 to 128.

21) There are two classes, B inherits A and C inherits B. Can we convert B to C? Such as C = (C) B;

22) Which class contains the clone method? Is it Cloneable or Object?

java.lang.Cloneable is an iconic interface and does not contain any methods. The clone method is defined in the object class. And you need to know that the clone() method is a native method, which means it is implemented in c or c++ or other native languages.

23) Are the ++ operators thread-safe in Java?

Not a thread-safe operation. It involves multiple instructions, such as reading the value of a variable, adding it, and then storing it back to memory. This process may involve multiple threads.

24) The difference between a = a + b and a += b

+= implicitly casts the result type of the addition operation to the type that holds the result. If two integer types are added, such as byte, short, or int, they will first be promoted to the int type, and then the addition operation will be performed. If the result of the addition operation is greater than the maximum value of a, then a + b will have a compilation error, but a += b is no problem, as follows:

byte a = 127; byte b = 127; b = a + b;//error: cannot convert from int to byte b += a;//ok

(Translator's Note: This place should be wrong. In fact, no matter what the value of a+b is, the compiler will report an error. Because the a+b operation will promote a and b to int type, so assign int type to byte Will compile error)

25) Can I assign a double value to a variable of type long without casting it?

No, you can't assign a double value to a variable of type long without a coercive type conversion, because the double type has a wider range than the long type, so coercion must be performed.

26) What will 3*0.1 == 0.3 return? true or false?

false, because some floating-point numbers cannot be represented exactly.

27) Which of int and Integer will take up more memory?

Integer objects will take up more memory. Integer is an object and needs to store the metadata of the object. But int is a primitive type of data, so it takes up less space.

28) Why is String in Java immutable (Immutable)?

Strings in Java are immutable because the designers of Java believe that strings are used very frequently. Setting the string to be immutable allows multiple clients to share the same string. See the answer for more details.

29) Can we use String in Switch?

Starting from Java 7, we can use strings in switch cases, but this is just a syntactic sugar. The internal implementation uses the hash code of the string in the switch.

30) What is the constructor chain in Java?

When you call another constructor from one constructor, it is the constructor chain in Java. This situation only occurs when the class constructor is overloaded.

JVM bottom layer and GC (Garbage Collection) interview questions

31) In 64-bit JVM, is the length of int the majority?

In Java, the length of an int type variable is a fixed value, regardless of the platform, all are 32 bits. This means that in 32-bit and 64-bit Java virtual machines, the length of the int type is the same.

32) What is the difference between Serial and Parallel GC?

Serial and Parallel will cause stop-the-world when GC is executed. The main difference between them is that the serial collector is the default copy collector. There is only one thread when performing GC, while the parallel collector uses multiple GC threads to execute.

33) For 32-bit and 64-bit JVMs, the length of int type variables is the majority?

In the 32-bit and 64-bit JVM, the length of the int type variable is the same, both 32 bits or 4 bytes.

34) The difference between WeakReference and SoftReference in Java?

Although both WeakReference and SoftReference are helpful to improve the efficiency of GC and memory, WeakReference, once the last strong reference is lost, will be reclaimed by GC. Although soft reference cannot prevent reclaiming, it can be delayed until the JVM memory is insufficient.

35) How does WeakHashMap work?

The work of WeakHashMap is similar to that of normal HashMap, but it uses weak references as keys, which means that when the key object has no references, the key/value will be recycled.

36) What does the JVM option -XX:+UseCompressedOops do? Why use it?

When you migrate your application from a 32-bit JVM to a 64-bit JVM, because the pointer of the object increases from 32-bit to 64-bit, the heap memory will suddenly increase, almost doubling. This will also adversely affect the data in the CPU cache (the capacity is much smaller than the memory). Because the main motivation for migrating to a 64-bit JVM is that you can specify the maximum heap size, and you can save a certain amount of memory by compressing OOP. With the -XX:+UseCompressedOops option, the JVM will use 32-bit OOP instead of 64-bit OOP.

37) How to judge whether the JVM is 32-bit or 64-bit through a Java program?

You can check certain system properties such as sun.arch.data.model or os.arch to get this information.

38) What is the maximum heap memory of 32-bit JVM and 64-bit JVM?

Theoretically speaking, the heap memory of a 32-bit JVM can reach 2^32, which is 4GB, but in fact it will be much smaller than this. Different operating systems are different, such as Windows system about 1.5 GB, Solaris about 3GB. The 64-bit JVM allows you to specify the maximum heap memory. Theoretically, it can reach 2^64. This is a very large number. In fact, you can specify the heap memory size up to 100GB. Even for some JVMs, such as Azul, it is possible to have a heap memory of up to 1000G.

39) What is the difference between JRE, JDK, JVM and JIT?

JRE stands for Java run-time and is required to run Java references. JDK stands for Java development kit (Java development kit). It is a development tool for Java programs, such as a Java compiler. It also includes JRE. JVM stands for Java virtual machine (Java virtual machine), and its responsibility is to run Java applications. JIT stands for Just In Time Compilation. When the number of code executions exceeds a certain threshold, Java bytecode will be converted to native code. For example, the main hotspot code will be replaced with native code, which is beneficial. Significantly improve the performance of Java applications.

Java interview questions with 3 years of work experience

40) Explain Java heap space and GC?

When a Java process is started via a Java command, memory will be allocated for it. Part of the memory is used to create the heap space. When an object is created in the program, the memory is allocated from the space. GC is a process inside the JVM that reclaims the memory of invalid objects for future allocation.

JVM low-level interview questions and answers

41) Can you guarantee GC execution?

No, although you can call System.gc() or Runtime.gc(), there is no way to guarantee the execution of GC.

42) How to get the memory used by the Java program? What percentage of the heap is used?

The remaining memory, total memory and maximum heap memory can be obtained through memory-related methods in the java.lang.Runtime class. Through these methods, you can also get the percentage of heap usage and the remaining space of heap memory. Runtime.freeMemory() method returns the number of bytes of remaining space, Runtime.totalMemory() method returns the number of bytes of total memory, and Runtime.maxMemory() returns the number of bytes of maximum memory.

43) What is the difference between heap and stack in Java?

The heap and stack in the JVM belong to different memory areas, and they are used for different purposes. The stack is often used to save method frames and local variables, and objects are always allocated on the heap. The stack is usually smaller than the heap, and it is not shared among multiple threads, while the heap is shared by all threads of the entire JVM.

Interview questions and answers about memory

Java basic concepts interview questions

44) What is the difference between "a==b" and "a.equals(b)"?

If both a and b are objects, then a==b is to compare the references of the two objects. Only when a and b point to the same object in the heap will it return true, and a.equals(b) is for logic Comparison, so it is usually necessary to rewrite this method to provide a logically consistent comparison. For example, the String class overrides the equals() method, so it can be used to compare two different objects but contain the same letter.

45) What is the use of a.hashCode()? What is the relationship with a.equals(b)?

The hashCode() method is the hash value of the corresponding object integer. It is often used in hash-based collection classes, such as Hashtable, HashMap, LinkedHashMap, etc. It is particularly closely related to the equals() method. According to the Java specification, two objects that use the equal() method to determine the equality must have the same hash code.

46) What is the difference between final, finalize and finally?

final is a modifier that can modify variables, methods, and classes. If final modifies a variable, it means that the value of the variable cannot be changed after initialization. The finalize method is a method called before the object is recycled, giving the object one last chance to resurrect itself, but there is no guarantee when finalize will be called. finally is a keyword, used together with try and catch for exception handling. The finally block will be executed, regardless of whether an exception occurs in the try block.

47) What are compile-time constants in Java? What are the risks of using it?

Public static final variables are what we call compile-time constants, where public is optional. In fact, these variables will be replaced at compile time, because the compiler knows the value of these variables and knows that these variables cannot be changed at runtime. One problem with this approach is that you use a public compile-time constant in an internal or third-party library, but this value was later changed by others, but your client is still using the old value, even if you have A new jar is deployed. To avoid this, when you are updating dependent JAR files, make sure to recompile your program.

Interview Questions for Java Collection Framework

This part also includes interview questions about data structures, algorithms, and arrays

48) The difference between List, Set, Map and Queue

List is an ordered collection that allows elements to be repeated. Some of its implementations can provide constant access time based on the subscript value, but this is not guaranteed by the List interface. Set is an unordered collection.

49) The difference between poll() method and remove() method?

Both poll() and remove() take out an element from the queue, but poll() will return null when it fails to get the element, but it will throw an exception when remove() fails.

50) What is the difference between LinkedHashMap and PriorityQueue in Java?

PriorityQueue guarantees that the highest or lowest priority element is always at the head of the queue, but the order maintained by LinkedHashMap is the order in which the elements are inserted. When traversing a PriorityQueue, there is no order guarantee, but the LinkedHashMap class guarantees that the traversal order is the order in which the elements are inserted.

51) Is there any difference between ArrayList and LinkedList?

The most obvious difference is that the underlying data structure of ArrrayList is an array, which supports random access, while the underlying data structure of LinkedList does not support random access. Using subscripts to access an element, the time complexity of ArrayList is O(1), while LinkedList is O(n). See the answer for more detailed discussion.

52) Which two ways are used to achieve the sorting of the collection?

You can use ordered collections, such as TreeSet or TreeMap, or you can use ordered collections, such as list, and then sort by Collections.sort().

53) How to print an array in Java?

You can use the Arrays.toString() and Arrays.deepToString() methods to print arrays. Since the array does not implement the toString() method, if the array is passed to the System.out.println() method, the contents of the array will not be printed, but Arrays.toString() can print each element.

54) Is LinkedList in Java a singly linked list or a doubly linked list?

It is a doubly linked list, you can check the source code of the JDK. In Eclipse, you can use the shortcut key Ctrl + T to open the class directly in the editor.

55) What tree is used to implement TreeMap in Java?

TreeMap in Java is implemented using red-black trees.

56) What is the difference between Hashtable and HashMap?

There are many differences between these two classes, some of which are listed below:

a) Hashtable is a class left over from JDK 1, and HashMap was added later.

b) Hashtable is synchronous and slower, but HashMap has no synchronization strategy, so it will be faster.

c) Hashtable does not allow an empty key, but HashMap allows a null key.

See the answer for more differences.

57) How does HashSet in Java work internally?

The interior of HashSet is implemented by HashMap. Since Map requires key and value, all keys have a default value. Similar to HashMap, HashSet does not allow duplicate keys, only one null key is allowed, which means that only one null object is allowed to be stored in HashSet.

58) Write a piece of code to remove an element while traversing the ArrayList?

The key to this question is whether the interviewer uses the remove() method of ArrayList or the remove() method of Iterator. Here is a sample code that uses the correct way to remove elements during the traversal process without
ConcurrentModificationException.

59) Can we write a container class ourselves, and then use for-each loop code?

Yes, you can write your own container class. If you want to use the enhanced loop in Java to traverse, you only need to implement the Iterable interface. If you implement the Collection interface, it will have this property by default.

60) What are the default sizes of ArrayList and HashMap?

In Java 7, the default size of ArrayList is 10 elements, and the default size of HashMap is 16 elements (must be a power of 2). This is the code snippet of the ArrayList and HashMap classes in Java 7:

//from ArrayList.java JDK 1.7 privatestaticfinalintDEFAULT_CAPACITY = 10;//from HashMap.java JDK 7 staticfinalintDEFAULT_INITIAL_CAPACITY = 1<< 4;//aka 16

61) Is it possible that two unequal objects have the same hashcode?

It is possible that two unequal objects may have the same hashcode value, which is why there is a conflict in the hashmap. The requirement for equal hashcode values only says that if two objects are equal, they must have the same hashcode value, but there is no requirement for unequal objects.

62) Will two identical objects have different hash codes?

No, according to the provisions of the hash code, this is impossible.

63) Can we use random numbers in hashcode()?

No, because the hashcode value of the object must be the same. See the answer for more knowledge about overriding the hashCode() method in Java.

64) What is the difference between Comparator and Comparable in Java?

The Comparable interface is used to define the natural order of objects, while the comparator is usually used to define a user-customized order. There is always only one Comparable, but there can be multiple Comparables to define the order of objects.

65) Why do I need to rewrite the hashCode method when rewriting the equals method?

Because there are mandatory specifications to specify that both hashcode and equal are methods that need to be rewritten at the same time, many container classes, such as HashMap and HashSet, rely on the provisions of hashcode and equals.

Interview questions for Java IO and NIO

IO is a very important point in the Java interview. You should have a good grasp of Java IO, NIO, NIO2 and basic knowledge related to operating system and disk IO. The following are frequently asked questions in Java IO.

66) In my Java program, I have three sockets, how many threads do I need to process?

67) How to create ByteBuffer in Java?

68) How to read and write ByteBuffer in Java?

69) Does Java use big-endian or little-endian?

70) What is the endianness in ByteBuffer?

71) What is the difference between a direct buffer and an indirect buffer in Java?

72) What is the memory mapped buffer area in Java?

73) What does the socket option TCP NO DELAY mean?

74) What is the difference between TCP protocol and UDP protocol?

75) What is the difference between ByteBuffer and StringBuffer in Java?

Interview Questions for Java Best Practices

Contains best practices in various parts of Java, such as collections, strings, IO, multithreading, error and exception handling, design patterns, and so on.

76) In Java, what best practices do you follow when writing multi-threaded programs?

These are some of the best practices I followed when writing Java concurrent programs:

a) Give the thread a name, which can help debugging.

b) Minimize the scope of synchronization, instead of synchronizing the entire method, only the key parts are synchronized.

c) If possible, prefer to use volatile instead of synchronized.

d) Use higher-level concurrency tools instead of wait() and notify() to implement inter-thread communication, such as BlockingQueue, CountDownLatch and Semeaphore.

e) Prioritize the use of concurrent collections instead of synchronizing collections. Concurrent collections provide better scalability.

77) Tell me a few best practices for using Collections in Java

Here are some of my best practices in using the Collectionc class in Java:

a) Use the correct collection class, for example, if you don't need to synchronize lists, use ArrayList instead of Vector.

b) Prefer to use concurrent collections instead of synchronizing collections. Concurrent collections provide better scalability.

c) Use interfaces to represent and access collections, such as using List to store ArrayList, using Map to store HashMap, etc.

d) Use iterators to loop through the collection.

e) Use generics when using collections.

78) Name at least 5 best practices for using threads in Java.

This question is similar to the previous question, you can use the answer above. For threads, you should:

a) Name the thread

b) Separate threads from tasks and use thread pool executors to execute Runnable or Callable.

c) Use thread pool

79) Name 5 best practices for IO

IO is very important to the performance of Java applications. Ideally, you should not avoid IO operations on the critical path of your application. Here are some Java IO best practices you should follow:

a) Use the IO class with buffer instead of reading bytes or characters separately.

b) Use NIO and NIO2

c) Close the stream in the finally block, or use a try-with-resource statement.

d) Use memory mapped files to get faster IO.

80) List 5 JDBC best practices that should be followed

There are many best practices, and you can give examples according to your preferences. Here are some more general principles:

a) Use batch operations to insert and update data

b) Use PreparedStatement to avoid SQL exceptions and improve performance.

c) Use database connection pool

d) Get the result set by column name, don't use column subscript to get it.

81) Tell me a few best practices for method overloading in Java?

Here are a few best practices for method overloading that can be followed to avoid confusion caused by autoboxing.

a) Don't overload such methods: one method accepts int parameters, and another method accepts Integer parameters.

b) Don't overload methods with the same number of parameters, but just different order of parameters.

c) If the number of overloaded method parameters is more than 5, use variable parameters.

Interview questions for Date, Time and Calendar

82) Is SimpleDateFormat thread safe in a multithreaded environment?

No, unfortunately, all implementations of DateFormat, including SimpleDateFormat, are not thread-safe, so you should not use them in multi-threaded programs unless you use them in an external thread-safe environment, such as restricting SimpleDateFormat to ThreadLocal. If you don't do this, you may get an incorrect result when parsing or formatting the date. Therefore, from all the practices of date and time processing, I strongly recommend the joda-time library.

83) How to format a date in Java? Such as formatting as ddMMyyyy?

In Java, you can use the SimpleDateFormat class or the joda-time library to format dates. The DateFormat class allows you to format dates in a variety of popular formats. See the sample code in the answer, which demonstrates formatting the date into different formats, such as dd-MM-yyyy or ddMMyyyy.

84) How to display the time zone in the formatted date in Java?

85) What is the difference between java.util.Date and java.sql.Date in Java?

86) How to calculate the difference between two dates in Java?

87) How to convert the string YYYYMMDD to a date in Java?

Unit test JUnit interview questions

89) How to test static methods?

You can use the PowerMock library to test static methods.

90) How to use JUnit to test the exception of a method?

91) Which unit test library have you used to test your Java program?

92) What is the difference between @Before and @BeforeClass?

Interview questions related to programming and coding

93) How to check that a string contains only numbers?

94) How to write an LRU cache using generics in Java?

95) Write a Java program to convert byte to long?

95) How to reverse a string without using StringBuffer?

97) How to get the highest frequency of words in a file in Java?

98) How to check that two given strings are in reverse order?

99) How to print out all permutations of a string in Java?

100) How can I print out the repeated elements in an array in Java?

101) How to convert a string to an integer in Java?

102) How to exchange the values of two integer variables without using temporary variables?

Interview questions about OOP and design patterns

This part contains the design principles of SOLID during the Java interview process, OOP basics, such as classes, objects, interfaces, inheritance, polymorphism, encapsulation, abstraction, and some more advanced concepts such as composition, aggregation, and association. It also contains the problem of GOF design pattern.

103) What is the interface? Why use interfaces instead of using concrete classes directly?

The interface is used to define the API. It defines the rules that the class must follow. At the same time, it provides an abstraction, because the client only uses the interface, so there can be multiple implementations, such as the List interface, you can use the ArrayList that can be accessed randomly, or the LinkedList that is easy to insert and delete. It is not allowed to write code in the interface to ensure abstraction, but in Java 8, you can declare a static default method in the interface, which is specific.

104) What is the difference between abstract class and interface in Java?

In Java, there are many differences between abstract classes and interfaces, but the most important one is that in Java, a class can only inherit one class, but can implement multiple interfaces. Abstract classes can well define the default behavior of a family class, and interfaces can better define types, which will help implement polymorphic mechanisms later. Please check the answer for the discussion on this question.

105) In addition to the singleton pattern, what other design patterns have you used in the production environment?

This needs to be answered based on your experience. Under normal circumstances, you can say dependency injection, factory mode, decoration mode or observer mode, just choose the one you have used. But you should be prepared to answer the next questions based on the model you choose.

106) Can you explain the principle of Liskov substitution?

107) Under what circumstances will the law of Dimit be violated? Why is there such a problem?

Dimit's rule suggests that "only talk to friends, not strangers" to reduce the coupling between classes.

108) What is the adapter mode? When is it used?

The adapter mode provides conversion to the interface. If your client uses some interfaces, but you have other interfaces, you can write an adaptation to connect these interfaces.

109) What are "dependency injection" and "inversion of control"? Why does anyone use it?

110) What is an abstract class? What is the difference between it and the interface? Why have you used abstract classes?

111) Constructor injection and setter dependency injection, which way is better?

Each method has its shortcomings and advantages. Constructor injection ensures that all injections are initialized, but setter injection provides better flexibility to set optional dependencies. If you use XML to describe dependencies, Setter injection will be more readable and writable. The rule of thumb is to force dependencies to use constructor injection, and optional dependencies to use setter injection.

112) What is the difference between dependency injection and engineering mode?

Although both modes separate the creation of objects from the application logic, dependency injection is clearer than the engineering mode. Through dependency injection, your class is a POJO, which only knows the dependencies and does not care how to obtain them. Using the factory pattern, your class needs to get dependencies through the factory. Therefore, using DI will be easier to test than using factory mode. See the answer for a more detailed discussion on this topic.

113) What is the difference between the adapter mode and the decorator mode?

Although the structure of the adapter pattern and the decorator pattern are similar, the intention of each pattern is different. The adapter pattern is used to bridge two interfaces, and the purpose of the decoration pattern is to add new functions to the class without modifying the class.

114) What is the difference between the adapter mode and the proxy mode before?

This problem is similar to the previous one. The difference between the adapter mode and the proxy mode lies in their different intentions. Since both the adapter mode and the proxy mode encapsulate the classes that actually perform actions, the structure is the same, but the adapter mode is used to convert between interfaces, and the proxy mode is to add an additional intermediate layer to support allocation, control or Smart access.

115) What is the template method pattern?

The template method provides the framework of the algorithm, and you can configure or define the steps yourself. For example, you can think of a sorting algorithm as a template. It defines the ordering steps, but for the specific comparison, you can use Comparable or similar in its language, and the specific strategy is up to you to configure. The method of listing the algorithm summary is the well-known template method.

116) When to use visitor mode?

The visitor pattern is used to solve the problem of adding operations to the inheritance level of the class, but not directly related to it. This mode adopts the form of double dispatch to increase the middle layer.

117) When to use the combined mode?

The combination mode uses a tree structure to show the partial and overall inheritance relationship. It allows the client to treat single objects and object containers in a unified form. Use composition mode when you want to show the inheritance relationship between the part and the whole of the object.

118) What is the difference between inheritance and composition?

Although both can achieve code reuse, composition is more flexible than inheritance, because composition allows you to choose different implementations at runtime. Code implemented with composition is also easier to test than inheritance.

119) Describe overloading and rewriting in Java?

Both overloading and rewriting allow you to use the same name to implement different functions, but overloading is a compile-time activity, and rewriting is a run-time activity. You can override methods in the same class, but you can only override methods in subclasses. Rewriting must have inheritance.

120) What is the difference between nested public static classes and top-level classes in Java?

There can be multiple nested public static classes inside a class, but a Java source file can only have one top-level public class, and the name of the top-level public class must be consistent with the name of the source file.

121) What is the difference between composition, aggregation and association in OOP?

If two objects are related to each other, they are said to be related to each other. Composition and aggregation are two forms of association in object-oriented. Combination is a stronger association than aggregation. In composition, one object is the owner of another, and aggregation means that one object uses another. If object A is combined by object B, if A does not exist, B must not exist, but if A object aggregates an object B, even if A does not exist, B can exist alone.

122) Give me an example of a design pattern that complies with the opening and closing principle?

The principle of opening and closing requires your code to be open for extension and closed for modification. This means that if you want to add a new feature, you can easily add new code without changing the tested code. Several design patterns are based on the principle of opening and closing, such as the strategy pattern. If you need a new strategy, you only need to implement interfaces and add configurations without changing the core logic. A working example is the Collections.sort() method, which is based on the strategy pattern and follows the open and closed principle. You don t need to modify the sort() method for new objects. All you need to do is implement your own Comparator interface. .

123) What is the difference between abstract factory pattern and prototype pattern?

124) When to use Flyweight mode?

Flyweight mode avoids creating too many objects by sharing objects. In order to use the flyweight model, you need to ensure that your objects are immutable so that you can share them safely. The String pool, Integer pool, and Long pool in the JDK are all good examples of using the flyweight pattern.

Regarding the details of the interview preparation, you can refer to my top article!

The golden three and the silver four have passed, and my friends should also prepare for the golden nine and silver ten. I also have some Java advanced architect materials now for free to those in need!

Receiving method: follow + forward + private message me [data] after collection to get it for free!