98 Java interview questions you need to know
By Jamie Mercer
Special thanks to Shane O’Sullivan and the team from Jibestream for their help with this article.
You’ve got the interview—now what? While some job interviews can follow a straightforward, simple question and answer format, in the Java industry, preparing for an interview can be slightly more difficult.
Back in the day, it used to be about knowing the difference between specific programming languages, but now Java interview questions are becoming more advanced.
These days, you are more likely to be asked questions from the areas of Java that a developer might not typically be familiar with, e.g. NIO patterns, algorithms, data structures, and coding.
Java interviews are known to be a little different than the other traditional programming interviews. Firstly, even though there will be questions about Data Structure and Algorithms, e.g. String or Array, you will still be able to clear these interviews if you are not a technical expert in them.
Considering Java is mainly used as an application programming language, the focus is associated accordingly with questions typically focusing on API and core concepts.
There is no way of guaranteeing which questions you will be asked in an interview, but it’s always better to be familiar with the frequently asked core Java interview questions.
Popular Topics to Consider for a Java Interview
There are a few topic areas to focus on when preparing for a Java interview and you should brush up on the following areas:
Concepts from core Java:
- OOPS concepts (Data Abstraction, Encapsulation, Inheritance, Polymorphism)
- Basic Java constructs like loops and data types
- String handling
- Collection framework
- Exception handling
- Serialisation & De-serialisation
- Concurrent collection
- JDBC (Java Database Connectivity)
- Spring (MVC, Core, JDBC, ORM, AOP)
- Hibernate ORM framework
- Web Services (SOAP & REST)
- Design patterns and design questions related to your projects.
With Java being around as long as it has, there are some reliable and credible books available to help prepare for Java interviews. A recommended book is Java Programming Interview Exposed by Noel Markham.
As a Java developer, it is worth reading this book to take you through some of the most important topics for Java interview, even if you aren’t specifically interviewing.
Core Java Interview Questions and Answers
Multithreading, Concurrency, and Thread Basics Questions
- Is it possible to make array volatile in Java?
Answer: Yes, it is possible to make an array volatile in Java, but only the reference which is pointing to an array, not the whole array. Therefore, if one thread changes the reference variable points to another array, which will provide a volatile guarantee.
However, if several threads are altering particular array elements, there won’t be any happens before assurance provided by the volatile modifier for such modification.
If the purpose is to provide memory visibility guarantee for individual indices of the array, volatile is of no practical use for you. Instead, you must rely on an alternative mechanism for thread-safety in that particular case, e.g. use of a synchronised keyword.
- From the two, which would be easier to write: synchronisation code for ten threads or two threads?
Answer: Both will have the same level of complexity regarding writing the code because synchronisation is independent of the number of threads, although the choice of synchronisation could be subject to the number of threads because this presents more conflict.
Therefore, you would opt for an advanced synchronisation technique, e.g. lock stripping, which requires more intricate code and proficiency.
- How would you call wait() method? Would you use if block or loop, and why?
Answer: wait() method should always be called in loop. It is likely that, until the thread gets CPU to start running again, the condition may not hold. Therefore, it is always advised to check the condition in loop before continuing.
- What is defined as false sharing in the context of multithreading?
Answer: False sharing is known to be one of the familiar performance issues on multi-core systems, whereby each process has a local cache.
False sharing can be hard to identify since the thread may be retrieving completely different global variables that occur to be fairly close together in memory.
Similar to many other concurrency issues, the main way to avoid false sharing is to carefully review your code and supporting your data structure with the size of a cache line.
- What is busy spin, and why should you use it?
Answer: Busy spin is known as one of the techniques to wait for events without freeing CPU. This is often done to avoid losing data in CPU cache, which could get lost if the thread is paused and resumed in some other core.
As a result, if you are working on a low latency system where your order processing thread isn’t in any particular order, rather than sleeping or calling wait(), you can just loop and then review the queue for new messages.
This is only valuable if you need to wait for a short amount of time, e.g. in microseconds or nanoseconds. LMAX Disruptor frameworks, a high-performance inter-thread messaging library has a BusySpinWait Strategy, which is centred on this model and uses a busy spin loop for EventProcessors waiting on the barrier.
LMAX Disruptor frameworks, a high-performance inter-thread messaging library has a BusySpinWait Strategy, which is centred on this model and uses a busy spin loop for EventProcessors waiting on the barrier.
- How do you take thread dump in Java?
Answer: By using kill -3 PID in Linux, where PID is the process id of Java process, you can take a thread dump of Java application. In Windows, you can press Ctrl + Break.
This will instruct JVM to print thread dump in standard out, and it may go to console or log file depending on your application configuration.
- Is Swing thread-safe?
Answer: No, Swing is not thread-safe. You aren’t able to update Swing components, e.g. JTable, JList or Jpanel from any thread. In fact, they must be updated from a GUI or AWT thread. This is why Swing’s provide
In fact, they must be updated from a GUI or AWT thread. This is why Swing’s provide invokeAndWait() and invokeLater() method to request GUI update from alternative threads.
These methods put update requests in AWT threads queue and wait for the update or return straight away for an asynchronous update.
- Describe what a thread-local variable is in Java
Answer: Thread-local variables are variables restricted to a thread. It is like thread’s own copy which is not shared between a multitude of threads. Java offers a ThreadLocal class to upkeep thread-local variables. This is one of the many ways to guarantee thread-safety.
However, it is important to be mindful while using a thread local variable in a controlled environment, e.g. with web servers where worker thread outlives any application variable.
Any thread local variable which is not taken away once its work is done can hypothetically cause a memory leak in Java application.
- What is the difference between sleep and wait in Java?
Answer: Both are used to pause thread that is currently running, however, sleep() is meant for short pause because it does not release lock, while wait() is meant for conditional wait.
This is why it releases lock, which can then be developed by a different thread to alter the condition of which it is waiting.
- What is defined as an immutable object? How would you create an immutable object in Java?
Answer: Immutable objects are defined as those whose state cannot be changed once it has been made, any alteration will result in a new object, e.g. String, Integer, and other wrapper class.
- What’s the difference between Callable and Runnable?
Answer: Both of these are interfaces used to carry out task to be executed by a thread. The main difference between the two interfaces is that Callable can return a value, while Runnable cannot. Another difference is that Callable can throw a checked exception, while Runnable cannot. Runnable has been around since Java 1.0, while Callable was introduced as part of Java 1.5.
- What do the Thread.class methods run() and start() do?
Answer: Thread.run() will execute in the calling thread, i.e. a new thread is not created, the code is executed synchronously. Thread.start() will execute the same code, but in a new asynchronous thread.
Basic Java Interview Questions and Data Types
- What is the right data type to represent a price in Java?
Answer: If memory is not a concern and performance is not critical, BigDecimal will be the right data type represent a price in Java. If not, double with predefined precision.
- How would you convert bytes to String?
Answer: To convert bytes to String, you would use Strong constructor which accepts byte.
However, you should be mindful of the right character encoding otherwise the platform’s default character encoding will be used, which may not necessarily be the same.
- Is it possible to cast an int value into a byte variable? What would happen if the value of int is larger than byte?
Answer: Yes, it is possible but int is 32 bit long in Java, while byte is 8 bit long in Java. Therefore when you can cast an int to byte higher, 24 bits are gone and a byte can only hold a value between -128 to 128.
- Which class contains method: Cloneable or Object?
Answer: java.lang.Cloneable is marker interface and does not contain at all any method. Clone method is well-defined in the object class.
Remember that clone() is a native method, therefore it is applied in C or C++ or any other native programming language.
- Is ++ operator thread-safe in Java?
Answer: ++ is not thread-safe in Java because it involves multiple commands such as reading a value, implicating it, and then storing it back into memory.
This can be overlapped between multiple threads.
- Is it possible to store a double value in a long variable without casting?
Answer: No, it is not possible to store a double value into a long variable without casting since the range of double is more, meaning you would need to type cast.
- Which one will take more memory: an int or Integer?
Answer: An integer object will take more memory as it stores metadata overhead about the object. An int is primitive, therefore it takes less space.
- Why is String immutable in Java?
Answer: String is immutable in Java since Java designer thought that String will be greatly used, making it immutable. It lets some optimisation easy sharing, and same String object between multiple clients.
A key step in that direction was the idea of putting away String literals in String pool. The aim was to moderate temporary String object by sharing them and in order to share, they must have to be from immutable class.
It is worth noting, that it isn’t possible to share a mutable project with two parties which are unfamiliar to each other.
- Is it possible to use String in the switch case?
Answer: Yes, this is possible from Java 7 onward. String can be used in switch case, but it is just syntactic sugar. Internal string hashcode is used for the switch.
- What is constructor chaining in Java?
Answer: Constructor chaining in Java is when you call one constructor from another. This generally occurs when you have multiple, overloaded constructor in the class.
- What are the default values of Java primitives?
Answer: byte – 0, int – 0, boolean – false, short – 0, long – 0L, float – 0.0f, double – 0.0d, char – ‘\u0000’
- How is the transient keyword used in Java?
Answer: The transient keyword is used to indicate that a field in class should not be serialized (used with the Serializable interface)
Looking for a new developer to lead your programming dream team?
Our free candidate search tool is full of top-class developer talent just waiting to be hired.
JVM Internals and Garbage Collection Interview Questions
- What is the size of int in 64-bit JVM?
Answer: The size of an int variable is constant in Java, it is always 32-bit regardless of platform. This means the size of primitive int is identical in both 32-bit and 64-bit Java Virtual Machine.
- What is the size of an int variable in 32-bit and 64-bit JVM?
Answer: The size of int is identical in both 32-bit and 64-bit JVM, and it is always 32-bits or 4 bytes.
- How does WeakHashMap work?
Answer: WeakHashMap operates like a normal HashMap but uses WeakReference for keys. Meaning if the key object does not devise any reference then both key/value mapping will become appropriate for garbage collection.
- How do you identify if JVM is 32-bit or 64-bit from Java Program?
Answer: This can be identified by checking some system properties such as sun.arch.data.model or os.arch.
- What is the maximum heap size of 32-bit and 64-bit JVM?
Answer: In theory, the maximum heap memory you can assign to a 32-bit JVM is 2^32, which is 4GB, but practically the bounds are much smaller.
It also depends on operating systems, e.g. from 1.5GB in Windows to almost 3GB in Solaris. 64-bit JVM allows you to stipulate larger heap size, hypothetically 2^64, which is quite large but practically you can specify heap space up to 100GBs.
- Explain the difference between JRE, JDK, JVM, and JIT.
Answer: JRE is an abbreviation of Java Runtime Environment that consist of sets of files needed by JVM throughout the runtime.
JVM is an abbreviation of Java Virtual Machine which delivers the runtime environment for collected Java Bytecode. JVM is in control of the conversion of the bytecode into machine-readable code.
JDK is an abbreviation for Java Development Kit which contains JRE including development tools for the purpose of development. JDK is required to write and execute a Java code.
JIT is an abbreviation of Just in Time compilation, and this helps to improve the performance of Java application by converting Java bytecode into native code when they cross a certain threshold, i.e. the mostly hot code is transformed into native code.
- Explain Java Heap Space and Garbage collection.
Answer: When a Java process has started using Java command, memory is distributed to it. Part of this memory is used to build heap space, which is used to assign memory to objects every time they are formed in the program.
Part of this memory is used to build heap space, which is used to assign memory to objects every time they are formed in the program.
Garbage collection is the procedure inside JVM which reclaims memory from dead objects for future distribution.
- Can you guarantee the garbage collection process?
Answer: No, the garbage collection cannot be guaranteed, though you can make a request using System.gc() or Runtime.gc() method.
- How do you locate memory usage from a Java program? How much of the percent is used?
Answer: You can use memory-related methods from java.lang.Runtime class to get the free memory, total memory and maximum heap memory in Java.
From using these methods, you can find out how much percent of the heap is used and how much heap space is outstanding.
Runtime.freeMemory() return the amount of free memory in bytes, Runtime.totalMemory() returns the total memory in bytes and Runtime.maxMemory() returns the maximum memory in bytes.
- What is the difference between Stack and Heap in Java?
Answer: Stack and Heap are different memory areas in the JVM, and they are used for different purposes.
The stack is usually much smaller than heap memory and also isn’t shared amongst multiple threads, but heap is shared among all threads in JVM.
Basic Java Concepts Interview Questions
- What is the difference between ‘a == b’ and ‘a.equals(b)’?
Answer: The ‘a = b’ does object reference matching if both a and b are an object and only return true if both are pointing to the same object in the heap space. However, a.equals(b) is used for logical mapping and it is likely from an object to supersede this method to provide logical equality.
For example, String class overrides this equals() method so that you can associate two Strings, which are not the same object but covers the same letters.
- What is a.hashCode() used for? How is it related to a.equals(b)?
Answer: hashCode() method returns an int hash value corresponding to an object. It is used in hash-based collection classes e.g. HashTable, HashMap, LinkedHashMap. It is very closely related to equals() method.
According to the Java specification, two objects which are identical to each other using equals() method needs to have the same hash code.
- What is the difference between final, finalize and finally?
Answer: Final is a modifier which you can apply to variable, methods, and classes. If you create a variable final, this means its value cannot be changed once initialised.
Finalise is a method, which is called just before an object is a garbage collected, allowing it a final chance to save itself, but the call to finalise is not definite.
Finally is a keyword which is used in exception handling, along with try and catch. The finally block is always implemented regardless of whether an exception is thrown from try block or not.
- What is a compile time constant in Java? What is the risk of using it?
Answer: Public static final variables are also known as the compile time constant, the public is optional there. They are substituted with actual values at compile time because compiler recognises their value up-front, and also recognise that it cannot be altered during runtime.
One of the issues is that if you choose to use a public static final variable from in-house or a third party library, and their value changed later, then your client will still be using the old value even after you deploy a new version of JARs.
This can be avoided by ensuring you compile your program when you upgrade dependency JAR files.
- What happens when a finally block has a return statement?
Answer: The returned value will override any value returned by the corresponding try block.
- Can you override a static method?
Answer: No, static methods are not overridable.
Java Collections Framework Interview Questions
- What is the difference between List, Set, Map and Queue in Java?
Answer: List, Set, and Map are three significant interfaces of Java collection framework.
Set provides an unordered collection of unique objects i.e. set does not allow duplicates, while Map provides a data structure based on key-value pair and hashing.
The difference between List and Set interface in Java is that List allows duplicates while Set does not allow duplicates. All implementation of Set honour this agreement. Map holds two objects per entry e.g. key and value, and it may contain duplicate values but keys are always unique.
One more difference between List and Set is that List is an ordered collection, List’s contract maintains insertion order or element. Set is an unordered collection, therefore you get no assurance on which order element will be stored.
Nevertheless, some of the set implementation (e.g. LinkedHashSet) retains order.
A queue is also ordered, but you will only ever touch elements at one end. All elements get inserted at the ‘end’ and removed from the ‘beginning’ (or head) of the queue.
You are able to find out how many elements are in the queue, but you are not able to find out what, for example, the ‘third’ element is.
- What is the difference between poll() and remove() method?
Answer: Both poll() and remove() take out the object from the Queue but if poll() fails, then it returns null. However, if remove() fails, it throws exception.
- What is the difference between LinkedHashMap and PriorityQueue in Java?
Answer: PriorityQueue guarantees that the lowest or highest priority element always remains at the head of the queue. However, LinkedHashMap maintains the order on which elements are inserted.
When you repeat over a PriorityQueue, iterator does not promise any order but iterator of LinkedHashMap does promise the order on which elements are put in.
- What is the difference between ArrayList and LinkedList in Java?
Answer: The main difference between them is that ArrayList is supported by array data structure, supports random access. LinkedList is backed by linked list data structure and doesn’t support random access.
- How do you print Array in Java?
Answer: You can print an array by using the Arrays.toString() and Arrays.deepToString() method. Since Array does not implement to String() by itself, just passing an array to System.out.printIn() will not print its content but Array.to.String will print each element.
- Is LinkedList in Java a doubly or singly linked list?
Answer: LinkedList is a doubly linked list, and you can review the code in JDK. In Eclipse, you are able to use the shortcut, Ctrl + T to directly open this class in editor.
- What is the difference between Hashtable and HashMap?
Answer: There are several differences between the two classes, including:
- Hashtable is a legacy class and current from JDK 1, HashMap was introduced and added later.
- Hashtable is synchronised and slower whereas HashMap is not synchronised and faster.
- Hashtable does not allow null keys but HashMap allows one null key.
- How does HashSet work internally in Java?
Answer: HashSet is internally implemented using a HashMap. Since a Map needs a key and value, a default value is used for all keys. Like HashMap, HashSet does not allow identical keys and only one null key – you are only able to store one null object in HashSet.
- Is it possible for two unequal objects to have the same hashcode?
Answer: Yes, two unequal objects can have the same hashcode. This is why collision can occur in hashmap. The equal hashcode contract only says that two equal objects must have the identical hashcode, but there is no indication to say anything about the unequal object.
- What is the difference between Comparator and Comparable in Java?
Answer: The comparable interface is used to define the natural order of object while Comparator is used to describe custom order. Comparable can always be one, but it is possible to have multiple comparators to define a custom order for objects.
Java IO and NIO Interview Questions
From a Java interview point of view, IO is very important. Ideally, you should have a good knowledge of old Java IO, NIO, and NIO2. Additionally, it is worth having knowledge of some operating systems and disk IO fundamentals. The following are some frequently asked questions regarding Java IO:
- What is the byte order of ByteBuffer?
Answer: The byte order is used when reading or writing multibyte values, and when creating buffers that are views of this byte buffer. The order of a new byte buffer is always BIG_ENDIAN.
- What is the difference between direct buffer and non-direct buffer in Java?
Answer: Byte buffer is one of the important class of Java NIO API. This was initially introduced in java.nio package on JDK 1.4. It lets you function on heap byte arrays as well as with direct memory, which occurs outside the JVM.
It lets you function on heap byte arrays as well as with direct memory, which occurs outside the JVM.
The main difference between direct and non-direct byte buffers are their memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory.
Meanwhile, direct byte buffer is outside of JVM and memory is not assigned from the heap.
A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java Virtual Machine will make a best effort to complete native I/O operations directly upon it.
It will try to evade copying the buffer’s content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system’s native I/O operations.
- What is the memory mapped buffer in Java?
Answer: Java IO has been considerably fast after the introduction of NIO and memory mapped file offers fastest IO operation possible in Java.
A key advantage of memory mapped file is that operating system is responsible for reading and writing and even if your program malfunctioned just after writing into memory. OS will take care of writing content to file.
- What is the difference between TCP and UDP protocol?
Answer: TCP and UDP are two transport layer protocols, which are widely used on the internet for transferring data from one host to another.
TCP is a connection-oriented protocol, whereas UDP is a connectionless protocol. Therefore, a connection is recognised between client and server before they can send data.
With UDP being a connectionless protocol, the point-to-point connection is not recognised before sending messages. For that reason, UDP is more fit for multicast distribution of the message.
There are many differences between TCP and UDP, but during the Java interview it is worth mentioning that TCP is connection oriented, dependable, sluggish, offers definite delivery and preserves the order of messages, while UDP is connectionless, unpredictable, no ordering assurance, but a fast protocol.
TCP is also much higher than UDP, as it transfers more metadata per packer than UDP.
Additionally, the header size of TCP is 20 bytes, compared to 8 bytes header of UDP. If you are in a position where you can’t afford to lose any messages, use TCP. If you need high-speed data transmission, where loss of a single packet is acceptable, use UDP.
If you need high-speed data transmission, where loss of a single packet is acceptable, use UDP.
Are you a Java developer looking for your next challenge?
browse the jobs FRG Technology Consulting has to offer or get in touch so we can match you with your dream role.
Java Best Practices Interview Questions
- What best practices should you follow while writing multithreaded code in Java?
Answer: When writing concurrent code in Java, the following are some best practices to be mindful of:
- Always name your thread as this help in debugging.
- Minimise the scope of your of synchronisation. Rather than making the whole method synchronised, be mindful that only the critical section should be synchronised.
- Opt for volatile over synchronisation if you have the option to.
- Use a higher level of concurrency utilities instead of waiting() and notify for inter-thread communication, e.g. BlockingQueue, CountDownLatch and Semaphore.
- Opt for concurrent collection over synchronised collection in Java as this will provide better scalability.
- Explain some best practices you would apply while using Collection in Java.
Answer: When using Collection classes in Java, the following are some best practices to be mindful of:
- Ensure you are using the right collection, e.g. if you need a non-synchronised list, then opt for ArrayList and not Vector.
- Opt for concurrent collection over a synchronised collection because they are more scalable.
- Ensure you are using interface to represent and access a collection e.g. use List to store ArrayList, Map to store HashMap.
- Use iterator to loop over collection.
- Always use generics with collection.
- Explain five best practices you would apply while using threads in Java.
Answer: Although similar to the previous question, be particularly mindful with thread, as you should:
- Always name your thread.
- Prioritise your task and threads by keeping them separate. Use runnable and Callable with thread pool executor.
- Use thread pool.
- Use volatile to indicate compiler about ordering, visibility, and atomicity.
- Avoid thread local variable because improper use of ThreadLocal class in Java can produce a memory leak.
- Explain 5 IO best practices.
Answer: IO is important for overall performance for your Java application, and ideally you should avoid IO in a critical path of your application. The following are Java IO best practices you should be mindful of:
- Use buffered IO classes instead of reading individual bytes and char.
- Use classes from NIO and NIO2.
- Always close streams in final block or use try-with-resource statements.
- Use memory mapped file for faster IO.
- Explain a few method overloading best practices in Java.
Answer: The following are examples of overloading a method in Java to avoid confusion with auto-boxing:
- Don’t overload method where one accepts ints and the other accepts Integer.
- Don’t overload method where a number of arguments are the same and only the order of argument is different.
Use varargs after the overload methods have had more than five arguments.
Date, Time, and Calendar Interview Questions in Java
- Is SimpleDateFormat safe to use in the multithreaded program?
Answer: No, DataFormat and all its implementation including SimpleDateFormat is not thread-safe, hence should not be used in the multithreaded program until external thread-safety measures are applied e.g. confining SimpleDateFormat object into ThreadLocal variable.
If you do not do that, you will get wrong results while analysing or configuring dates in Java.
- How would you format a data in Java? i.e. in the DDMMYYY format.
Answer: This can be done by using either SimpleDateFormat class or java-time library to format a date in Java. DateFormat class lets you format the date on many common formats.
- How do you show the time zone in a formatted date In Kava?
Answer: You are able to put time zone information in formatted Date using z attribute of DateFormat class.
- What is the difference between java.util.Date and java.sql.Date in Java?
Answer: Both are known as Date class, but there is some difference between java.util.Date and java.sql.Date, for example, Former is used whenever a Date is required in Java application while later is used to read and store DATE SQL type from the database.
Another significant difference is java.util.Date stores both date and time values, while java.sql.date only stores date information, without any time apart. According to the Javadoc specification, java.sql.date is a thin wrapper around a millisecond value that lets JDBC distinguish as an SQL DATE value.
To fit in with the meaning of SQL DATE, the millisecond values bound by a java.sql.Date instance must be ‘normalised’. However, setting the hours, minutes, seconds, and milliseconds to zero in the specific time zone with which the case is connected.
Unit Testing JUnit Interview Questions
- How do you test static method?
Answer: PowerMock library can be used to test static methods in Java.
- How do you test a method for an exception using JUnit?
Answer: One part of unit testing a Java method is checking exception thrown by that method. In a Java unit test, it should really prove correct exception thrown in exceptional case and no exception would be thrown in normal case.
In order to test any Java method for throwing exception in Junit4, you need to make sure that argument provided to that method, from the test must result in expected exception, otherwise JUnit test will fail.
A testing method called speed(), returns speed as distance/time, but before calculating speed it checks whether time and distance are positive or negative and if time is zero or negative it throws IllegalArgumentException.
- What is the difference between @Before and @BeforeClass annotation?
Answer: The code marker @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your text class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.
In general, you would use @BeforeClass when numerous tests are required to share the same computationally expensive setup code. Starting a database connection falls into this category. You are able to move code from @BeforeClass into @Before, but your test run may be delayed.
@BeforeClass is run as static initialiser, therefore it will run before the class instance of your test fixture is created.
- What’s the difference between unit, integration and functional testing?
Answer: A unit tests tests a small isolated piece of code such as a method. It doesn’t interact with any other systems such as a database or another application.
An integration test tests how your code plays with other systems, such as a database, a cache or a third-party application.
A functional test is the testing of the complete functionality of an application. This may involve the use of an automated tool to carry out more complex user interactions with your system. It tests certain flows/use cases of your application.
- What is the difference between state-based unit testing and interaction-based unit testing?
Answer: State-based unit testing tests that the resulting state of a piece of code under test is as expected. Interaction-based testing tests that the piece of code under tests followed a certain flow or invoked certain methods as expected.
Programming and Coding Questions
- How do you check if a String contains only numeric digits?
Answer: java.lang.String class offers a couple of methods with an inherent support of systematic expression e.g.split method, replaceAll() and matches method. Although this can be used for this purpose, it can have a disadvantage.
They produce a new consistent expression pattern object, each time you call. Since most of the time the pattern can be reused, there is no need to spend time on producing and assembling pattern, which is costly in comparison to testing a String against the pattern.
In terms of reusable patterns, you can receive assistance of java.util.regex package, it offers two class Pattern and Matcher to create pattern and review String alongside that pattern.
To complete this, you need to create a regular expression pattern object. This can be done by passing regular expression String “(.)*(\\d)(.)*” to Pattern.compile() method.
This will then output a compiled version of regular expression String. From using this pattern you can acquire Matcher object to identify if input string passes this systematic expression pattern or not.
- How do you write a Java program to convert bytes to long?
Answer: The byte takes 1 byte of memory and long takes 8 bytes of memory. Assignment 1 byte value to 8 bytes is done indirectly by the JVM.
Byte -> short -> int -> long -> float -> double
The left-side value can be assigned to any right-side value and is done indirectly. The reverse requires explicit casting.
- How do you reverse a String in Java without using StringBuffer?
Answer: To reverse a String in Java, you are able to use rich Java API to quickly reverse contents of any String object. The Java library provides String Buffer and StringBuilder class with reverse() method, which can be used to reverse String in Java.
Since changing between String and StringBuffer is very easy, this is the easiest way presented to reverse String in Java. Reverse is a recursive job, and for that reason you can use recursion as well as loop to reverse String in Java.
- How do you check if two given String are anagrams?
Answer: Anagrams are a mix-up of characters in String e.g. army and mary, stop and pots etc. To identify if Strings are anagram, you will need to get their character array and identify if they are equal or not.
You are able to use indexOf(), substring() and StringBuffer or StringBuilder class to solve this question.
- How do you convert String to int in Java?
Answer: Java provides Integer.parseInt() method to parse a String to an int value. However, there is another way to do this, which takes advantage of the parsing logic of parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful.
Java Interview Questions from OOP and Design Patterns
- What is the difference between abstract class and interface in Java?
Answer: There are various differences between abstract class and interface in Java, however, the most significant would be Java’s restriction on permitting a class to extend just one class but lets it implement multiple interfaces.
An abstract class is good to define default behaviour for a family of class, but the interface is good to outline which is then used to leverage Polymorphism.
- Explain Liskov Substitution Principle.
Answer: According to the Liskov Substitution Principle, Subtypes must be appropriate for super type i.e. methods or functions which use super class type must be able to work with object of subclass with no issues.
LSP is closely related to Single Responsibility Principle and Interface Segregation Principle. If a class has more functionality, then subclass might not upkeep some of the functionality and does violate LSP.
To follow the LSP SOLID Design Principle, derived class or subclass must improve functionality, but not lessen them. LSP represent ‘L’ on SOLID acronym.
- What is Law of Demeter violation and why does it matter?
Answer: Java is centred on application programming and structuring code. If you have good knowledge of common coding best practices, patterns, and what not do, then you can write good code.
Law of Demeter suggests you ‘talk to friends and not stranger’, therefore used to reduce coupling between classes.
- What is Adapter pattern and when would you use it?
Answer: Adapter pattern provides interface conversion. For example, if your client is using some interface but you have something else, you can write an adapter to bridge them together.
- What is an abstract class? How is it different from an interface, and why would you use it?
Answer: An abstract class is a class which can have state, code, and implementation, but an interface is a contract which is totally abstract.
The abstract class and inheritance equally take precautions that most of the code is written with abstract and high-level classes, therefore it can influence Inheritance and Polymorphism.
- Which is better: constructor injection or setter dependency injection?
Answer: Both have their advantages and disadvantages. Constructor injection guaranteed that class will be initialised with all its dependency. However, setter dependency injection offers flexibility to set an optional dependency.
Setter dependency injection is also more understandable if you are using XML file to define dependency. A general rule of thumb is to use constructor injection for compulsory dependency and use setter injection for non-compulsory dependency.
- What is the difference between Adapter and Decorator pattern?
Answer: Though they are both similar, the difference is the intent of each pattern. The adapter pattern is used to bridge the gap in the middle of two interfaces, but Decorator pattern is used to add an extra level of indirection to support distributed, controlled or intelligent access.
- What is Template method pattern?
Answer: Template pattern provides an outline of an algorithm and lets you configure or customise its steps. For example, you are able to view a sorting algorithm as a template to sort object.
It describes steps for sorting but lets you arrange how to associate them using Comparable or something comparable in another language. This pattern uses double dispatch to supplement another level of indirection.
- What is the difference between Inheritance and Composition?
Answer: Both allow code reuse, however, Composition is more flexible than Inheritance because it lets you switch to a different implementation at run-time. Code written using Composition is also better and easier to test than code including inheritance hierarchies.
- Explain overloading and overriding in Java.
Answer: They both let you write two methods of different functionality but with the same name, but overloading accumulates time activity while overriding is runtime activity. You can overload a method in the same class, however, you can only override a method in child classes.
It is worth noting that Inheritance is necessary for overriding.
Looking for your next Java role?
Sign up to our jobs by email and be one of the first to apply for great jobs as they become available.
Miscellaneous Java Interview Questions
- What is the difference between nester static class and top-level class?
Answer: A public top-level class must have the same name as the name of the source file – there is no obligation for nested static class.
A nester static class is at all times inside a top-level class and you need to use the name of the top-level class to refer nested static class. For example, HashMap.Entry is a nester static class, whereby HashMap is a top-level class and Entry is a nested static class.
- Is it possible to write a regular expression to check if String is a number?
Answer: A numeric String is only able to contain digits i.e. 0-9 and +/- sign. By using this information, you can write following regular expression to check if given String is number or not.
- What is the difference between throw and throws in Java?
Answer: The throw is used to actually throw an instance of java.lang.throwable class, meaning you can throw both Error and Exception using throw keyword.
However, throws is used as part of method declaration and indicate which kind of exceptions are thrown by this method, so that its caller can handle them.
It is compulsory to assert any unhandled checked exception in throws clause in Java.
- What is the difference between Serializable and Externalizable in Java?
Answer: Serializable interface is used to make Java classes serializable so that they can be transmitted over the network or their state can be kept on disk. However, it influences default serialization built-in JVM, which is pricey, fragile, and unsecured.
Externalizable lets you fully control the Serialization process, identify a customer binary format and enhance security measure.
- What is the difference between DOM and SAX parser in Java?
Answer: DOM parser loads the whole XML into memory to create a tree-based DOM model. This helps it quickly locate nodes and make a change in the structure of XML. SAX parser is an event based parser and does not load the whole XML into memory.
For this reason, DOM is quicker than SAX but it needs more memory and is not fitting to parse large XML files.
- Explain 5 features introduced in JDK 1.7.
- try-with-resource statements free you from closing streams, and resources when you are finished with them, Java automatically closes this.
- Fork-join pool to implement something like the Map-reduce pattern in Java, which allows String variable, and literal into switch statements.
- Diamond operator for improving type inference, so there is no need to assert generic type on the right-hand side of variable declaration any longer, meaning the results are more clear and the code is more concise.
- Improved exception handling, which lets you catch multiple exceptions in the same catch block.
- Explain 5 features introduced in JDK 1.8.
- Lambda Expression: This allows you to pass an anonymous function as object.
- Stream API: Allows you to take advantage of multiple cores of modern CPU and lets you write concise code.
- Date and Time API: There is a solid and easy to use date and time library in JDK.
- Extension Methods: You can include static and default method into your interface.
- Repeated Annotation: This lets you apply the same annotation multiple times on a type.
- What is the difference between Maven and ANT in Java?
Answer: Both are a build tool and used to create a Java application build but Maven is more advanced. It provides a standard structure for Java projects based on the ‘convention over configuration’ concept and routinely manages dependencies (JAR files on which your application is dependent) for Java application.
- What is the difference between checked and unchecked exceptions?
Answer: Checked exception are checked at compile time. If your code throws a checked exception, it must handle it or specify it using the ‘throws’ keyword.
Unchecked exceptions extend the RuntimeException or Error class and do not need to be handled in the code if they are thrown or specified using ‘throws’. You can always write code to specifically handle an unchecked exception.
- What is the difference between Object Oriented Programming and Object Based Programming?
Answer: Object oriented programming supports all the usual OOP features such as inheritance and polymorphism. It also has no built in objects. Object based programming does not support inheritance or polymorphism and does have some built in objects.
Preparing for a Java Interview
Java interviews can vary depending on the candidate’s experience. For example, junior Java developers with one-to-four years of experience may experience questions on topics like fundamentals, API, data structure, and algorithms.
Senior Java developers with more than five or six years of experience will be asked more questions about concurrent programming, Java concurrency API, JVM internals, GC tuning and Java performance.
Therefore, when preparing for a Java interview, it should be aligned with your experience. It is essential to also bear in mind the type of interview you are preparing for. Java EE interviews are based on framework experience and knowledge of the likes of JSF, Spring, and Hibernate while Java interviews are mostly focused on core concepts like concurrency, collections, and JVM internals.
Examples of Java Interview Tasks and Questions
Speaking to developers in the community, these are some of their favourite interview questions from personal experience and how they dealt with them:
Alan Mellor, a Java developer since 2001, and currently a Consultant Software Engineer at BJSS, said his favourite interview was being asked to do a 30-45 minute observed pair-programming session with a senior developer.
The task was simply to read some data, pick some data out, and to write it to console.
Alan continues to highlight how this was a great opportunity to show off how he thinks about stuff, how he writes his tests, how he splits his code, how he names his variables, how he applies dry and solid principles, and what sort of interactions he has with a programming pair.
In his experience, Alan believes this was much better than being asked some ‘weird quirk’ of the Java language specification.
Jevin Menezes, an Open Source software enthusiast who learned Java fundamentals during his studies of engineering, comments on the types of interview questions he recommends for newcomers in Java.
The two questions he experienced tested his knowledge of core concepts.
- Is String a datatype in Java?
The interviewer wanted an explanation which stated that String is not a primitive data type in Java; it is one of the most extensively used objects in Java, which is an instance of String class.
- String class is defined under which package in Java?
The answer to this Java question is java.lang package, and this will test the very basics of core Java knowledge.
David Owens, who is a freelancing Java developer also provides interview questions about the core fundamentals of Java knowledge.
The following questions are what he believes is fair to expect during an interview:
- What occurs when an object is constructed?
Answer: Several things happen in a specific order to guarantee the object is constructed properly:
- Memory is distributed from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data consist of point to class and method data.
- The instance variables of the objects are initialised to their default values.
- The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor is for java.lang.Object is called, as java.lang.Object is the base class for all objects in Java.
- Before the body of the constructor is executed, all instance variable initialisers and initialisation blocks are executed. Then the body of the constructor is executed. This, the constructor for the base class completes first and constructor for the most derived class completes last.
A question like this will indicate a good understanding of processes with the core Java language.
- Explain the difference between the public, private, final, protected, and default modifiers.
Answer: These keywords – public, private, final, protected, and default modifiers – are to specify access levels for member variables, or for member functions (methods).
- Public variables: these are variables that are noticeable to every class.
- Private variables: these are variables that are noticeable only to the class to which they fit in.
- Protected variables: these are variables that are noticeable only to the class to which they fit in, as well as any other relevant subclasses.
The decision to use private, protected, or public variables can be difficult. It is a question of whether or not an external object (or program), actually needs direct access to the information.
If you prefer to have other objects to access internal data, but want to control it at the same time, you would make it either private or protected. However, be mindful of delivering functions which can affect the data in an organised way.
Although David mentions it isn’t fair to place too much emphasis on the protected and default modifiers and exactly what they mean. Though extra credit could be assumed for why and which circumstances you would use these.
- Explain why Java does not have multiple inheritance.
Answer: Multiple inheritance is a feature of some object-oriented computer programming languages. This is where an object or class can come into characteristics and features from one or more parent object or parent class.
Java does not support multiple inheritance because it can cause ambiguity in various scenarios, mainly because of the ‘diamond problem’. Java is designed to be a simple programming language.
The problem is that is a class extended two other classes, and both superclasses had, for example, a doStuff() method, which version of doStuff() would the subclass inherit? This type of scenario is typically known as ‘Diamond Problem’ also known as ‘Deadly Diamond of Death’, and because of the shape of the class diagram that can be created in a multiple inheritance design.
The diamond is formed when classes B and C both extend A, and both C and C have overridden the method in A. Class D has, in principle, inherited two different implementations of the identical method.
When drawn as a class diagram, the shape of the four classes looks the same as a diamond.
After the introduction of Default Methods in Java 8, the interfaces can also have the method bodies. In Java 8 interface, it can have method definition using Default Methods, then clearly it should also result in ambiguity? Yes, but Java 8 can handle this type of compatible problem.
In Java 8, you cannot implement multiple interfaces having the same signature, without explicitly overriding the methods in the Child class. It is possible to call the Parent interface method explicitly from the Child class.
Explaining the inheritance exception for Java 8 may not be necessary but David believes this may show extra credibility knowing this extra bit of information.
David also discusses his love for snippets of code being projected onto a wall or are shown to you in a reasonably easy-to-read form, and you are asked to describe what they mean, what they print, and what value of a variable would be.
However, the types of questions he isn’t too fond of are coding exercises in which you need to type. Especially, if it is in an editor platform or IDE that is unfamiliar, as he believes this is not a test of knowledge.
David’s advice for candidates going through the Java interview process is to understand that when they are asking questions and evaluating you on your answers, it is entirely appropriate to evaluate them on the content of those questions and how they react to your answers. His indication of a good company is: ‘if this company was public, would I buy stock in them?’
And that is our round-up of the popular Java interview questions you may come across. These questions have been outlined on how to best answer during an interview, however, it is advised to do as much research as possible to ensure you answer the question as best as you can.
Have you experienced any interesting Java interview questions? Let us know In the comments and explain how you answered the question.
Time to get that dream Java job.
Let our recruitment experts make it happen.