Java interviews have changed over time. In the old days, knowing the difference between String and StringBuilder would get you straight to the second interview, but now the questions are getting more advanced and interviewers are asking more in-depth questions. When I was starting out, questions like Vector versus Array, HashMap versus Hashtable were popular, and simply remembering them would give you a better chance in an interview, but that’s no longer the case. Today, you’ll be asked about areas that many Java programmers have never looked at, such as NIO, design patterns, sophisticated unit testing, or hard-to-master knowledge such as concurrency, algorithms, data structures, and coding.

\

Since I like to research interview questions, I have collected many interview questions, including many, many different topics. I have been preparing for many of these questions for some time now, and I share them with you. It covers not only classic interview questions like threads, collections, Equals and Hashcode, sockets, but also topics like NIO, arrays, strings, Java 8, and more.

\

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.

\

Luckily for you, there are many good books out there today to help you prepare for Java interviews, and one that I find particularly useful and interesting is Java Programming Interview Exposed by Markham. This book shows you some of the most important topics for Java and JEE interviews, and is worth reading even if you are not preparing for Java interviews.

\

The list of questions is very long, and we have questions from all over the place, so the answers have to be short, concise, crisp, and not sloppy. So, outside of that one paragraph, you’ll just hear questions and answers, nothing else, no feedback, no comments. To that end, I’ve written a few blog posts where you can find my perspective on issues like why I like this question and what are the challenges of this question? What kind of answers are you looking for from the interviewer?

\

This list is a little different, and I encourage you to share your questions and answers in a similar way so that you can easily review them. I hope this list will be of great use to both the interviewer and the candidate, and that interviewers will be able to tweak some of these questions to capture the element of novelty and surprise that is so important for a good interview. Candidates, on the other hand, can extend and test knowledge of key areas of the Java programming language and platform. In 2015, there will be more focus on concurrency concepts, inside JVMS, the difference between 32-bit and 64-bit JVMS, unit testing, and clean code. I’m sure if you read this huge list of Java interview questions, you’ll do well in either a phone interview or a face-to-face interview.

\

Important topics in a Java interview

\

In addition to the amazing number of problems you see, I also try to ensure quality. More than once, I shared questions on various important topics, and also made sure to include so-called advanced topics that many programmers don’t like to prepare for or simply drop because their work doesn’t involve them. The Java NIO and JVM underlayers are the best examples. You can also categorize design patterns into this category, but more and more experienced programmers understand GOF design patterns and apply them. I also try to include the most recent interview questions from 2015 in this list, which are likely to be the focus of the coming year. To give you an idea, here are the topics covered in 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

\

120 Big Java interview questions and answers

\

Now it’s time to show you the 120 questions I’ve collected from interviews over the past five years. I’m sure you’ve seen a lot of these questions in your interviews, and you can answer many of them correctly.

\

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? (the answer)

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 answer)

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

}

\

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:

\

\

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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 answer)

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; (answer answer)

\

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

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? (the answer)

23) 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 = 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? (the answer)

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? (the answer)

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

\

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

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? (answer answer)

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? (answer answer)

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? (answer answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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? (the answer)

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.

java_heaps_memory

\

\

JVM bottom level questions and answers

\

41) Can you guarantee GC execution? (the answer)

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 answer)

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

\

\

\

Java basic Concepts interview questions

\

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

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 answer)

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? (the answer)

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 (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 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? (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

\

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.