Multithreading, concurrency, and threading fundamentals

1) Can Volatile arrays be created in Java?

Yes, you can create volatile arrays in Java, but only as a reference to the array, not the entire array. What I mean by that is that changing the array to which the reference refers is protected by volatile, but if multiple threads change the elements of the array at the same time, the volatile identifier is not protected.

2) Can volatile make a nonatomic operation atomic?

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

3) What is the practice with volatile modifiers?

One practice is to use volatile to modify long and double variables so that they can be read and written by atomic type. Double and long are both 64 bits wide, so reads of both types are split into two parts, first reading the first 32 bits and then reading the remaining 32 bits. This process is not atomic, In Java, however, volatile long or double variables are read and written atomically. Another use of volatile fixes is to provide memory barriers, as in distributed frameworks. In simple terms, the Java memory model inserts a write barrier before you write a volatile variable, and a read barrier before you read a volatile variable. This means that when you write a volatile field, you can ensure that any thread can see the value you write, and that any value changes are visible to all threads prior to writing, because the memory barrier updates all other written values to the cache.

4) What guarantees do volatile variables provide?

Volatile variables provide order and visibility guarantees. For example, the JVM or JIT may reorder statements for better performance, but volatile variables do not reorder statements even if they are assigned without synchronized blocks. Volatile provides a happens-before guarantee that changes made by one thread are visible to other threads. Volatile can also provide atomicity in some cases, such as reading 64-bit data types, such as long and double, which are not atomic, but double and long, which are volatile.

5) Which is easier to write, 10-thread or 2-thread synchronization code?

From a coding standpoint, the complexity is the same, because synchronized code is independent of the number of threads. But the choice of synchronization strategy depends on the number of threads, because more threads means more contention, so you need to take advantage of synchronization techniques such as lock separation, which require more complex code and expertise.

6) How do you call wait ()? If block or loop? Why is that?

The wait() method should be called in a loop, because other conditions may not have been met by the time the thread gets to the start of CPU execution, so it is better to loop to check if the conditions have been met before processing. Here is a standard code that uses wait and notify:

// 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 multi-threaded environment?

Pseudo-sharing is a well-known performance problem in multithreaded systems (where each processor has its own local cache). Pseudo-sharing occurs when threads on different processors modify variables depending on the same cache line, as shown in the following figure:

Java interview questions for experienced programmers

Pseudo-sharing problems are difficult to detect because threads can access completely different global variables that happen to be in very similar locations in memory. As with many other concurrency issues, the most basic way to avoid pseudo-sharing is to take a close look at your code and adjust your data structure based on the cached lines.

8) What is Busy Spin? Why do we use it?

Busy Spin is a technique that waits for events without releasing the CPU. It is often used to avoid losing data in the CPU’s cache (lost if the program is paused first and then runs on another CPU). So, if your job requires low latency and your threads are currently out of any order, you can loop through the queue to detect new messages instead of calling sleep() or wait(). The only advantage is that you only have to wait a few microseconds or nanoseconds. The LMAX Distributed framework is a high performance library for interthread communication. The library has a BusySpinWaitStrategy class implemented based on this concept, using the BusySpin loop EventProcessors wait barrier.

How to obtain a thread dump file in Java?

On Linux, you can run the kill -3 PID command to obtain the dump file of the Java application. On Windows, you can get it by pressing Ctrl + Break. The JVM then prints the thread’s dump file to standard output or an error file, either in the console or in a log file, depending on the configuration of the application. If you use Tomcat.

10) Is Swing thread-safe?

No, Swing is not thread-safe. Swing components such as JTable, JList, or JPanel cannot be updated by any thread; in fact, they can only be updated by GUI or AWT threads. This is why Swing provides the invokeAndWait() and invokeLater() methods to get GUI update requests from other threads. These methods put the update request into a thread queue in the AWT and can either wait or return the result directly through asynchronous updates. You can also see and learn more details in the reference answers.

11) What are thread-local variables?

