Preface:
Third day of working from home. Move within 10 square meters every day. Buttocks are sore, numb!
This article is not original. To arrange the income! But the content is dry! It helps that I read it. Make a share.Copy the code
This list contains questions for both entry-level Java programmers and senior developers with years of experience. Whether you’re a developer with 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10 years of experience, there are some interesting questions to be asked. It contains questions that are super easy to answer, as well as questions that experienced Java programmers would struggle with.
In the upcoming job interview season of Jinsanyinsi, congratulations to you all on getting the offer in advance. Bright future, bright future, prosperous future, thriving, lucky !!!!!!!
(All nice things to say)Copy the code
Now I have organized more than 1000 Java interview questions from more than 400 pages of PDF documents, which have been organized by topic. There are also hundreds of pages of Java core knowledge PDFS, and a huge amount of learning materials
Welcome everyone to pay attention to the public number to receive, reply: PDF can, by the way to everyone for a praise, point a concern! Hey hey
I am timothy
A flood of moral integrity, a awe-inspiring, upright Java programmer
Body:
Here are the topics covered by this Java interview question list:
- Multithreading, concurrency and threading basics
- Basic principles of data type conversion
- Garbage Collection (GC)
- Java Collections Framework
- An array of
- string
- GOF design patterns
- SOLID (single function, open/close principle, Richter substitution, interface isolation and dependency inversion) design principles
- Abstract classes and interfaces
- Java basics such as Equals and HashCode
- Generics and enumerations
- Java IO and NIO
- Common Network Protocols
- Data structures and algorithms in Java
- Regular expression
- The JVM the underlying
- Java Best Practices
- JDBC
- The Date, Time and Calendar
- The Java XML processing
- JUnit
- programming
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
methodsynchronized (obj)
{
while (condition does not hold)obj.wait();
// (Releases lock, and reacquires on wakeup)...
// Perform action appropriate to condition
}
Copy the code
See Effective Java article 69 for more on why you should call the wait method in a loop.
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:
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.
Java interview questions for experienced programmers
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?
When using ThreadLocal to maintain variables,ThreadLocal provides a separate copy of the variable for each thread that uses the variable. Each thread can change its own copy independently without affecting the corresponding copy of other threads, which is thread-isolated. The secret to thread isolation lies in the ThreadLocalMap class (the static inner class of ThreadLocal)
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.
ThreadLocal methods: void set(T value), T get(), and T initialValue().
How ThreadLocal creates copies of variables for each thread:
First of all, a ThreadLocal. Inside each Thread Thread ThreadLocalMap types of member variables threadLocals, copy the threadLocals is used to store the actual variable, the key value for the current ThreadLocal variables, Value is a copy of a variable (that is, a variable of type T). When called from the get() or set() function of a ThreadLocal variable, threadLocals will be initialized with the current function as the key. The copy variable to be saved as value by ThreadLocal is saved to threadLocals. Then in the current thread, if you want to use duplicate variables, you can look them up in threadLocals using the get method.
Conclusion:
A. The actual copies created by ThreadLocal are stored in each thread’s own threadLocals
B. The key value of a threadLocals map is a ThreadLocal object, since there can be multiple ThreadLocal variables per thread, like longLocal and stringLocal.
C, before performing get, must first set, otherwise a null pointer exception will be reported; You must override the initialValue() method if you want to access it without calling set before get
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?
String receives bytes constructor converted to String, then long.parselong
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 in Java are 32 bits and byte is 8 bits, so if cast is, the higher 24 bits of ints are discarded, and byte ranges from -128 to 127.
21) There are two classes, B inherits A and C inherits B. Can we convert B to C? C = (C) B;
Yes, go down. However, it is not recommended to use this command because type transformation exceptions may occur.
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.
byte a = 127;
byte b = 127;
b = a + b;
// error : cannot convert from int to byteb += a; // ok
Copy the code
(Since a+b promotes a and b to int, assigning int to byte causes a compilation 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?
There are four types of references in Java. StrongReference, SoftReference, WeakReference, and PhantomReference.
StrongReference is a Java default reference implementation that lives in the JVM as long as possible and is reclaimed by the GC if no object points to it
WeakReference, as the name implies, is a WeakReference that is reclaimed by GC when the referenced object no longer has a strong reference in the JVM
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. SoftReference retains references as long as possible before being reclaimed when the JVM runs out of memory (a VIRTUAL machine guarantee), which makes SoftReference ideal for caching applications
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 applications. 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.geTruntime ().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. Difference between stack and heap memory in Java
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. Java technology allows you to use the Finalize () method to do the necessary cleanup before the garbage collector purifies objects from memory. This method is called by the garbage collector when it determines that the object is not referenced, 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 (answer)
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? (the answer)
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 answer)
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? (the answer)
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? (answer answer)
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? (the answer)
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? (the answer)
TreeMap in Java is implemented using red-black trees.
56) What is the difference between Hashtable and HashMap? (the answer)
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? (answer answer)
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 answer)
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 use a for-each loop?
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? (the answer)
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:
// 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
Copy the code
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()? (the answer)
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 answer)
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? (the answer)
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? (the answer)
Here are some of the best practices I follow when writing concurrent Java programs: a) Give threads names that 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 (answer)
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 (Java7) 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?
Add Z yyyY-MM-DD HH: MM: ss.sss Z to pattern
85) What is the difference between java.util.Date and java.sql.Date?
Java.sql. Date is used for SQL statements, which contain only the Date and no time part. They all have a getTime method that returns the number of milliseconds, so they can be built directly. Date is the parent class of java.sql.Date.Date is the parent class of java.sql.Date.Date is the parent class of java.sql.Date, which is used to format or obtain the current time. Because the second argument to PreparedStament setDate() and the second argument to ResultSet getDate() are both java.sql.date.
86) In Java, how to calculate the difference between two dates?
public static int dateDiff(Date d1, Date d2) throws Exception
{
long n1 = d1.getTime();long n2 = d2.getTime();
long diff = Math.abs(n1 - n2);
diff /= 3600 * 1000 * 24;
return diff;
}
Copy the code
How to convert a string YYYYMMDD to a date in Java?
SimpleDateFormat’s parse method
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? (Solution)
94) How to write an LRU cache using generics in Java? (the answer)
95) Write a Java program that converts byte to long? (the answer)
95) How do YOU invert a string without using a StringBuffer? (Solution)
In Java, how do I get the highest frequency of words in a file? (Solution)
98) How do I check that two given strings are in reverse order? (Solution)
99) How do I print all permutations of a string in Java? (Solution)
100) In Java, how do I print duplicate elements in an array? (Solution)
101) How to convert a string to an integer in Java? (Solution)
102) How can I exchange the values of two integer variables without using temporary variables? (Solution)
Swap two values, no temporary variables, okay? We do this by xOR in bit operations. // The test code is C language code
Pre-knowledge:
1. If an integer is xor with itself, the result is 0 // Because the rule of xor is, same is 0, different is 1, note that this is all binary bits.
2. If any integer is xor with 0, the result is itself. // Because 1 xor 0 is 1,0 xor 0 is 0, so 1 is still 1,0 is still 0.
The test code is as follows:
int main(int argc, char* argv[])
{
int a=575,b=667;
a=a^b;
b=a^b;
a=a^b;
printf("a=%d b=%d \n",a,b);
getchar();
return 0;
}
Copy the code
// The effect screenshot is as follows:
Analyze the reasons for the exchange between A and B:
From the above code, it is not difficult to obtain the following expression:
1. b=(a^b)^b=a^b^b=a
2. a=(a^b)^[(a^b)^b]=a^b^[a^b^b]=a^b^a^b^b=a^a^b^b^b=b
Copy the code
It’s not hard to see why a and B have swapped, based on what I said before.
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? (the answer)
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? (the answer)
107) Under what circumstances is Demeter’s Law violated? Why is this a problem? (the answer)
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? (the answer)
110) What is an abstract class? How is it different from an interface? Why have you ever used abstract classes? (the answer)
Abstract method: the method modified by abstract is abstract method. Abstract method only has the definition of method, but does not have the implementation of method. Abstract classes: If a class contains abstract methods, all classes I should be declared abstract using the abstract keyword. Abstract classes cannot be instantiated. A class can be defined as abstract even if it has no abstract methods in it. Similarly, it cannot be instantiated.
The meaning of abstract classes:
1. Provide a common type for subclasses. 2. Encapsulate repeated content (member variables and methods) in subclasses; 3. Abstract methods are defined. Although subclasses have different implementations, the definition of this method is consistent.Copy the code
Abstract class: provides the same method entry for subclasses in order to be inherited by subclasses. Interface: defines a standard (a special abstract class).
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 factory 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.
A variety of other Java interview questions
This section contains Java interview questions on XML, JDBC interview questions, regular expression interview questions, Java errors and exceptions, and serialization interview questions
125) What is the difference between nested static classes and top-level classes?
A common top-level class has the same source file name as the class name, whereas nested static classes do not have this requirement. A nested class is inside a top-level class, and the name of the top-level class needs to be used to refer to the nested static class, such as HashMap.Entry, which is a nested static class, HashMap, which is a top-level class, and Entry, which is a nested static class.
126) Can you write a regular expression to determine if a string is a number?
A numeric string can contain only digits, such as 0 through 9 and the beginning of + and -. With this information, you can use the following regular expression to determine whether a given string is a number.
127) What is the difference between checked and unchecked exceptions in Java?
The checked exception compiler checks during compilation. For such exceptions, methods enforce handling or declare them via throws clause. One of these cases is a subclass of Exception but not RuntimeException. Unchecked is a subclass of RuntimeException that is not checked by the compiler at compile time.
Throws throws 128) What is the difference between throws and throws?
Throw is used to throw an instantiated object of the java.lang.Throwable class. This means that you can throw an Error or an Exception using the keyword throw, as in: Throw New IllegalArgumentException(” size must be multiple of 2 “) And throws an exception as part of the method declaration and signature so that the caller can handle it. In Java, any unchecked checked exception is forced to be declared in the THROWS clause.
129) How is Serializable different from Externalizable in Java?
Serializable interface Serializable interface is an interface that serializes Java classes so that they can be transferred over the network or their state can be stored on disk. It is the default serialization method embedded in the JVM and is expensive, fragile, and insecure. Externalizable allows you to control the entire serialization process, specify specific binary formats, and add security mechanisms.
130) What is the difference between DOM and SAX parsers in Java?
The DOM parser loads the entire XML document into memory to create a DOM model tree, which makes it faster to find nodes and modify the XML structure, whereas the SAX parser is an event-based parser that does not load the entire XML document into memory. For this reason, DOM is faster and requires more memory than SAX, and is not suited for parsing large XML files.
131) Name three new features in JDK 1.7?
While JDK 1.7 isn’t as big as JDK 5 and 8, there are a number of new features, such as try-with-resource statements, that allow you to use streams or resources without having to manually close them. Fork-join pooling implements the Java version of Map-Reduce to some extent. Allow String variables and text in Switch. The diamond operator (<>) is used for type inference and eliminates the need to declare generics on the right side of variable declarations, resulting in stronger, cleaner code that can be read and written. Another feature worth mentioning is improved exception handling, such as allowing multiple exceptions to be caught in the same catch block.
132) Name five new features introduced in JDK 1.8?
Java 8 is a groundbreaking release in Java history. Here are five key features in JDK 8: Lambda expressions, which allow anonymous functions to be passed like objects through the Stream API, take full advantage of modern multicore cpus to write very concise code in the Date and Time API. Finally, there is a stable, simple Date and Time library that you can use to extend methods. Now, Interfaces can have static, default methods. Repeat annotations. Now you can use the same annotation multiple times on the same type.
133) What is the difference between Maven and ANT in Java?
While both are build tools for creating Java applications, Maven does more, providing a standard Java project structure based on the concept of convention over configuration while automatically managing dependencies (JAR files that the application depends on). See the answers for more differences between Maven and ANT tools.
Finally:
That’s all the interview questions, right?
If you see this, I'll give you a thumbs up too!Copy the code
I can guarantee that if you can answer all the questions on this list, you can easily handle any core Java or advanced Java interview.
Although servlets, JSP, JSF, JPA, JMS, EJB and other Java EE technologies are not covered here, and mainstream frameworks such as Spring MVC, Struts 2.0, Hibernate are not included. SOAP and RESTful Web Services are not included either, but this list is also useful for Java developers who are preparing for Java Web development positions, because all of the Java interviews, The initial questions are all about Java basics and JDK apis.
If you think I have any popular Java issues that should be on this list and I’ve left them out, feel free to give me suggestions.
My goal is to create an up-to-date list of the best Java interview questions from recent interviews.
Now I have organized more than 1000 Java interview questions from more than 400 pages of PDF documents, which have been organized by topic. There are also hundreds of pages of Java core knowledge PDFS, and a huge amount of learning materials
Welcome everyone to pay attention to the public number to receive, reply: PDF can, by the way to everyone for a praise, point a concern! Hey hey
I am timothy
A flood of moral integrity, a awe-inspiring, upright Java programmer