1) Can I create a volatile array in Java?
Yes, you can create an array of volatile types in Java, but only a reference to an array, not an entire array. I mean, if you change the array that the reference points to, 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 be able to act as a protection.
2) Does volatile make a non-atomic operation into an atomic operation?
A typical example is a long type member variable in a 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 type variable in Java is not atomic, it needs to be divided into two steps, and if one thread is modifying the value of the long variable, the other thread may see only half of that value (the first 32 bits). However, reading and writing to a volatile long or double variable is atomic.
3) What is the practice of 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 64 bits wide, so for these two types of reading is divided into two parts, the first read the first 32 bits, and then read the remaining 32 bits, the process is not atomic, but the Java volatile type long or double variable read and write is atomic. Another effect of the volatile modifier is to provide memory barriers (barrier), such as applications in distributed frameworks. Simply put, it is when you write a volatile variable that the Java memory model inserts a write barrier (write barrier), and before reading a volatile variable, it inserts a reading barrier (read barrier). This means that when you write a volatile domain, you can ensure that any thread can see the value you write, and that the update of any value is visible to all threads before writing, because the memory barrier updates all other write values to the cache.
4) What are the guarantees for volatile type variables?
Volatile variables provide order and visibility guarantees, for example, the JVM or JIT reordering statements for better performance, but the volatile type variable is not reordered with other statements even if there are no synchronized blocks. Volatile provides happens-before guarantees that a thread's modifications can be visible to other threads. In some cases, volatile can also provide atomicity, such as reading 64-bit data types, such as long and double are not atomic, but the volatile type of double and long is atomic.
5) How do you call the Wait () method? Do you use an if block or a loop? Why?
The wait () method should be called in a loop, because when the thread gets to the CPU to start executing, other conditions may not be met, so it is better to have the loop detection condition satisfied before processing. The following is a standard code for using the 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
}
6) What is pseudo-sharing in a multithreaded environment (false sharing)?
Pseudo-sharing is a well-known performance issue in multithreaded systems where each processor has its own local cache. Pseudo-sharing threads that occur on different processors are dependent on the same cache line for the modification of the variable, as shown in:
7) What is Busy spin? Why should we use it?
BUSY Spin is a technology that waits for events on the basis of not releasing the CPU. It is often used to avoid losing data in the CPU cache (if the thread pauses first, then runs on other CPUs are lost). So, if your job requires low latency, and your threads are not currently in any order, you can instead call the sleep () or wait () method by looping through new messages in the queue. The only benefit is that you just have to wait a short time, such as a few microseconds or a few nanoseconds. The LMAX distributed framework is a library of high-performance inter-thread communication that has a busyspinwaitstrategy class that is based on this concept and uses the busy spin loop eventprocessors to wait for the barrier.
8) What are thread local variables?
A thread local variable is a variable that is confined to the thread itself and is owned by the thread itself and is not shared among multiple threads. Java provides the ThreadLocal class to support thread-local variables, which is a way to implement thread safety. However, when using thread-local variables in a managed environment (such as a Web server), you should be particularly careful, in which case the worker thread has a longer life cycle than any application variable. Once any thread local variable is not released after the work is completed, there is a risk of a memory leak in the Java application.
9) What is the difference between the sleep method and the Wait method in Java?
While both are used to pause the currently running thread, sleep () is actually just a short pause because it does not release the lock, and wait () means that the condition waits, which is why the method is releasing the lock because the other waiting thread can get to the lock when the condition is met.
10) What are immutable objects (immutable object)? How do I create an immutable object in Java?
Immutable objects means that once an object is created, the state can no longer be changed. Any modifications will create a new object, such as String, Integer, and other wrapper classes.
11) Can we create an immutable object that contains Mutable objects?
Yes, we can create an immutable object that contains Mutable objects, you just have to be careful not to share references to mutable objects, and if you need to change, return a copy of the original object. The most common example is a reference to an object that contains a Date object.
data types and Java Basics interview questions
What data types should be used in Java to represent prices?
If you are not particularly concerned about memory and performance, use BigDecimal, otherwise use a double type of predefined precision.
13) How do I convert a byte to a String?
You can use the constructor of the String to receive the byte[] parameter to convert, the point to be aware of is the correct encoding to use, otherwise the platform default encoding, which may be the same as the original encoding, or may be different.
14) can we cast int to a variable of type byte? What happens if the value is greater than the range of type byte?
Yes, we can do the cast, but the int in Java is 32 bits, and byte is 8 bits, so if coercion is, the high 24 bits of the int type will be discarded, and the range of byte type is from-128 to 128.
is the Java + + operator thread-safe?
is not a thread-safe operation. It involves multiple instructions, such as reading the value of a variable, increasing it, and then storing it back into memory, and this process may occur when multiple threads are involved.
A = the difference between A + B and a + = b?
+ = implicitly casts the result type of the plus operation to the type holding the result. If two of these integers are added, such as Byte, short, or int, they are first promoted to the int type, and then the addition operation is performed. If the result of the addition operation is greater than the maximum value of a, then A+b will have a compile 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
Note: In fact, regardless of the value of A+b, the compiler will error, because the a+b operation will promote A, b to the int type, so the int type is assigned to byte will compile an error
17) Can I assign a double value to a variable of type long without casting?
No, you can't. You cannot assign a double value to a variable of type long without forcing a type conversion, because the range of double types is wider than the long type, so you must cast.
18) 3*0.1 = = 0.3 What will be returned? True or False?
False, because some floating-point numbers are not exactly represented.
int and Integer which will consume more memory?
An Integer object consumes more memory. An Integer is an object that needs to store the object's metadata. But int is a primitive type of data, so it takes up less space.
20) Why is the String in Java immutable (immutable)?
The string in Java is immutable because Java designers believe that strings are used very frequently, and that setting the string to immutable allows multiple clients to share the same string.
What is the constructor chain in Java?
When you call another constructor from a constructor, it is the constructor chain in Java. This situation only occurs when the constructor of the class is overloaded.
interview questions for the JVM underlying and GC (garbage Collection)
22) in a 64-bit JVM, the length of int is the majority?
In Java, the length of an int type variable is a fixed value, regardless of the platform, and is 32 bits. This means that in 32-bit and 64-bit Java virtual machines, the length of the int type is the same.
) What is the difference between Serial and Parallel GC?
Serial and Parallel will cause stop-the-world when the GC executes. The main difference between them is that the serial collector is the default copy collector, there is only one thread when the GC is executed, and the parallel collector uses multiple GC threads to execute.
24) The length of the 32-bit and 64-bit Jvm,int type variables is the majority?
In 32-bit and 64-bit JVMs, the length of the int type variable is the same, both 32-bit or 4-byte.
What is the difference between WeakReference and softreference in Java?
Although both WeakReference and softreference contribute to the efficiency of GC and memory, WeakReference, once the last strong reference is lost, is recycled by GC, and soft references, although not prevented from being recycled, can be deferred to the JVM's low-memory When
How does Weakhashmap work?
Weakhashmap's work is similar to normal HashMap, but using a weak reference as key means that Key/value will be recycled when the key object does not have any references.
What is the role of the JVM option-xx:+usecompressedoops? Why should I use it?
When you migrate your app from a 32-bit JVM to a 64-bit JVM, the heap memory increases abruptly, almost doubling, as the object's pointer increases from 32 bits to 64 bits. This can also adversely affect the CPU cache (which is much smaller than memory). Because the primary motivation for migrating to a 64-bit JVM is to specify the maximum heap size, you can save some memory by compressing OOP. With the-xx:+usecompressedoops option, the JVM uses 32-bit OOP instead of 64-bit OOP.
28) How to determine whether the JVM is 32-bit or 64-bit through a Java program?
You can check some system properties such as Sun.arch.data.model or os.arch to get that information.
29) What is the maximum heap memory for 32-bit JVM and 64-bit JVM, respectively?
In theory, the 32-bit JVM heap memory can reach 2^32, or 4GB, but is actually much smaller than this. Different operating systems, such as the Windows system about 1.5 gb,solaris about 3GB. The 64-bit JVM allows you to specify the maximum heap memory, which can theoretically reach 2^64, which is a very large number, and you can actually specify the heap memory size to 100GB. Even some jvms, such as Azul, heap memory to 1000G are possible.
What is the difference between JRE, JDK, JVM, and JIT?
The JRE represents the Java runtime (Java run-time), which is required to run Java references. The JDK represents the Java development tool (Java Development Kit) and is a development tool for Java programs, such as the Java compiler, which also contains the JRE. The JVM represents the Java virtual machine, which is responsible for running Java applications. JIT stands for Instant compilation (Just in Time compilation), and when code executes more than a certain threshold, Java bytecode is converted to native code, such as the main hotspot code being switched to native code, which can greatly improve the performance of Java applications.
31) Explain Java heap space and GC?
When the Java process is started through a Java command, it allocates memory for it. Part of the memory is used to create the heap space, and the memory is allocated from the space when the object is created in the program. A GC is a process inside the JVM that reclaims the memory of an invalid object for future allocations.
32) Can you guarantee the GC to execute?
No, although you can call System.GC () or RUNTIME.GC (), there is no way to guarantee the execution of the GC.
33) How to get the memory used by the Java program? Percentage of heap usage?
The memory-related methods in the Java.lang.Runtime class can be used to obtain the remaining memory, the total memory, and the maximum heap memory. With these methods you can also get the percentage of heap usage and the remaining space of heap memory. The Runtime.freememory () method returns the number of bytes of space remaining, the number of bytes of total memory in the Runtime.totalmemory () method, and Runtime.maxmemory () returns the maximum memory bytes.
What is the difference between heap and stack in Java?
The heap and stack in the JVM belong to different memory regions and are used for different purposes. Stacks are often used to save method frames and local variables, and objects are always allocated on the heap. Stacks are usually smaller than heaps and are not shared across multiple threads, and the heap is shared by all threads of the entire JVM.
Java Basic concept surface question
What is the difference between "a==b" and "A.equals (b)"?
If both A and B are objects, a==b is a reference to compare two objects, and only if A and B point to the same object in the heap to return true, whereas A.equals (b) is a logical comparison, it is often necessary to override the method to provide a comparison of logical consistency. For example, the String class overrides the Equals () method, so it can be used for two different objects, but contains the same letters as the comparison.
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 integral type. It is often 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.
The difference between final, Finalize, and finally?
Final is a modifier that can modify variables, methods, and classes. If the final modifier variable, it means that the value of the variable cannot be changed after initialization. The Finalize method is a method that is called before the object is recycled, giving the object its own last chance of resurrection, but when it is called Finalize is not guaranteed. Finally is a keyword that is used in conjunction with try and catch for exception handling. The finally block is bound to be executed regardless of whether an exception occurred in the try block.
What is the compile-time constant in Java? What's the risk of using it?
The public static immutable final variable is what we call the compile-time constants, and here is the publicly available option. In fact, these variables are replaced at compile time because the compiler knows the values of these variables and knows that these variables cannot be changed at run time. One problem with this approach is that you use a public compile-time constant in an internal or third-party library, but the value is changed by someone else, but your client is still using the old value, and even you have deployed a new jar. To avoid this situation, be sure to recompile your program when you update the dependent JAR file.
face questions in the Java collection framework
What is the difference between List, Set, Map, and Queue?
List is an ordered set that allows elements to be duplicated. Some of its implementations can provide constant access time based on subscript values, but this is not guaranteed by the List interface. Set is an unordered collection.
The difference between the poll () method and the Remove () method?
Both poll () and remove () remove an element from the queue, but poll () returns NULL when the element fails, but the remove () throws an exception when it fails.
What is the difference between Linkedhashmap and priorityqueue in Java?
Priorityqueue the element that guarantees the highest or lowest priority is always on the head of the queue, but the order in which Linkedhashmap is maintained is the order in which the elements are inserted. There is no guarantee of order when traversing a priorityqueue, but the Linkedhashmap class guarantees that the traversal order is the order in which the elements are inserted.
ArrayList and LinkedList are not different?
The most obvious difference is that the arrraylist underlying data structure is an array that supports random access, while LinkedList's underlying data structure book list does not support random access. Using the subscript to access an element, the time complexity of the ArrayList is O (1), while the LinkedList is O (n).
43) in which two ways to achieve the sorting of the collection?
You can use an ordered set, such as TreeSet or TREEMAP, or you can use a sequential collection, such as list, and then sort by collections.sort ().
How do I print a group in Java?
You can use the arrays.tostring () and arrays.deeptostring () methods to print an array. Because the array does not implement the ToString () method, if you pass the array to the SYSTEM.OUT.PRINTLN () method, you will not be able to print the contents of the group, but arrays.tostring () can print each element.
What is the difference between Hashtable and HashMap?
These two classes have many different places, some of which are listed below:
A) Hashtable is a class left over from JDK 1, and HashMap is later added.
b) Hashtable is synchronous and slower, but HashMap has no synchronization policy, so it will be faster.
c) Hashtable does not allow an empty key, but HASHMAP allows a null key to appear.
HashSet in Java, how does the interior work?
The interior of the HashSet is implemented using HashMap. Since the MAP requires key and value, all keys have a default value. Similar to Hashmap,hashset does not allow duplicate keys, only a null key is allowed, meaning that only one null object is allowed in HashSet.
47) Write a piece of code to remove an element while traversing ArrayList?
The key to the problem is whether the interviewer is using the ArrayList remove () or the Iterator remove () method. Here is a sample code that uses the correct way to implement the sample code that removes the element during traversal without the concurrentmodificationexception exception.
48) Can we write a container class by ourselves and then use the For-each loop code?
Yes, you can write a container class of your own. If you want to use the enhanced loops in Java to traverse, you only need to implement the Iterable interface. If you implement the Collection interface, this property is the default.
The default size of ArrayList and HashMap is the majority?
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 for the ArrayList and HashMap classes in Java 7:
From Arraylist.java JDK 1.7
private static final int default_capacity = 10;
From Hashmap.java JDK 7
static final int default_initial_capacity = 1 << 4; aka 16
50) is it possible that two unequal objects have the same hashcode?
It is possible that two unequal objects might have the same hashcode value, which is why there is a conflict in the HashMap. The provisions of the equal Hashcode value only say that if two objects are equal, the same hashcode value must be there, but there is no provision for unequal objects.
51) Two of the same objects will have different hash code?
No, according to the hash code, this is not possible.
52) 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.
In Java, what is the difference between Comparator and comparable?
The comparable interface is used to define the natural order of objects, and comparator is typically used to define the order in which users are customized. Comparable always have only one, but you can have multiple comparator to define the order of the objects.
54) Why do I need to override the Hashcode method when overriding the Equals method?
Because there are mandatory specification designations that require both rewriting hashcode and equal are methods, many container classes, such as HashMap, HashSet, are dependent on the provisions of hashcode and equals.
interview questions for Java best practices
In Java, what are some of the best practices you'll follow when you're writing a multi-threaded program?
A) give the thread a name that can help with debugging.
b) Minimize the range of synchronizations, rather than synchronizing the entire method, synchronizing only the critical parts.
c) If possible, more inclined to use volatile rather than synchronized.
d) Use higher-level concurrency tools instead of using wait () and notify () to implement inter-thread communication, such as Blockingqueue,countdownlatch and Semeaphore.
e) Prioritize the use of concurrent collections instead of synchronizing the collections. Concurrent collections provide better scalability.
56) What are some of the best practices for using collections in Java?
A) Use the correct collection class, for example, if you do not need to synchronize the list, use ArrayList instead of Vector.
b) Prioritize the use of concurrent collections instead of synchronizing the collections. Concurrent collections provide better scalability.
c) Use interfaces to represent and access collections, such as using list storage ArrayList, using MAP storage HashMap, and so on.
d) Use iterators to loop the collection.
e) Use generics when using collections.
57) say best practices for using threads in Java?
A) name the thread
b) Detach the thread from the task and use the thread pool executor to execute Runnable or callable.
c) using the thread pool
58) say best practices for IO?
A) Use the IO class with buffers instead of reading bytes or characters separately.
b) Use of NIO and NIO2
c) Close the stream in the finally block, or use the Try-with-resource statement.
d) Use a memory-mapped file for faster IO.
59) List the JDBC best practices that should be followed?
A) Use bulk operations to insert and update data
b) Use PreparedStatement to avoid SQL exceptions and improve performance.
c) using a database connection pool
D) Get the result set by column name and do not use the subscript of the column to get it.
60) say a few best practices for method overloading in Java?
A) do not overload such a method: One method receives an int parameter, and the other method receives an Integer parameter.
b) do not overload the same number of parameters, but only a different order of the parameters.
c) If the overloaded method has more than 5 parameters, a variable parameter is used.
face questions for Date, time, and Calendar
61) 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 it in a multi-line program, unless you are using it in an externally threaded environment, such as restricting SimpleDateFormat to The ThreadLocal. If you do not, you may get an incorrect result when parsing or formatting the date. Therefore, I strongly recommend the Joda-time library for all the practices of date and time processing.
) How do I format a date in Java? As formatted as a ddmmyyyy form?
In Java, you can use the SimpleDateFormat class or the Joda-time library to format dates. The DateFormat class allows you to format dates using a variety of popular formats. See the example code in the answer, which demonstrates formatting dates into different formats, such as DD-MM-YYYY or ddmmyyyy.
face questions about OOP and design patterns
63) What is an interface? Why use interfaces instead of using specific classes directly?
Interface is used to define the API. It defines the rules that a class must follow. At the same time, it provides an abstraction, because the client uses only the interface, so that there can be multiple implementations, such as the List interface, you can use random access to the ArrayList, you can also use easy to insert and delete the LinkedList. The interface does not allow writing code to guarantee abstraction, but in Java 8 you can declare a static default method on the interface, which is specific.
In Java, what is the difference between an abstract class and an interface?
In Java, abstract classes and interfaces have many differences, but the most important one is that Java restricts a class to inherit only one class, but can implement multiple interfaces. Abstract classes can well define the default behavior of a family class, and the interface can define the type better, which helps to implement the polymorphic mechanism later. Please see the answer to the discussion on this issue.
65) In addition to the singleton mode, what design patterns have you used in the production environment?
This needs to be answered according to your experience. In general, you can say that depending on injection, Factory mode, decoration mode or observer mode, feel free to choose one of the things you have used. But you have to be prepared to answer questions that are based on the pattern you choose.
66) What is the adapter mode? When do I use it?
The adapter mode provides a translation of the interface. If your client uses some interfaces, but you have other interfaces, you can write an adapter to connect the interfaces.
67) constructor injection and setter dependency injection, that way better?
Each of these approaches has its drawbacks 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 can be read-write more strongly. The rule of thumb is to enforce dependency using constructor injection, optionally relying on setter injection.
68) What is the difference between dependency injection and engineering mode?
While both modes separate the creation of objects from the application logic, dependency injection is clearer than engineering mode. By relying on injection, your class is POJO, it knows only the dependencies and doesn't care how they get. With Factory mode, your class needs to get dependencies through the factory. Therefore, using DI is easier to test than using the Factory mode.
69) What is the difference between adapter mode and adorner mode?
Although the adapter pattern and adorner pattern are similar in structure, each pattern has a different intent. The adapter mode is used to bridge two interfaces, and the purpose of the adornment mode is to add new functionality to the class without modifying the class.
70) What is the difference between adapter mode and proxy mode?
This problem is similar to the previous one, where the difference between adapter mode and proxy mode is that they have different intentions. Because both the adapter mode and the proxy pattern are classes that encapsulate the actual execution of the action, the structure is consistent, but the adapter pattern is used for the conversion between interfaces, while the proxy mode is to add an additional middle tier to support allocation, control, or intelligent access.
71) What is the template method mode?
The template method provides the framework for the algorithm, and you can configure or define the steps yourself. For example, you can consider a sorting algorithm as a template. It defines the steps of sequencing, but the specific comparisons can be made using comparable or something similar in their language, and the specific strategy is for you to configure. The method for listing algorithm summaries is a well-known template approach.
72) When do I use the visitor mode?
The visitor pattern is used to resolve additions to the class's inheritance hierarchy, but is not directly associated with it. This model uses a double distribution to increase the middle tier.
73) When do I use the combo mode?
The combined pattern uses a tree structure to show part-to-whole inheritance relationships. It allows clients to treat individual objects and object containers in a uniform form. The combination pattern is used when you want to show the inheritance of this part of the object to the whole.
74) What is the difference between inheritance and composition?
While both can implement code reuse, the combination is more flexible than inheritance, because the combination allows you to choose different implementations at run time. Code implemented in combination is also easier to test than inheritance.
75) Describe the overloads and overrides in Java?
Overloading and overriding allow you to implement different functions with the same name, but overloading is a compile-time activity, and overrides are run-time activities. You can overload a method in the same class, but only the method can be overridden in a subclass. Overrides must have inheritance.
In Java, what is the difference between a nested public static class and a top-level class?
A class can have more than one nested public static class, but a Java source file can have only one top-level public class, and the name of the top-level public class must be the same as the source file name.
What is the difference between composition, aggregation, and association in OOP?
If two objects are related to each other, they are said to be associated with each other. Composition and aggregation are two forms of affinity in an object-oriented way. A combination is a more powerful association than aggregation. In combination, one object is the owner of another, and aggregation refers to one object using another object. If object A is composed of object B, then a does not exist, B must not exist, but if a object aggregates an object B, then B can exist alone even if a does not exist.
78) Give me an example of a design pattern that fits the opening and closing principle?
The open and close principle requires that your code be opened to extensions and closed to modifications. This means that if you want to add a new feature, you can easily add new code without changing the code you've already tested. There are several design patterns that are based on the open/closed principle, such as the strategy mode, if you need a new strategy, just implement the interface, add configuration, and do not need to change the core logic. A working example is the Collections.sort () method, which is based on the policy pattern, which follows the open and closed principle, you do not need to modify the sort () method for the new object, all you have to do is implement your own Comparator interface.
79) When do I use the enjoy meta mode?
The enjoy meta mode avoids creating too many objects by sharing objects. In order to use the enjoy meta mode, you need to make sure that your objects are immutable so that you can share them securely. The String pool, the Integer pool, and the long pool in the JDK are good examples of using the enjoy meta pattern.
The basic problems of multithreading, concurrency, and threading