Thread-local variables are variables that are limited within a thread and are owned by the thread itself and are not shared between multiple threads. Java provides a ThreadLocal class to support thread-local variables as a way to achieve thread-safety. However, be careful when using thread-local variables in a managed environment, such as a Web server, where the life of a worker thread is longer than the life of any application variable. Java applications run the risk of memory leaks if any thread-local variables are not released after work is done.

12) Use Wait-notify to write code to solve a producer-consumer problem?

Refer to the sample code in the answer. Just remember to call wait() and notify() in the synchronized block and, if blocked, test the wait condition through a loop.

13) Write a thread-safe Singleton in Java?

Refer to the sample code in the answer, which provides step-by-step instructions for creating a thread-safe Java singleton class. When we say thread-safe, we mean that even if the initialization is in a multi-threaded environment, a single instance can still be guaranteed. In Java, using enumerations as singleton classes is the easiest way to create thread-safe singleton patterns.

14) What is the difference between sleep and wait in Java?

While both are used to pause the currently running thread, sleep() is actually a short pause because it does not release the lock, and wait() means conditional waiting, which is why this method releases the lock so that other waiting threads can acquire the lock when the condition is met.

15) What are immutable objects? How do you create an immutable object in Java?

Immutable objects mean that once an object is created, its state cannot be changed. Any changes create a new object, such as String, Integer, and other wrapper classes. See the answer for a step-by-step guide to creating an immutable class in Java.

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

Yes, it is possible to create an immutable object that contains a mutable object. You just need to be careful not to share references to mutable objects, and return a copy of the original object if changes are needed. The most common example is when an object contains a reference to a date object.

Data types and Java basics interview questions

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

Use BigDecimal if you are not particularly concerned with memory and performance, otherwise use a double of predefined precision.

18) How to convert byte to String?

The conversion can be done using the String constructor that accepts the byte[] argument. The important thing is to use the correct encoding, otherwise the platform default encoding will be used, which may or may not be the same as the original encoding.

19) How to convert bytes to long in Java?

You answer this question 🙂

20) Can we cast int to a byte variable? What happens if the value is greater than the byte range?

Yes, we can cast, but Ints are 32-bit in Java and byte is 8-bit, so if cast is, the higher 24 bits of ints are discarded, and byte ranges from -128 to 128.

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

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

Java.lang.Cloneable is an explicit interface that does not contain any methods. The Clone method is defined in the Object class. You also need to know that the Clone () method is a native method, which means it is implemented in C or C ++ or another native language.

23) Is the ++ operator in Java thread-safe?

Not a thread-safe operation. It involves multiple instructions, such as reading variable values, incrementing them, and then storing them back into memory, which can have multiple threads crossing.

24) A = a + b

+= implicitly casts the result type of the add operation to the type that holds the result. If two integers are added, such as byte, short, or int, they are first promoted to int and then added. If the result of the addition operation is larger than the maximum value of a, a+b will generate a compilation error, but a+ = b is fine, as follows:

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

A +b raises a and B to int, so assigning an int to byte will cause a compiler error.

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

No, you can’t assign a double to a long without casting. Double has a wider range than long, so casting is required.

26) 3*0.1 == 0.3 will return what? True or false?

False because some floating-point numbers cannot be represented exactly.

27) Which takes up more memory, int or Integer?

Integer objects take up more memory. Integer is an object whose metadata needs to be stored. But int is a primitive type of data, so it takes up less space.

28) Why are strings Immutable in Java?

Strings are immutable in Java because Java’s designers thought strings were used so frequently that making them immutable would allow multiple clients to share the same String. See the answers for more details.

29) Can we use String in Switch?

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

30) What is a constructor chain in Java?

When you call one constructor from another, that’s the chain of constructors in Java. This can only happen if the class’s constructor is overloaded.

The underlying JVM and Garbage Collection interview questions

31) The length of an int in a 64-bit JVM is the majority?

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

32) What are the differences between Serial and Parallel GC?

Serial and Parallel both cause stop-the-world during GC execution. The main difference between them is that the Serial collector is the default copy collector and only has one thread for GC, while the Parallel collector uses multiple GC threads for GC.

33) For 32-bit and 64-bit JVMS, is the length of a variable of type int the majority?

In 32-bit and 64-bit JVMS, variables of type int are the same length, either 32 bits or 4 bytes.

34) Difference between WeakReference and SoftReference in Java?

Although WeakReference and SoftReference are both beneficial to improving the efficiency of GC and memory, WeakReference will be recovered by GC once it loses the last strong reference, while SoftReference cannot prevent collection. But it can be deferred until the JVM runs out of memory.

35) How does WeakHashMap work?

WeakHashMap works like a normal HashMap, but uses a weak reference as the key, meaning that the key/value is reclaimed when the key object has no reference.

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, the heap memory is suddenly increased, almost doubling, as Pointers to objects are increased from 32-bit to 64-bit. This also adversely affects the amount of data cached by the CPU (which is much smaller than memory). Because the main motivation for moving to a 64-bit JVM is the ability to specify a maximum heap size, some memory can be saved by compressing OOP. With the -xx :+UseCompressedOops option, the JVM uses 32-bit OOP instead of 64-bit OOP.

37) How to determine whether a JVM is 32-bit or 64-bit using a Java program?

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

38) What is the maximum heap memory for 32-bit and 64-bit JVMS?

In theory, 32-bit JVM heap memory can be up to 2^32, or 4GB, but in practice it is much smaller than that. The GB varies depending on the operating system. For example, the GB is 1.5 GB for Windows and 3GB for Solaris. 64-bit JVMS allow you to specify maximum heap memory, theoretically up to 2^64, which is a very large number, and in practice you can specify heap size up to 100GB. Even some JVMS, such as Azul, can have up to 1000GB of heap memory.

39) What are the differences between the JRE, JDK, JVM and JIT?

JRE stands for Java run-time and is required to run Java references. JDK stands for Java Development Kit, which is a development tool for Java programs, such as the Java compiler, which also contains the JRE. The JVM stands for Java Virtual Machine, and its responsibility is to run Java applications. JIT stands for Just In Time compilation. When code execution exceeds a certain threshold, Java bytecode is converted to native code. For example, major hot code is quasi-converted to native code, which can greatly improve the performance of Java applications.

3 years of work experience in Java interview questions

40) Explain Java heap space and GC?

When a Java process is started with a Java command, memory is allocated to it. A portion of memory is used to create heap space, and when objects are created in the program, memory is allocated from the pair space. GC is a process within the JVM that reclaims the memory of invalid objects for future allocation.

JVM bottom level 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 that gc will execute.

42) How to obtain the memory used by Java programs? What percentage of the heap is used?

The remaining memory, total memory, and maximum heap memory can be obtained using the memory-related methods in the java.lang.Runtime class. Using these methods you can also get the percentage of heap usage and the amount of heap memory remaining. Runtime.freememory () returns the number of bytes of freeMemory, runtime.totalmemory () returns the number of bytes of totalMemory, 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 belong to different areas of memory in the JVM and are used for different purposes. Stacks are often used to hold method frames and local variables, while objects are always allocated on the heap. Stacks are typically smaller than the heap and are not shared between multiple threads, whereas the heap is shared by all threads across the entire JVM.

Interview questions and answers about memory

Java basic Concepts interview questions

44) What is the difference between “a==b” and “a. quals(b)”?

If a and b are both objects, then a==b is a reference to compare two objects, and returns true only if a and B refer to the same object in the heap, while a.equals(b) is a logical comparison, so it is often necessary to override this method to provide a logically consistent comparison. For example, the String class overrides equals() so it can be used to compare two different objects that contain the same letters.

45) What does a.hashcode () do? What does it have to do with A. als(b)?

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

46) What is the difference between Final, Finalize and finally?

Final is a modifier that modifies variables, methods, and classes. If final decorates a variable, it means that its value cannot be changed after initialization. Finalize method is a method called before objects are collected to give objects themselves the last chance to revive, but there is no guarantee when To call Finalize. Finally is a keyword that is used with try and catch for exception handling. A finally block must 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 compile-time constants, which are optional. These variables are actually replaced at compile time because the compiler knows their values and knows that they cannot be changed at run time. One problem with this approach is that you use a public compile-time constant from an internal or third-party library, but the value is later changed by someone else, but your client still uses the old value, even if you have deployed a new JAR. To avoid this, be sure to recompile your program when updating dependent JAR files.

Java Collections Framework interview questions

This section also includes interview questions on data structures, algorithms, and arrays

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

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

49) Poll () method and remove() method difference?

Poll () and remove() both fetch an element from the queue, but poll() returns null on failure to fetch an element, and remove() throws an exception on failure.

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 LinkedHashMap maintains the order in which the element was inserted. There is no guaranteed order when traversing a PriorityQueue, but the LinkedHashMap class guarantees that the traversal order is the order in which the elements were inserted.

51) No 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, a book list, does not. Using subscripts to access an element, the time complexity of ArrayList is O(1) and LinkedList is O(n). See answers for more detailed discussion.

52) What are the two ways to sort sets?

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

53) How to print an array in Java?

You can print Arrays using the arrays.tostring () and arrays.deepToString () methods. Because Arrays don’t implement toString(), passing Arrays to system.out.println () won’t print out the contents of the array, but arrays.tostring () will print each element.

54) Is LinkedList unidirectional or bidirectional in Java?

Is a bidirectional linked list, you can check the JDK source. In Eclipse, you can use the shortcut 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 the two classes, some of which are listed below:

A) Hashtable is a legacy of JDK 1, while HashMap was added later.

B) Hashtable is synchronous and slow, but HashMap has no synchronization policy, so it is faster.

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

See the answers for more differences.

57) How does a HashSet in Java work internally?

The inside of a HashSet is implemented using a HashMap. Since maps require keys and values, all keys have a default value. Similar to a HashMap, a HashSet does not allow duplicate keys. Only one NULL key is allowed, meaning that only one NULL object can be stored in a HashSet.

58) Write code to remove an element while iterating through an ArrayList?

The key to this question is whether the interviewer uses the remove() method of ArrayList or Iterator. Here’s a sample code, is to use the right way to realize in the process of traversing remove elements, and won’t appear abnormal ConcurrentModificationException sample code.

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

Yes, you can write your own container class. If you want to iterate with Java’s enhanced loops, you just need to implement the Iterable interface. If you implement the Collection interface, you have this property by default.

60) Default size of ArrayList and HashMap is majority?

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

/ / the 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 objects that are not equal have the same Hashcode?

It is possible that two objects that are not equal may have the same HashCode value, which is why there are conflicts in the HashMap. The rule for equal Hashcode values simply says that if two objects are equal, they must have the same Hashcode value, but there is nothing about unequal objects.

62) Can two identical objects have different hash codes?

No, according to Hash Code, that’s not possible.

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

No, because the objects’ HashCode values must be the same. See the answer for more on 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 typically used to define user-customized orders. Comparable is always only one, but you can have more than one comparator to define the order of objects.

65) Why do I need to override hashCode when overriding equals?

Because there is a mandatory specification to override both hashcode and equal methods, many container classes, such as HashMap and HashSet, rely on hashcode and equals.

Java IO and NIO interview questions

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

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

67) How to create a ByteBuffer in Java?

68) How to read and write ByteBuffer in Java?

69) Is Java big-endian or small-endian?

70) What is the byte order in ByteBuffer?

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

72) What is a memory mapped cache in Java?

73) What is the socket option TCP NO DELAY?

What is the difference between TCP and UDP?

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

Java Best Practices interview questions

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

76) What best practices do you follow when writing multithreaded programs in Java?

Here are some of the best practices I follow when writing concurrent Java programs:

A) Give the thread a name to help with debugging.

B) Minimize the scope of synchronization, instead of synchronizing the entire method, only the key parts.

C) If possible, use volatile rather than synchronized.

D) Use higher-level concurrency tools such as BlockingQueue, CountDownLatch, and Semeaphore instead of wait() and notify() for interthread communication.

E) Use concurrent collections in preference to synchronizing collections. Concurrent collections provide better scalability.

77) Name 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 right collection class, for example, ArrayList instead of Vector if you don’t need to synchronize lists.

B) Use concurrent collections in preference to 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, and so on.

D) Use iterators to loop through collections.

E) Use generics when using collections.

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

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

A) Name the thread

B) Separate threads from tasks and use thread pool actuators to perform Runnable or Callable.

C) Use thread pools

79) Name 5 IO best practices

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

A) Use buffered IO classes instead of reading bytes or characters individually.

B) Use NIO and NIO2

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

D) Use memory-mapped files to get faster IO.

80) List five JDBC best practices that should be followed

There are many best practices, and you can list them according to your preference. Here are some more general principles:

A) Use batch operations to insert and update data

B) Use preparedStatements to avoid SQL exceptions and improve performance.

C) Use a database connection pool

D) Obtain result sets by column names, not by column subscripts.

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

Here are a few best practices for method overloading that you can follow to avoid the chaos of automatic boxing.

A) Do not overload a method that takes an int and another method that takes an Integer.

B) Do not overload methods with the same number of arguments but different order of arguments.

C) If the number of overloaded method parameters is more than 5, variable parameters are used.

Date, Time and Calendar interview questions

82) Is SimpleDateFormat thread-safe in a multithreaded environment?

No, unfortunately, all DateFormat implementations, including SimpleDateFormat, are not thread-safe, so you should not use them in multithreaded sequences unless they are used in an external thread-safe environment. For example, restrict SimpleDateFormat to ThreadLocal. If you don’t, you may get incorrect results when parsing or formatting dates. Therefore, I highly recommend the Joda-time library for all practices in date and time handling.

83) How to format a date in Java? For example, format to 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 that demonstrates formatting dates into different formats, such as DD-MM-YYYY or ddMMyyyy.

In Java, how to display the time zone in a formatted date?

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

86) In Java, how to calculate the difference between two dates?

How to convert a string YYYYMMDD to a date in Java?

Unit test JUnit interview questions

89) How do I test static methods?

You can use the PowerMock library to test static methods.

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

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

92) What is the difference between @before and @beforeclass?

Programming and code related interview questions

93) How do I check if a string contains only numbers?

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

95) Write a Java program that converts byte to long?

95) How do YOU invert a string without using a StringBuffer?

In Java, how do I get the highest frequency of words in a file?

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

99) How do I print all permutations of a string in Java?

100) In Java, how do I print duplicate elements in an array?

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

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

Interview questions about OOP and design patterns

This section covers SOLID design principles from the Java interview process, OOP fundamentals such as classes, objects, interfaces, inheritance, polymorphism, encapsulation, abstraction, and more advanced concepts such as composition, aggregation, and association. GOF design pattern issues are also covered.

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

Interfaces are used to define apis. It defines the rules that classes must follow. At the same time, it provides an abstraction because the client only uses interfaces, which can have multiple implementations, such as the List interface, where you can use arrayLists that are randomly accessible, or linkedLists that are easy to insert and delete. No code is allowed in interfaces to ensure abstraction, but in Java 8 you can declare static default methods in interfaces that are concrete.

104) What is the difference between abstract classes and interfaces in Java?

There are many differences between abstract classes and interfaces in Java, but one of the most important is that Java limits a class to inheriting only one class, but can implement multiple interfaces. Abstract classes can define the default behavior of a family of classes, while interfaces can define the types better, which helps to implement the polymorphism mechanism later. See the answer for a discussion of this question.

105) Besides singletons, what other design patterns have you used in production?

This is based on your experience. In general, you can say dependency injection, factory mode, decorator mode, or observer mode, whichever you’ve used before. But be prepared to answer subsequent questions based on the model you choose.

Can you explain Richter’s substitution principle?

107) Under what circumstances is Demeter’s Law violated? Why is this a problem?

Demeter’s Rule advises “only talk to friends, not strangers” to reduce coupling between classes.

108) What is the adapter mode? When to use it?

The adapter pattern provides transformations to interfaces. If your client uses some interfaces, but you have other interfaces, you can write an adaptation to connect to those interfaces.

109) What are “dependency injection” and “inversion of control”? Why do people use it?

110) What is an abstract class? How is it different from an interface? Why have you ever used abstract classes?

Which is better, constructor injection or setter dependency injection?

Each approach has its disadvantages and advantages. Constructor injection ensures that all injections are initialized, but setter injection provides greater flexibility to set optional dependencies. If XML is used to describe dependencies, Setter injection is 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 patterns?

Although both patterns separate object creation from application logic, dependency injection is cleaner than engineering. With dependency injection, your class is a POJO, and it only knows about dependencies and doesn’t care how they get them. With the factory pattern, your classes need to get dependencies through the factory. Therefore, using DI is easier to test than using factory mode. See answers for a more detailed discussion of this topic.

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

Although the structure of the adapter pattern and the decorator pattern are similar, each pattern appears for a different purpose. The adapter pattern is used to bridge two interfaces, while the decorator pattern is intended to add new functionality to a class without modifying it.

What was the difference between the adapter pattern and the proxy pattern?

This problem is similar to the previous one, the adapter pattern and the proxy pattern differ in their intent. The structure is the same because both the adapter pattern and the proxy pattern encapsulate classes that actually perform actions, but the adapter pattern is used for transformations between interfaces, while the proxy pattern adds an additional middle layer to support allocation, control, or intelligent access.

115) What is the template method pattern?

The template approach provides a framework for algorithms that you can configure or define yourself. For example, you can think of a sorting algorithm as a template. It defines the steps for sorting, but you can use Comparable or something similar in its language for specific comparisons, and the specific policies are up to you to configure. The method of outlining an algorithm is known as the template method.

116) When to use the visitor pattern?

The visitor pattern addresses, but is not directly associated with, adding operations at the inheritance level of a class. This mode adopts the form of double distribution to increase the middle layer.

117) When to use composite mode?

The composite pattern uses a tree structure to show the inheritance relationship between parts and the whole. It allows clients to treat individual objects and object containers in a uniform manner. Use composition mode when you want to show the inheritance of parts to the whole of an object.

118) What is the difference between inheritance and composition?

Although both allow code reuse, composition is more flexible than inheritance because composition allows you to choose different implementations at run time. Code implemented by composition is also simpler to test than inheritance.

119) Describe overloading and overwriting in Java?

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

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

Classes can have multiple nested public static classes inside them, but a Java source file can have only one top-level public class, and the top-level public class name must be the same as the source file name.

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. Composition and aggregation are two forms of association in object orientation. A combination is a stronger association than an aggregation. In composition, one object is the owner of another, while aggregation is the use of one object by another. If object A is composed of object B, then B does not exist if A does not exist, but if object A aggregates an object B, then B can exist alone even if A does not exist.

122) Give me an example of a design pattern that conforms to the open close principle?

The open closed principle requires that your code 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 already tested code. There are several design patterns that are based on the open closed principle, such as the policy pattern. If you need a new policy, you just implement the interface, add configuration, and don’t change the core logic. One working example is the collections.sort () method, which is policy-based and follows the open and close principle. You don’t need to modify sort() 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 the premium mode?

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

For details on how to prepare for an interview, you can refer to my top article!

Gold three silver four has passed, friends should now also reserve nine silver ten, I also have some Java advanced architect information is now free to have the need of friends!

Get way: attention + forward + collect after the private letter I [information] can be free to get!