Grokking The Java Interview 02
Grokking The Java Interview 02
In this book, we have included topics such as class loader, Enum, String,
HashMap, ConcurrentHashMap, Date and Time, Web Services, NIO, Socket
Programming, Inheritance, Abstract class, and Interface. These topics are
essential for any Java developer to master to ace their interviews.
We understand that Java interviews can be challenging, and preparing for them
can be overwhelming. Our aim with this book is to help you grok the topics in-
depth and ace your interviews with confidence.
We hope that this book will be a valuable resource in your Java interview
preparation journey. Let's get started and grok the Java interview together!
— iii —
Contents
PREFACE .............................................................................................................................. iii
CONCLUSION................................................................................................................ 154
CHAPTER 1:
Java String
Interview Questions
H ello Java Programmers, if you are preparing for a Java developer interview
and want to refresh your knowledge about the String class in Java, you have
come to the right place. In this chapter, I will share 35 Java String Questions for
Interviews. The String class and concept are essential in Java. There is not a single
Java program out there that does not use String objects, and that's why it's also
crucial from the interview point of view. In this chapter, I will share 35 String-based
questions from different Java interviews.
You can use this list to refresh your knowledge about String in Java and prepare
for your following Java interview.
—1—
GROKKING THE JAVA INTERVIEW
Question 1
Why is String final in Java?
There are a couple of reasons for this, e.g., String pool, Caching, and Performance,
but Security is probably the most important reason. Given String is used in
sensitive places like specifying the host and port details, locking it for modification
prevents many Security related risks. It's one of the popular Java interview
questions.
Question 2
How does the substring method work in Java?
This returns a substring of a specified range from the original String on which
it is called. It returns a new String object because String is immutable and can't
be changed. However, prior to Java 7, it also held the reference of the original
array, which can prevent it from collecting garbage and causing a memory leak,
which is not ratified.
Question 3
What is the String pool in Java? What is the difference in the String pool
between Java 6 and 7?
It's a pool of cached String objects to minimize the number of String instances
and improve performance by sharing the same instance with multiple clients
and reducing garbage collection. Prior to Java 7, the String pool was located on
meta-space where class metadata was stored, but from JDK 7 onwards, it's
moved into heap space.
Question 4
What is the difference between "ABC".equals(str) and str?equals("ABC"),
where an str is a String object?
Though both look similar and return the same result if str is equal to "ABC,"
the real difference comes when the given String is null, i.e., str = null. In
—2—
JAVA STRING INTERVIEW QUESTIONS
that case, the first code snippet will return false, while the second code snippet
will throw NullPointerException.
This is one of the tricky Java questions, and if a candidate can answer this, then
he has good knowledge of Java fundamentals. It's also one of the several weird
tricks to avoid NullPointerException.
Question 5
Difference between str1 == str2 and str1.equals(str2)?
The critical difference is that the first one uses the == operator, which makes a
reference-based comparison, while the second one uses the equals() method,
which makes a content-based comparison. Since the String class overrides
equals() to perform character-based comparison
The first will return true only if both str1 and str2 point to the same object, but
the second one will return true if str1 and str2 have the same content, even if
they are different objects.
Question 6
When you execute String str = new String("abcd")? how many String objects
are created?
This is another tricky Java interview question, as many Java developers will
answer just one, but that's not true. There are two String objects created here.
The first String object is created by String literal "abcd," and the second one is
created by new String(). If you are not sure about how
Question 7
What does the intern() method of the String class do?
The intern() method of the String class puts the String on which it has called
into the String pool like str.intern() will put the String str into the pool.
Once the String is in the pool, it can be reused and improve performance.
—3—
GROKKING THE JAVA INTERVIEW
Question 8
How do you split comma-separated String in Java?
You can use either the StringTokenizer or the split() method of
java.lang.String class to split a comma-separated String. The split()
method is better because it also expects a regular expression and returns an
array of String which you can use or pass to a function.
Question 9
What is the difference between String and StringBuffer in Java?
The key difference between String and StringBuffer is that String is Immutable while
StringBuffer is mutable, which means you can change the content of a StringBuffer
without creating separate String objects. If you are creating string programmatically,
consider using StringBuffer for better performance as it puts less pressure on
Garbage Collector by reducing the number of temporary objects.
Question 10
What is the difference between StringBuffer and StringBuilder in Java?
Now, this is interesting because both StringBuffer and StringBuilder represent
mutable String. This is also asked a follow-up question to the previous question.
Anyway, the real difference is that methods of StringBuffer like append() are
synchronized, hence slow, while those of StringBuilder is not synchronized,
hence fast.
Otherwise, StringBuilder is just a copy of StringBuffer, and you can see that in
the Javadoc of the StringBuilder class as well.
Question 11
Write a program to reverse a String in Java without using StringBuffer.
This is a common coding problem from Java interviews. You can use recursion
or iteration to solve this problem.
—4—
JAVA STRING INTERVIEW QUESTIONS
In this program, we have first defined a reverse() method that takes a String as
input and returns the reversed String. We then convert the input String to a
character array using the toCharArray() method.
We then use two pointers, left and right, to traverse the character array from
both ends. We swap the characters at left and right positions until we reach the
middle of the array.
Finally, we return the reversed String by creating a new String object from the
character array using the String(char[] chars) constructor.
—5—
GROKKING THE JAVA INTERVIEW
Question 12
Write a program to replace a character from a given one in Java.
This is another coding problem based on String, but it doesn't specify whether
you can use String API. If not, then you can use the replace method of String
to solve this problem.
import java.util.Scanner;
In this program, we first take the input String from the user using a Scanner
object. Then we take the character to be replaced and the new character as
input. The replaceChar() method takes the input String, old character, and
—6—
JAVA STRING INTERVIEW QUESTIONS
new character as input and return a String where the old character is replaced
with a new character.
Question 13
Can you write a Java program to count the occurrence of a given character
in String?
This problem requires using HashMap for string characters as keys and their
count as values. Once you know this trick, you can easily solve such string
coding problems. Just convert String to character array and then loop through
the array. For each character, store the character as a key and the value as 1 in
HashMap. If the key or character already exists, then increase the count by 1.
When you run this program you will see following output:
—7—
GROKKING THE JAVA INTERVIEW
Question 14
Why is a char array better than a String for storing sensitive information?
This is one of the trick questions from Java interviews. The reason is that
because String is immutable, they are cached in memory, and there is a good
chance that they will remain in memory for a longer duration posing a possible
threat, while character array gives you the option to erase data once they are
used. This is the primary reason, but there are some more subtle reasons.
Question 15
How to check if a String contains only numeric digits?
This is one of the simple problem to solve. You can either use a regular
expression to check if a string contains only numbers, or you can convert it to
a character array and then check the ASCII value of those characters to see if
they are in the range of numbers. For example, You can use the matches()
method in Java with a regular expression to check if a String contains only
numeric digits as shown below:
This method takes a String as input and returns a boolean indicating whether
the String contains only numeric digits or not. The regular expression \\d+
matches one or more digits. The matches() method returns true if the String
matches the regular expression and false otherwise.
—8—
JAVA STRING INTERVIEW QUESTIONS
Question 16
Can you write a program to check if a String is a palindrome in Java?
If you don't know, a string is said to be a palindrome if it's equal to its reverse.
In order to check if a given String is a palindrome or not, you need to first
reverse it and then compare the reversed string with the original string. If they
are equal, the given String is a palindrome. If you remember, we have seen
questions about reversing a string, you can either use that technique to reverse
a string, or you can use convert the String to StringBuffer and use its
reverse() method to reverse the given string.
import java.util.Scanner;
—9—
GROKKING THE JAVA INTERVIEW
In the above program, we first take input string from the user using Scanner.
Then, we check if the string is palindrome or not using isPalindrome()
method. This method takes a string as input and returns a boolean value true
if the string is a palindrome; otherwise false. To check if the string is
palindrome, we compare the characters from start and end of the string and
return false as soon as we find a mismatch. If we reach the middle of the string
without finding any mismatch, we return true.
Question 17
How to format String in Java?
You can use the format() method of the java.lang.String class to
format a given String in Java. If you just want to print the formatted String, you
can also use the System.out.printf() method, which prints the
formatted string to the console.
Question 18
How to convert Enum to String in Java?
Similar to any Java object, you can also use the toString() method to
convert an Enum to a String in Java. The Enum class provides a toString()
method which can be overridden by your Enum implementations.
Question 19
How to convert String to Date in Java?
Prior to Java 8, you could use DateFormat or SimpleDateFormat class to convert a
String to Date In Java or vice-versa. From Java 8 onwards, when you use the new
Date and Time API, you can also use the DateTimeFormatter class to convert
String to LocalDate, LocalTime, or LocalDateTime class in Java.
— 10 —
JAVA STRING INTERVIEW QUESTIONS
Question 20
Is String thread-safe in Java? Why?
Yes, String is thread-safe because it's Immutable. All Immutable objects are
thread-safe because once they are created, they can't be modified. Hence is no
issue with respect to multiple threads accessing them.
Question 21
Can we use String as the HashMap key in Java?
Yes, we can use String as a key in HashMap because it implements the
equals() and hashcode() method, which is required for an object to be
used as a key in HashMap.
Question 22
How to check if a String is empty in Java?
There are many ways to check if a String is empty in Java, e.g., you can check
its length. If the length of the String is zero, then it's empty. Otherwise, you can
also use the isEmpty() method, which returns true if the String is empty.
Though you need to be careful with requirements, e.g., a String may contain a
whitespace that will look empty, but the length will not be zero. So, it depends
upon your requirements.
Question 23
How to convert String to int in Java?
There are many ways to convert the String to the int primitive in Java, but the
best way is by using Integer.parseInt() method. This method parses
the given string and returns a primitive int value. If you need a wrapper class
Integer object, you can use Integer.valueOf() method. Although it
internally uses the parseInt() method, it caches frequently used Integer
values, e.g., -128 to 127, which can reduce temporary objects.
— 11 —
GROKKING THE JAVA INTERVIEW
Question 24
How does String concatenation using the + operator work in Java?
The + operator can be used to concatenate two Strings in Java. This is the only
operator that is overloaded, i.e., it can be used two add numbers as well as to
concatenate String. Internally, the concatenation is done by using
StringBuffer, or StringBuilder append() method, depending upon
which version of Java you are using.
Question 25
Can we use String in switch case in Java?
Yes, after the JDK 7 release, you can use the String in the switch case in Java.
Earlier, it wasn't possible, but now it's possible.
Question 26
What is the String enum pattern in Java?
This is a common pattern to declare String constants inside an enum. For
example, days of the Week can be declared as Enum so that you can use them
as Enum instead of String.
Question 27
Write a Java program to print all permutations of a String.
This is also one of the most popular string coding problems, which can be easily
solved using recursion, provided you know the permutations.
import java.util.*;
— 12 —
JAVA STRING INTERVIEW QUESTIONS
This program uses recursion to generate all possible permutations of the input
String. It first checks if the String is null or empty, and if so, returns an empty
list. Otherwise, it calls a helper function that takes in the String as a character
array, an index representing the current position in the array, and a list to store
the permutations.
— 13 —
GROKKING THE JAVA INTERVIEW
If the index is at the end of the array, the function adds the current permutation
to the list. Otherwise, it swaps the current character with every character to its
right and recursively generates permutations for the remaining characters.
After each recursive call, it swaps the characters back to their original positions
to backtrack and generate the next permutation.
Question 28
What is the difference between String in C and Java?
Even though both C and Java String is backed by character array, C String is a
NULL-terminated character array while Java String is an object. This means
you can call methods on Java String, e.g., length, toUpperCase,
toLowerCase, substring, etc.
Question 29
How to convert String to double in Java?
Question 30
How to convert String to long in Java?
It's similar to converting String to int or String to double in Java. All you need
to do is just use the parseLong() method of the Long class. This method
returns a primitive long value. Even though you can use the
Long.valueOf() method, which can be used to convert String to Long but
it returns a Long object. Hence you would need to use auto-boxing to convert
the wrapper object to a primitive value.
— 14 —
JAVA STRING INTERVIEW QUESTIONS
Question 31
What is the difference between the format() and printf() methods in Java?
Even though both methods can be used to format Strings and they have the
same rules, the key difference is that format() method returns a formatted
String while the printf() method prints a formatted String to the console.
So, if you need a formatted String, use the format method, and if you want to
print, then use the printf() method.
Question 32
How do you append a leading zero to a numeric String?
You can use the format() method of String to append leading zeros to a
numeric String in Java.
Question 33
How to remove white space from String in Java?
You can use the trim() method to remove white space from String in Java.
It's similar to SQL Servers LTRIM() and RTRIM() methods.
Question 34
How to check if two Strings are Anagram in Java?
There are multiple ways to solve this problem. One way is to sort both strings
and then compare them. This way, all characters will come into the same place,
and if Strings are anagrams, then they will be equal to each other.
— 15 —
GROKKING THE JAVA INTERVIEW
import java.util.Arrays;
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + "
are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + "
are not anagrams.");
}
}
}
The program takes two strings as input and returns true if they are anagrams
of each other and false otherwise. It first checks if the lengths of the strings are
equal since if they're not, they cannot be anagrams. Then it converts both
strings to char arrays, sorts them, and checks if they are equal using the
Arrays.equals() method. If the char arrays are equal, the strings are anagrams
— 16 —
JAVA STRING INTERVIEW QUESTIONS
Question 35
What is character encoding? What is the difference between UTF-8 and
UTF-16?
That's all about the top 35 Java String Interview Questions. These questions
are not only good for preparing for Java job interviews but also expand your
knowledge about String in Java, one of the key classes of JDKD. Even after
programming in Java for more than 20 years, I still discover things about core
classes that I should have known earlier. Truly, there is so much to learn in Java.
— 17 —
CHAPTER 2:
It’s mostly fact-based questions, but some questions, like the difference between
abstract class and interface in Java and when to prefer abstract class over the
interface, can be tricky and require deep knowledge of object-oriented
programming and Java.
— 18 —
ABSTRACT CLASS AND INTERFACE QUESTIONS
Question 1
Can abstract classes have constructors in Java?
Yes, an abstract class can declare and define a constructor in Java. Since you
cannot create an instance of an abstract class, a constructor can only be called
during constructor chaining, i.e., when you create an instance of the concrete
implementation class.
Now some interviewers ask what the purpose of a constructor is if you can not
instantiate an abstract class. Well, it can still be used to initialize common
variables, declared inside an abstract class and used by various
implementations.
Question 2
Can abstract class implement the interface in Java? Do they require to
implement all methods?
— 19 —
GROKKING THE JAVA INTERVIEW
It’s the best of both worlds. You can get the advantage of an interface for
declaring the type and flexibility of abstract classes to implement common
behavior in one place. Effective Java has a nice chapter on how to use interface
and abstract classes in Java, which is worth reading.
Question 3
Can an abstract class be final in Java?
No, an abstract class can not be final in Java. Making them final will stop the
abstract class from being extended, which is the only way to use an abstract
class. They are also opposite each other. The abstract keyword enforces
extending a class for using it. On the other hand, the final keyword prevents a
class from being extended.
Question 4
Can abstract classes have static methods in Java?
Yes, an abstract class can declare and define static methods. Nothing prevents
doing that. But, you must follow guidelines for making a method static in Java, as
it’s not welcomed in an object-oriented design because static methods can not be
overridden in Java. It’s very rare you see static methods inside an abstract class, but
as I said, if you have a very good reason for doing it, then nothing stops you.
— 20 —
ABSTRACT CLASS AND INTERFACE QUESTIONS
Question 5
Can you create an instance of an abstract class?
No, you can not create instances of abstract classes in Java. They are
incomplete. Even though, if your abstract class doesn’t contain any abstract
method, you can not create an instance of it. By making a class abstract,
you told the compiler that it’s incomplete and should not be instantiated. Java
compiler will throw an error when a code tries to instantiate an abstract class.
Question 6
Is it necessary for an abstract class to have an abstract method?
No, it’s not mandatory for an abstract class to have any abstract method. You
can make a class abstract in Java by just using the abstract keyword in the
class declaration. The compiler will enforce all structural restrictions applied to
an abstract class, like, not allowing to create of any instance.
By the way, it’s debatable whether you should have an abstract method inside
the abstract class or interface. In my opinion, the abstract class should have
abstract methods because that’s the first thing programmer assumes when he
sees that class. That would also go nicely along with the principle of least
surprise.
Question 7
What is the difference between abstract class and interface in Java?
This is the most important and one of the classic Java Interview questions. I
don’t know how often I have seen this question at all levels of Java interviews.
One reason which makes this question interesting is the ability to produce
examples.
— 21 —
GROKKING THE JAVA INTERVIEW
points like this, a candidate more often fumbles. You can see this post for all
syntactical differences between abstract class and interface, but it deserves a
post on its own.
Question 8
When do you favor abstract classes over interface?
Abstract class in Java evolves better than the interface. Similarly, if you have too
many methods inside the interface, you create pain for all its implementation;
consider providing an abstract class for default implementation. This is the pattern
followed in the Java collection package. You can see AbstractList provides a
default implementation for the List interface.
Question 9
What is the abstract method in Java?
An abstract method is a method without a body. You just declare the method
without defining it and use abstract keywords in the method declaration.
All methods declared inside Java Interface are, by default, abstract. Here is an
example of an abstract method in Java:
To implement this method, you need to extend the abstract class and override
this method.
— 22 —
ABSTRACT CLASS AND INTERFACE QUESTIONS
Question 10
Can an abstract class contain the main method in Java?
Yes, an abstract class can contain the main() method. It is just another static
method; you can execute the Abstract class with the main method until you
don’t create any instance.
— 23 —
CHAPTER 3:
Java Inheritance
Interview Questions
It's expected of Java developers to know about these OOP concepts and have an
understanding of when to use them as many times. Composition is the better
choice than Inheritance because of the flexibility it offers, but when it comes to
leveraging polymorphism of type, you have to use Inheritance. In Java, inheritance
is supported by language using extends and implements keywords.
In Java, a class can extend another class and implement the interface,
but an interface can only extend other interfaces. At the same time, Java doesn't
support multiple inheritances just like C++ does, but it does support multiple
inheritances of type by allowing an interface to extend multiple interfaces. You
will see many such Inheritance based Java questions in this article.
— 24 —
JAVA INHERITANCE INTERVIEW QUESTIONS
Question 1
What is Inheritance in Java?
Question 2
What are the different types of Inheritance supported by Java?
Question 3
Why is multiple Inheritance not supported by Java?
Java was introduced after C++, and Java designers didn't want to take some
C++ features, which are confusing and unnecessary. They think multiple
— 25 —
GROKKING THE JAVA INTERVIEW
inheritances are one of them, which doesn't justify the complexity and
confusion it introduces. You can also check why multiple inheritances are not
supported in Java for more reasons and discussions around this.
Question 4
Why is Inheritance used by Java Programmers?
Question 5
How to use Inheritance in Java?
Question 6
What is the syntax of Inheritance?
Question 7
What is the difference between Inheritance and Encapsulation?
— 26 —
JAVA INHERITANCE INTERVIEW QUESTIONS
concept used to hide a class's internal details; e.g., HashMap encapsulates how to
store elements and calculate hash values.
Question 8
What is the difference between Inheritance and Abstraction?
Question 9
What is the difference between Polymorphism and Inheritance?
Both Polymorphism and Inheritance go hand in hand. They help each other to
achieve their goal. Polymorphism allows flexibility. You can choose which code
to run at runtime by overriding. See the detailed answer for more details.
Question 10
What is the difference between Composition and Inheritance in OOP?
— 27 —
GROKKING THE JAVA INTERVIEW
Question 11
Can we override the static method in Java?
No, you cannot override a static method in Java because it's resolved at compile
time. In order for overriding to work, a method should be virtual and resolved
at runtime because objects are only available at runtime. This is one of the
tricky Java questions where the interviewer tries to confuse you. A programmer
is never sure about whether they can override or overload a static method in
Java.
Question 12
Can we overload a static method in Java?
Yes, you can overload a static method in Java. Overloading has nothing to do
with runtime, but the signature of each method must be different. In Java, to
change the method signature, you must change either number of arguments,
type of arguments, or order of arguments.
Question 13
Can we override a private method in Java?
No, you cannot override a private method in Java because the subclass does not
inherit the private method in Java, which is essential for overriding. In fact, a
private method is not visible to anyone outside the class, and, more
importantly, a call to the private method is resolved at compile time by using
Type information as opposed to runtime by using the actual object.
Question 14
What is Method Hiding in Java?
Since the static method cannot be overridden in Java, declaring the same static
method in the subclass would hide the method from the superclass. It means if
you call that method from the subclass, then the one in the subclass will be
— 28 —
JAVA INHERITANCE INTERVIEW QUESTIONS
invoked, but if you call the same method from the superclass, then the one in
the superclass will be invoked. This is known as Method Hiding in Java.
Question 15
Can a class implement more than one interface in Java?
Yes, A class can implement more than one interface in Java, e.g., A class can be
both Comparable and Serializable simultaneously. This is why the interface
should be best for defining Type as described in Effective Java. This feature
allows one class to play a polymorphic role in the program.
Question 16
Can a class extend more than one class in Java?
No, a class can only extend just one more class in Java. Though Every class also,
by default, extends the java.lang.Object class in Java.
Question 17
Can an interface extend more than one interface in Java?
Unlike classes, an interface can extend more than one interface in Java. There
are several examples of this behavior in JDK, e.g., java.util.List
interface extends both Collection and Iterable interface to tell that it is
a Collection and allows iteration via Iterator.
Question 18
What will happen if a class extends two interfaces and they both have a
method with the same name and signature?
In this case, a conflict will arise because the compiler cannot link a method call
due to ambiguity. You will get a compile time error in Java.
— 29 —
GROKKING THE JAVA INTERVIEW
Question 19
Can we pass an object of a subclass to a method expecting an object of the
super class?
Yes, you can pass that because subclass and superclass are related by
Inheritance which provides IS-A property. Banana is a Fruit, so you can pass a
banana if somebody expects fruit. Now there are scenarios where you can't do,
e.g., when subclass violates the Liskov Substitution principle, i.e., you cannot
pass a plastic banana to someone expecting fruit :-), The eat() function will
throw an exception.
Question 20
What is the Liskov substitution principle?
The Liskov substitution principle is one of the five object-oriented design
principles, collectively known as SOLID principles.
For example, suppose a method is expecting a List. In that case, you can also pass
ArrayList or LinkedList, and it should work just fine because ArrayList and
LinkedList both follow Liskov Substitution Principle, but the java.sql.Date,
which is a subclass of java.util.Date in Java violates Liskov Substitution
Principle because you cannot pass an object of java.sql.Date class to a
method expecting an object of java.util.Date, Why? Because all time-related
methods will throw java.lang.UnsupportedOperationException.
— 30 —
JAVA INHERITANCE INTERVIEW QUESTIONS
Question 21
How do you call a subclass method if you are holding an object of the
subclass in a reference variable of type superclass?
You can call a subclass method by first casting the object held by the reference
variable of the superclass into the subclass. Once you hold the object in the
subclass reference type, you can call methods from the subclass. See how type
casting works in Java for more details.
— 31 —
CHAPTER 4:
Advanced Java
ClassLoader
Interview Questions
H ello guys, if you are preparing for Java interviews and want to refresh your
knowledge of Java Classloaders, you have baught the right book. I will
share frequently asked Java interview questions about class loaders in this
chapter. If you don't know, a class loader is a program that loads classes in Java
programs. The class loading mechanism is crucial to understanding how the
Java program works. When you run a Java program, you give the name of the
main class, and from there onwards, built-in classloaders like Bootstrap
classloader start loading not just the main classes but other Java library classes
which is required to run that program.
JVM uses three main class loaders to load all the classes required to execute a Java
program. They are Bootstrap class loader, Extension class loader, and System or
Application class loader. Except for the BootStrap ClassLoader, all ClassLoader is
implemented in Java and extends java.lang.ClassLoader, which is an
abstract class in Java.
— 32 —
ADVANCED JAVA CLASSLOADER INTERVIEW QUESTIONS
In this article, I have included basic and advanced class loader questions so that
you can get decent ideas about how a class loader works in a core Java
application and in a managed Java EE environment when web servers and
application servers are involved.
Question 1
What is ClassLoader in Java? From where do they load classes? And where
is class-related metadata stored?
ClassLoader in Java is a class that is used to load other classes in Java virtual
machines. This is the most frequently asked interview question about
ClassLoader in Java. There are primarily three class loaders that are used by the
JVM bootstrap class loader, extension class loader, and System or application
class loader.
Except for the Bootstrap class loader, all ClassLoader is implemented in Java
and extends java.lang.ClassLoader, which is an abstract class in Java.
Also, all the class-related metadata, like a class definition, fields, and methods,
are stored in the METASPACE part of JVM memory.
— 33 —
GROKKING THE JAVA INTERVIEW
Question 2
How does ClassLoader work in Java?
Question 3
What are the two rules of ClassLoader in Java?
— 34 —
ADVANCED JAVA CLASSLOADER INTERVIEW QUESTIONS
Question 4
Can you implement your own ClassLoader in Java?
Yes, you can implement your own ClassLoader in Java, which can load .class
files or any binary which can be translated or mapped into a .class file from any
source like a database or network. You need to extend
java.lang.ClassLoader is an abstract class that needs to override the
findClass() method, which takes delegation.
Question 5
Can multiple classloaders in Java load the same class?
Yes, the Same class can be loaded by multiple ClassLoaders in Java. A class is
uniquely identified by Java virtual machine by its fully qualified name and in
the context of ClassLoader. This is a very useful feature of Java ClassLoader,
which treats classes loaded from a different source even though they share a
name, which is very much a possibility on Applets, where classes are normally
downloaded from different sources.
Question 6
What does System.getClass().getClassLoader() return?
The getClassLoader() method of java.lang.The class returns
the class loader for the class, I mean, the name of ClassLoader which loaded
that particular class.
The bootstrap class loader loads system classes like String or any other class
from JDK, and they are implemented in the native language, mostly in C, and
don't have the corresponding java.lang.ClassLoader instance. So, this
call will return null.
System.out.println("System.getClass().getClassLoad
er() : " + System.class.getClassLoader());
Output : System.getClass().getClassLoader() : null
— 35 —
GROKKING THE JAVA INTERVIEW
Question 7
Can you load a class that is not in CLASSPATH?
Yes, it's possible to load classes that are not in Classpath. Since Java Virtual
Machine itself uses three different ClassLoader: BootStrap, extension, and
System or Application class loaders, out of that, only Application ClassLoader
uses CLASSPATH to search classes, and Extension ClassLoader loads a class
from jre/lib/ext directory.
Question 8
What is the extension ClassLoader in Java? From where does it load classes?
An extension class loader is one of three default class loaders that exist in the
Java programming language. Extension class loader is a child of BootStrap
ClassLoader and loads classes from the jre/lib/ext directory.
Question 9
What is the binary name of a Class in Java?
What do you think? Can you answer this question? If you know, just answer in
the comments, and I will put the first three people's names here who answered
it correctly.
— 36 —
ADVANCED JAVA CLASSLOADER INTERVIEW QUESTIONS
Question 10
What is the Context ClassLoader in Java?
Same here. Can you try to answer these questions without using Google? If you
can, just answer, and I will put the first three people names here who answer
this question correctly in the comments.
Question 11
Can two objects loaded from different ClassLoaders be equal in Java?
No, two objects loaded from different ClassLoaders cannot be the same. In the
run time, a class is recognized by its fully qualified name and in the context of
ClassLoader.
If you remember correctly, How to override the equals method in Java, you will
see that the equals method has a check for getClass(), which will return
false if two different ClassLoaders load it. If you don't have that check on
equals() method, it will throw ClassCastException while comparing two
classes loaded by different class loaders.
Question 12
Can Parent ClassLoader see classes loaded by Child ClassLoader in Java?
No, the Parent ClassLoader can not see classes loaded by the child ClassLoader
in Java. As explained in a first ClassLoader interview question, Java Classloader
works on the delegation principle, where a request to load a class is delegated
to the parent ClassLoader.
But if the parent doesn't find the class and ultimately the child loads that class, it
will not be visible to the parent ClassLoader, and any attempt to load that class
from the parent ClassLoader will result in NoClassDefFoundError in Java.
— 37 —
GROKKING THE JAVA INTERVIEW
Question 13
If you call Class.forName(), then which ClassLoader will load that
particular class?
Question 14
Do the classloader loads all the classes at the start?
No, not all the classes are loaded by classloaders from the start. Only those
which are needed are loaded. They follow lazy loading and only load the class
when a static variable or method is invoked. You can also load a class using the
Class.forName() method, which is often used to load JDBC driver classes
from respective JAR Files.
— 38 —
CHAPTER 5:
E num was introduced in Java 5, and since then, it's been very popular
among Java developers and widely used in different Java applications.
Since Enum in Java is much more versatile than Enum in C or C++, it also
presents many interesting use cases. But, despite being so popular, many Java
programmers are still unaware of Enum's functionality and the subtle details of
using Enum in Java code.
I realized this fact when a couple of my readers asked me questions like Can
Enum implement an interface in Java or Why we can not create Enum
instances outside of Enum, stating that these have been asked to them in their
Java Interviews.
This motivates me to put together a list of frequently asked questions in Java Enum,
which not only helps to do well in Interviews but also opens a new learning path.
As I had said before, a question in Interviews often makes you take a topic more
seriously than otherwise, which is not bad. Given the power and facilities offered
by Java Enum, I think it's high time to get a master of it.
— 39 —
GROKKING THE JAVA INTERVIEW
Question 1
Can Enum implement an interface in Java?
Yes, Enum can implement an interface in Java. Since an enum is a type similar
to a class and interface, it can implement an interface. In some cases, this
gives a lot of flexibility to use Enum as a specialized implementation.
Question 2
Can we use Enum in the switch case in Java?
Yes, you can use Enum in the Switch case in Java. That's one of the main
advantages of using Enum. Since Enum instances are compile-time constants,
you can safely use them inside switch and case statements.
Enum and Switch cases go well with each other, especially if Enum has a
relatively small number of fixed constants like seven days in a week, 12 months
in a year, etc.,
Question 3
How do you create Enum without any instance? Is it possible without
compile-time error?
This is one of those tricky Java questions that the Interviewer loves to ask. Since
Enum is viewed as a collection of a well-defined fixed number of instances like
— 40 —
JAVA ENUM INTERVIEW QUESTIONS
Days of Week, and Months in a Year, having an Enum without any instance
may seem awkward.
But yes, you can create Enum without any instance in Java, for creating a utility
class. This is another innovative way of using Enum in Java.
Question 4
Can we override toString() method for Enum? What happens if we don't?
Of course, you can override toString in Enum, as like any other class, it also
extends java.lang.Object and has toString() method available, but
even if you don't override, you will not going to regret it much because the
abstract base class of the enum does that for you and return the name, which is
the name of the enum instance itself. here is the code of the toString()
method from the Enum class :
Name is set, when compiler emits code for creating enum in response to
instance declaration in enum class itself, along with setting ordinal, as visible
in this enum constructor from java.lang.Enum class :
— 41 —
GROKKING THE JAVA INTERVIEW
This is the only constructor for creating an enum, which is called by code,
generated by the compiler in response to an enum type declaration in the Java
program.
Question 5
Can we create an instance of Enum outside of Enum itself? If Not, Why?
No, you can not create enum instances outside of the Enum boundary because
Enum doesn't have any public constructor, and the compiler doesn't allow you
to provide any public constructor in Enum. Since the compiler generates much
code in response to the enum type declaration, it doesn’t allow public
constructors inside Enum, which enforces declaring enum instances inside
Enum itself.
Question 6
Can we declare Constructor inside Enum in Java?
This is asked along with the previous question on Java Enum. Yes, you can, but
remember you can only declare either private or package-private constructor
inside the enum. Public and protected constructors are not permitted inside
the enum.
Question 7
What is the difference in comparing Enum with the == and equals() method?
Equals method of java.lang.Enum uses the == operator to check if two enums
are equal. This means you can compare Enum using both the == and equals
methods.
— 42 —
JAVA ENUM INTERVIEW QUESTIONS
By the way, there are subtle differences when you compare the enum with the ==
and equals method, which stems from == (equality operator) being an operator
and equals() being a method.
Question 8
What does the ordinal() method do in Enum?
The ordinal method returns the order in which Enum instances are declared
inside Enum. For example, in a DayOfWeek Enum, you can declare days in the
order they come e.g.
Similarly, you can use an enum to represent the Month of the year in the order
they come from, e.g., FEBRUARY after JANUARY and before MARCH.
— 43 —
GROKKING THE JAVA INTERVIEW
Question 9
Can we use Enum with TreeSet or TreeMap in Java?
This is an interesting question on Java Enum. I would love to ask this to gauge
knowledge of Enum until you know about java.lang.Enum and have
looked at its code.
It's more likely that you don't know that Enum implements a Comparable
interface, which is the main requirement to be used in Sorted Collections like
TreeSet and TreeMap. Since Enum by default impalement Comparable
interface, they can be safely used inside TreeSet or TreeMap in Java.
Question 10
What is the difference between the ordinal() and compareTo() in Enum?
This is a follow-up to the previous question on Java Enum. Actually,
compareTo() mimics ordering provided by the ordinal() method,
which is the natural order of Enum.
In short, Enum constraints are compared in the order they are declared. Also
worth remembering is that enum constants are only comparable to other enum
constants of the same enum type. Comparing the enum constant of one type to
another type will result in a compiler error.
Question 11
Can Enum extend a class in Java?
No, Enum can not extend the class in Java. Surprised because I just said it's a
type as a class or interface in Java. That is why this question is a good
follow-up to the previous Enum interview question.
— 44 —
JAVA ENUM INTERVIEW QUESTIONS
Question 12
How to iterate over all instances of an Enum?
Well, if you have explored java.lang.Enum, you know that a values()
method returns an array of all enum constants. Since every enum type
implicitly extends java.lang.Enum, they get these values() method.
Using this, you can iterate over all enum constants of a certain type.
Question 13
What are the advantages and disadvantages of using Enum as Singleton?
Enum provides you with a quick shortcut to implement the Singleton design
pattern, and ever since it was mentioned in Effective Java, it's also been a
popular choice.
On the face, Enum Singleton looks very promising and handles a lot of stuff for
you, e.g., controlled instance creation, Serialization safety. On top of that, it’s
extremely easy to create thread-safe Singleton using Enum. You don’t need to
worry about double-checking locking and volatile variables anymore.
Question 14
What is the advantage of using Enum over an enum int pattern and an enum
String pattern?
Suppose you have been coding for over five years and coded in JDK 1.3 and 1.4.
In that case, you must be familiar with the Enum String pattern and enum int
pattern, where we used public static final constants to represent a collection of
a well-known fixed number of things like DayOfWeek.
There were a lot of problems with that approach like you don't have a dedicated
enum type. Since it's a String variable representing days of the week, it can take
any arbitrary value. Similarly, the enum int pattern can take any arbitrary value;
the compiler doesn't prevent those.
By using Enum, you get this type-safety and compiler checking for you.
— 45 —
GROKKING THE JAVA INTERVIEW
Question 15
How to convert a String to Enum in Java?
This is a day-to-day ask, given the popularity of String and Enum in Java
application development. The best way for converting Enum to String is to
declare a factory method inside Enum itself, which should take a String
argument and return an Enum. You can choose to ignore the case as well.
That's all on this list of Java 15 Enum Interview Questions and Answers. Just
remember though, reading is not enough for learning, it's just a first step. To
get proficient with an enum, try to find out where you can use Enum in your
project. This will give you REAL experience, and with real experience, you learn
a lot more than a sample application because you tend to face more issues and
handle the rather complex and detailed requirements. Nevertheless, these Java
15 Enum questions are still worth revising your knowledge, especially if you are
rushing for an Interview and don't have enough time to explore Enum in detail.
— 46 —
CHAPTER 6:
Java ArrayList
Interview Questions
H ello guys, if you are preparing for Java interviews, then you have come to
the right place. In this chapter, I will share some good Java interview
questions based on the ArrayList class. I have hardly seen a Java interview
without any questions from ArrayList, and why not? It's one of the most
popular collection classes, and every Java developer uses it daily. Another
reason for asking a question related to ArrayList is that you can ask a wide
variety of questions to really check the breadth and depth of a candidate's
knowledge.
To give you some idea about ArrayList, it's a collection class that
implements the List interface. It's an alternative to an array data structure
whose size you cannot change once created. ArrayList is a dynamic array that
can grow and resize itself.
By implementing the List interface, it also got some properties like ordering,
ArrayList keeps the element in the order they are inserted, and it also provides
constant-time search operation if you know the index of an element like
get(index) is O(1) operation.
— 47 —
GROKKING THE JAVA INTERVIEW
This makes ArrayList an ideal choice when you are looking to retrieve values
based on the index.
I am sure you know the basics, but you will learn more by reviewing some of
these frequently asked Java ArrayList questions.
Question 1
How to remove duplicates from ArrayList in Java?
— 48 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
4. The new ArrayList will have all the elements of the original ArrayList
with duplicates removed.
Here's an example:
Question 2
How to reverse ArrayList in Java?
— 49 —
GROKKING THE JAVA INTERVIEW
import java.util.ArrayList;
import java.util.Collections;
Collections.reverse(fruits);
Output:
— 50 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
Question 3
What is the difference between an array and an ArrayList in Java?
Question 4
How to synchronize ArrayList in Java?
Question 5
When to use ArrayList and LinkedList in Java?
This is by far the most popular ArrayList based question from Java Interviews,
and you can answer it very easily if you are familiar with two key data
structures, array and linked list.
Since the array provides constant-time search operation, it's better to use
ArrayList if search outnumbers add and remove operation. Otherwise, use
LinkedList, which provides constant time add and remove operation.
— 51 —
GROKKING THE JAVA INTERVIEW
Question 6
What is the difference between ArrayList and HashSet in Java?
One of the simplest questions you will ever see in a Java interview. The main
difference is the former is List while the latter is Set which means ArrayList
allows duplicates and keeps elements in order, while HashSet doesn't allow
duplicates and provides no ordering guarantee.
Question 7
How to loop over ArrayList in Java?
There are many ways to traverse over ArrayList, you can use the classic for loop
with index, or you can take an iterator from ArrayList and can use a while loop
in conjunction with Iterator.hasNext() method, Or you can use the new for
each loop introduced in Java 5, which doesn't require an index.
Question 8
What is the difference between Vector and ArrayList in Java?
This is the second most popular question based on ArrayList in Java. Though
both Vector and ArrayList implement List interface, Vector is synchronized
while ArrayList is not synchronized, which means the former is thread-safe and
fast while the latter is not thread-safe and slow.
Question 9
How to create and initialize ArrayList in one line?
— 52 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
Question 10
How to sort ArrayList in Java?
Another task-based ArrayList interview question. You can easily sort the
ArrayList by using the Collections.sort() method. All you need to do
is make sure that elements implement either the Comparable or Comparator
interface. The former is used to sort in the natural order which is increasing
order for a List with numbers, while the latter is used while sorting in the
custom order.
Here's an example:
import java.util.ArrayList;
import java.util.Collections;
Collections.sort(numbers);
— 53 —
GROKKING THE JAVA INTERVIEW
Output:
Before sorting: [3, 1, 4, 2]
After sorting: [1, 2, 3, 4]
In the example above, we first create an ArrayList of integers and add some
elements to it. Then, we print the elements of the ArrayList before sorting.
Next, we call the Collections.sort() method to sort the elements in ascending
order. Finally, we print the elements of the ArrayList after sorting.
Question 11
What is the difference between HashMap and ArrayList in Java?
Question 12
How to use ArrayList in Java?
You can use ArrayList in Java for storing objects where you want fast search
with index as well you want to keep them in the order they are inserted into the
list. ArrayList also allows duplicates.
Question 13
How to convert ArrayList to String in Java?
— 54 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
import java.util.ArrayList;
— 55 —
GROKKING THE JAVA INTERVIEW
Question 14
How to get a sublist from ArrayList in Java?
This is another task-based question, but you can easily do it if you remember
API. You can get a list of elements in a range by using the subList() method
from the ArrayList class. This would be very helpful in case of a sorted list.
This method takes two parameters, the starting index and the ending index
(exclusive) of the sublist. Here's an example:
System.out.println(sublist); // [2, 3, 4]
Question 15
What is the difference between the length() of the array and the size() of
ArrayList in Java?
This is one of the tricky questions. If you get the backed array and call the
length(), it will return how many elements you can store in this array, also
known as capacity, but if you call the size() function of the ArrayList class, then
it will return a total number of elements currently stored in ArrayList, which is
always less than or equal to capacity.
— 56 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
Question 16
What is CopyOnWriteArrayList in Java?
Question 17
How to remove objects from ArrayList in Java?
There are two ways to remove elements from ArrayList. First, you can call the
remove(int index) method and pass on the index of the element you
want to remove, and second, you can call the remove(Object obj)
method and pass the element you want to remove. By the way, just be careful
while working with an ArrayList of integers because autoboxing can cause
issues by creating an ambiguity between two remove methods.
— 57 —
GROKKING THE JAVA INTERVIEW
Question 18
How to make ArrayList read-only in Java?
Another task and API-based interview question. You can answer it easily if you
are about the Collections utility class, which provides several wrappers of the
standard ArrayList class, e.g., you can use Collections to create a synchronized
version or read-only version of ArrayList in Java. From Java 11 onwards, you
can make an ArrayList read-only by wrapping it in an unmodifiable list using
the Collections.unmodifiableList() method. This creates an unmodifiable
view of the original list, so any attempts to modify the list will result in an
UnsupportedOperationException.
List<String> readOnlyList =
Collections.unmodifiableList(originalList);
It's important to note that although the read-only list cannot be modified
directly, it is still possible to modify the original list. Any changes made to the
— 58 —
JAVA ARRAYLIST INTERVIEW QUESTIONS
original list will be reflected in the read-only view. If you need to ensure that
the list cannot be modified in any way, you should consider making a defensive
copy of the list before wrapping it in an unmodifiable view. Question 19
How to sort ArrayList in descending order in Java?
This is the follow-up question to one of the previous questions related to sorting.
By default, elements are sorted in increasing order as this is how their
compareTo() or compare() method compares them. If you want to sort into
descending order, just reverse the comparison logic using the Collections
.reverseComparator() or Collections.revrseOrder() method.
In this example, we create an ArrayList called list with four elements. We then
sort the list in descending order using the Collections.sort() method and
passing Collections.reverseOrder() as the Comparator. This method returns
a Comparator that sorts the elements in reverse order. Finally, we print the
sorted list to the console.
You can use this same approach to sort an ArrayList of any type in descending
order, as long as you provide an appropriate Comparator for that type.
— 59 —
GROKKING THE JAVA INTERVIEW
That's all about ArrayList questions from Java Interviews. I have covered
almost everything I know, which has been asked previously of many Java
programmers, both freshers and experienced with 2 to 5 years of experience.
Some companies which give more importance to coding skills can also ask you
to implement your own ArrayList class in Java, so be prepared for that also.
You can always use an array to implement ArrayList in Java.
— 60 —
CHAPTER 7:
Java HashMap
Interview Questions
Though, if you have a special need, you can use other hash table implementations
available in JDK. For example, if you want to preserve the order of mapping, then
you can consider using LinkedHashMap. If you wish to keep mappings sorted,
then you can use TreeMap, which is a sorted map implementation.
Similarly, if you need a hash table implementation that is thread-safe and can
be used in a concurrent application without compromising the Scalability, then
consider using a ConcurrentHashMap from JDK 5.
— 61 —
GROKKING THE JAVA INTERVIEW
Question 1
How does the put() method of HashMap works in Java?
Question 2
What is the requirement for an object to be used as a key or value in
HashMap?
The key or value object must implement the equals() and hashcode()
methods. The hash code is used when you insert the key object into the map,
while equals are used when you try to retrieve a value from the map.
Question 3
What will happen if you try to store a key that is already present in
HashMap?
If you store an existing key in the HashMap, then it will override the old value
with the new value, and put() will return the old value. There will not be any
exceptions or errors.
— 62 —
JAVA HASHMAP INTERVIEW QUESTIONS
Question 4
Can you store a null key in Java HashMap?
Yes, HashMap allows one null key, which is stored at the first location of the
bucket array, e.g., bucket[0] = value. The HashMap doesn't call
hashCode() on the null key because it will throw NullPointerException. Hence
when a user calls the get() method with null, then the value of the first index
is returned.
Question 5
Can you store a null value inside HashMap in Java?
Yes, HashMap also allows null values; you can store as many null values as you
want, as shown in the hashmap example post in this blog.
Question 6
How does HashMap handle collisions in Java?
In the worst case, where all key has the same hashcode, your hash table will be
turned into a linked list, and searching for a value will take O(n) time as
opposed to O(1) time.
If you want to learn more about hash table data structure, I suggest you consult
a good data structure and algorithm course like these best data structures and
algorithms courses, which cover not only basic data structures like an array,
linked list, binary tree, and hash table but also advanced concepts like O(n)
sorting algorithms, Radix sort, Counting sort, etc.
— 63 —
GROKKING THE JAVA INTERVIEW
Question 7
Which data structure does HashMap represent?
Question 8
Which data structure is used to implement HashMap in Java?
Question 9
Can you store a duplicate key in HashMap?
No, you cannot insert duplicate keys in HashMap. It doesn't allow duplicate
keys. If you try to insert an existing key with the new or same value, then it will
override the old value, but the size of HashMap will not change, i.e., it will
remain the same. This is one of the reasons why you get all keys from the
HashMap by calling keySet(). It returns a Set, not a Collection because a Set
doesn't allow duplicates.
Question 10
Can you store the duplicate value in Java HashMap?
Yes, you can put duplicate values in the HashMap of Java. It allows duplicate
values; that's why when you retrieve all values from the Hashmap by calling the
values() method, it returns a Collection and not a Set. Worth noting is that it
— 64 —
JAVA HASHMAP INTERVIEW QUESTIONS
doesn't return List because HashMap doesn't provide any ordering guarantee
for key or value.
Question 11
Is HashMap thread-safe in Java?
No, HashMap is not a thread-safe in Java. You should not share a HashMap
with multiple threads if one or more thread is modifying the HashMap, e.g.,
inserting or removing a map. Though, you can easily share a read-only
HashMap.
Question 12
What will happen if you use HashMap in a multithreaded Java application?
Question 13
What are the different ways to iterate over HashMap in Java?
— 65 —
GROKKING THE JAVA INTERVIEW
Question 14
How do you remove a mapping while iterating over HashMap in Java?
while(itr.hasNext()){
Map.Entry current = itr.next();
if(current.getKey().equals("matching"){
itr.remove(); // this will remove the current
entry.
}
}
You can see that we have used Iterator.remove() method to remove the
current entry while traversing the map.
Question 15
In which order are mappings stored in HashMap?
Random order because HashMap doesn't provide any ordering guarantee for
keys, values, or entries. When you iterate over a HashMap, you may get a
different order every time you iterate over it.
Question 16
Can you sort HashMap in Java?
No, you cannot sort a HashMap because, unlike List, it is not an ordered
collection. Albeit, you can sort the contents of HashMap by keys, values, or by
— 66 —
JAVA HASHMAP INTERVIEW QUESTIONS
entries by sorting and then storing the result into an ordered map like
LinkedHashMap or a sorted map, e.g., TreeMap.
Question 17
What is the load factor in HashMap?
Question 18
How does resize happen in HashMap?
The resizing happens when the map becomes full or when the size of the map
crosses the load factor. For example, if the load factor is 0.75 and then becomes
more than 75% full, then resizing trigger, which involves an array copy. First, the
size of the bucket is doubled, and then old entries are copied into a new bucket.
Question 19
How many entries can you store in HashMap? What is the maximum limit?
There is no maximum limit for HashMap. You can store as many entries as you
want because when you run out of the bucket, entries will be added to a linked
list that can support an infinite number of entries, of course, until you exhaust
all the memory you have.
Btw, the size() method of HashMap returns an int, which has a limit. Once
a number of entries cross the limit, size() will overflow, and if your program
relies on that, then it will break.
This issue has been addressed in JDK 8 by introducing a new method called
mappingCount(), which returns a long value. So, you should use
mappingCount() for large maps.
— 67 —
GROKKING THE JAVA INTERVIEW
Question 20
What is the difference between the capacity and size of HashMap in Java?
The capacity denotes how many entries HashMap can store, and size
denotes how many mappings or key/value pair is currently present.
Question 21
What will happen if two different keys of HashMap return the same
hashcode()?
If two keys of HashMap return the same hash code, then they will end up in the
same bucket; hence collision will occur. They will be stored in a linked list
together.
That's all about important Java HashMap interview questions. I have tried to
answer them as well, but if you disagree with an answer, then feel free to
comment. Since HashMap is a very important class in Java and equally
important from the Java interview point of view, it pays to understand this class
and its implementation in depth. These questions will not only help you to
understand HashMap better but also encourage you to find out more about
HashMap, its Java implementation, and hash table data structure in general.
— 68 —
CHAPTER 8:
Java
ConcurrentHashMap
Interview Questions
Because of its performance and scalability, as well as thread safety, it is the most
popular choice of Map in concurrent Java applications.
— 69 —
GROKKING THE JAVA INTERVIEW
Anyway, let's start with this list of Java interview questions based on
ConcurrentHashMap class and the concepts around it.
These questions will not only help you to do well in interviews but also
encourage you to learn more about the concurrent hash map, which will
eventually help you in your day-to-day programming job.
Question 1
What is ConcurrentHashMap in Java?
Question 2
Does ConcurrentHashMap thread-safe in Java?
— 70 —
JAVA CONCURRENTHASHMAP INTERVIEW QUESTIONS
Question 3
How does ConcurrentHashMap achieve thread safety?
Question 4
Can multiple threads read from ConcurrentHashMap same time?
Question 5
Can one thread read and the other write on ConcurrentHashMap at the
same time?
Yes, it's possible for a small number of writes. For example, if a write operation
is modifying one segment of ConcurrentHashmap and a read operation is
happening on other segments, then a reader will not block, but if the reader
thread is also trying to read from the same segment, then it will block until the
writer is done.
Question 6
How does ConcurrentHashMap work internally?
— 71 —
GROKKING THE JAVA INTERVIEW
Question 7
How do you atomically update a value in ConcurrentHashMap?
It accepts both old values and new values and only updates the map if the
existing value in the map matches with the old value provided. This means the
map is not concurrently modified during its call.
If the existing value is changed and does not match with the old value, then
replace fails and returns false. You can use call the replace() method in the
while loop until you succeed, as shown below:
— 72 —
JAVA CONCURRENTHASHMAP INTERVIEW QUESTIONS
Question 8
How do you remove a mapping while iterating over ConcurrentHashMap?
while(iterator.hasNext()){
if(iterator.next().contains("Java")){
iterator.remove();
}
}
System.out.println("after removing : " +
bookAndPrice);
Output
before removing : {Java Concurrency in Practice=33,
Head First Design Patterns=41, Effective Java=42,
Head First Java=29}
after removing : {Head First Design Patterns=41}
— 73 —
GROKKING THE JAVA INTERVIEW
Question 9
Does the Iterator of ConcurrentHashMap fail-safe or fail-fast?
Question 10
What will happen if you add a new mapping in ConcurrentHashMap
while one thread is iterating over it?
Question 11
Can you pass an object of ConcurrentHahsMap when a Map is expected?
— 74 —
JAVA CONCURRENTHASHMAP INTERVIEW QUESTIONS
Though, this means you may not have access to methods declared in the
java.util.concurrent.ConcurrentHashMap class, e.g., forEachKey() or
forEachValue() method added in Java 8.
— 75 —
CHAPTER 9:
Since the Java development job market is perfect at this moment. There are
many jobs open, particularly in the investment banking domain in Asia Pacific.
It's probably the best time to change your job, especially if you are stuck with
no learning, no salary increment, and not a significant bonus or incentive in
the last couple of years.
— 76 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
Apart from stability, growth is significant because if you don't move forward,
you will be stuck and eventually move backward; hence, changing jobs is as
important as sticking to a working job.
Question 1
Does SimpleDateFormat be safe to use in the multithreaded program?
Question 2
How do you format a date in Java? Like in the ddMMyyyy format?
You can either use the SimpleDateFormat class or the joda-time library to
format the date in Java. DateFormat class allows you to format data in many
popular formats. From Java 8 onwards you can also use new Date and Time
API and DateFormatter class to format a date in Java.
— 77 —
GROKKING THE JAVA INTERVIEW
Here's an example of how to format a date in the ddMMyyyy format using Java
8:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
In this example, we first get the current date using the LocalDate.now()
method. Then, we create a DateTimeFormatter object using the ofPattern()
method, passing in the desired date format as a string. Finally, we format the
date using the format() method of the LocalDate class and print the result to
the console.
Question 3
Can you tell some differences between the old and new Date Time API of
Java 8?
Even though the new Date and Time APIs are completely new APIs, you can
deduce the following difference between them:
1) In the old API, Date was mutable, but in Java 8, all date and time classes
like LocalDate, LocalTime, or LocalDateTime are Immutable.
2) In the old API, SimpleDateFormat was not thread-safe, but in Java 8,
Formatter is thread-safe.
— 78 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
3) In the old Date and Calendar API, the Year starts with 1900, and
Months start with 0, which is corrected in Java 8; here, the numbers
make more sense.
4) Old Date and Calendar API has just one class, Date, to represent date
and time, but Java 8 has separated classes for Date and Time, e.g.,
LocalDate and LocalTime
Question 4
Which date does the following Date instance represent?
This is a tricky question for casual Java developers who have no written date
and time-based code because this will not represent Christmas day or 25th
December 2015. This code has got two bugs. First, the year starts in 1900 and
represents 2015. You need to pass 115, i.e., 2015-1900.
The second issue with this code is that the month is not correct. The month
starts from 0, so December would be 11, not 12. Interesting right? That's why
you should use the new Date and Time API from Java 8, which solves all these
issues.
Question 5
How do you copy a Date in Java?
It's a simple question to answer. The Date class implements the clone() method,
so just call the date.clone() to create a copy of the Date object in Java.
Question 6
What is the relationship between java.sql.Date and java.util.Date?
This is one of the exciting questions as not many developers know this fine but
obvious detail. The java.sql.Date extends java.util.Date and suppresses
— 79 —
GROKKING THE JAVA INTERVIEW
all time-related methods to act as just a date class. This is in direct violation of
the Liskov substitution principle.
Question 7
Can you format Calendar in Java?
No, the Calendar cannot be formatted in Java. You can only format dates.
Question 8
How do you convert a Calendar to a Date and vice versa?
Question 9
What is the equivalent of a Date class in Java 8?
Question 10
How do you convert a millisecond to a Date in Java?
Question 11
How do you get a month and year from a Date object in Java?
You can convert a Date to a Calendar and then use its get() method with
various fields to get the month, year, day of the week, and other date particulars
e.g.
— 80 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
Better, you should use Java 8 API . In Java 8, you can use the java.time package
to get a month and year from a java.util.Date object. Here's an example:
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.Date;
In this example, we first convert the Date object to a LocalDate object using
the toInstant() method and the system default time zone. Then we can use the
getMonthValue() and getYear() methods to get the month and year from the
LocalDate object. Alternatively, we can use the YearMonth class to get the year
and month together.
— 81 —
GROKKING THE JAVA INTERVIEW
Question 12
How do you convert XMLGregorianCalendar to Date in Java?
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
— 82 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
Question 13
How do you get the current time in GMT in Java?
The Java date is independent of time and displays time in a current time zone
only if you print them. So, to convert the current time to GMT, you need to use
a Calendar with a time zone as shown in the given answer. Alternatively, you
can also use Java 8 Date and Time API. For example, To get the current time
in GMT (Greenwich Mean Time) in Java, you can use the
java.time.OffsetDateTime class along with the java.time.ZoneOffset class.
Here's an example code snippet:
Question 14
Is the java.util.Date class Immutable in Java?
No, the Date is not immutable. You can change its internal to represent a
different date. This is why when you have a member variable which represent
Date, you must be careful not to leak its reference outside using the
getDate() method because then the client can modify the state of the
Immutable object. Instead, a copy should be returned to the client.
Alternatively, you should use LocalDate, LocalTime, and LocalDateTime
classes from Java 8 API which are both immutable and preffered in new code.
— 83 —
GROKKING THE JAVA INTERVIEW
Question 15
How do you add and subtract a day, month, and year in a Date object?
This is one of the common day-to-day tasks of a Java developer. In Java, you
can add and subtract a day, month, and year from a Date object using the
Calendar class or you can use Java 8 Date and Time classes like LocalDate,
LocalTime, and LocalDateTime to get the current date and time, create a
specific date, and manipulate dates by adding and subtracting days and
months.
Here is an example:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
// Create a date
LocalDate date = LocalDate.of(2023, Month.JANUARY,
26);
System.out.println("Date: " + date);
— 84 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
Question 16
How do you compare two dates in Java to check if they are equal?
This is one of the easier questions you will see in terms of skill checking on Date
classes. The java.util.Date class implements the equals() method,
which returns true if both Dates are the same and false otherwise. You can
also use the compareTo() method to compare two date objects in Java as shown
below:
— 85 —
GROKKING THE JAVA INTERVIEW
In both cases, the equals() method and compareTo() method will return true
if the two dates represent the same point in time, and false otherwise.
Question 17
How do you find if one date comes before or after another date in Java?
This is the follow-up question to the previous question. The interviewer further
checks the candidate's date comparison skill by asking this question. The
answer is simple, the java.util.Date class provides before() and
after() method, which returns true and false if the date on which the
method is called comes before or after the other date passed as a method
argument.
Question 18
How do you convert java.util.Date to java.sql.Date in Java
JDBC?
Question 19
How to convert local time to GMT in Java?
To convert local time to GMT in Java, you can use the java.time package that
was introduced in Java 8.
— 86 —
JAVA DATE, TIME, AND CALENDAR INTERVIEW QUESTIONS
Here's an example:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
In this example, we first create a LocalDateTime object representing the local time.
We then get the local time zone using the ZoneId.systemDefault() method. We
use the atZone() method to convert the LocalDateTime to a ZonedDateTime
object in the local time zone. Finally, we use the withZoneSameInstant() method
to convert the ZonedDateTime to GMT, and then format the output using
DateTimeFormatter.ISO_LOCAL_DATE_TIME.
Note that the java.time package is thread-safe and provides many other
features for working with date and time in Java.
— 87 —
GROKKING THE JAVA INTERVIEW
Question 20
What is the difference between java.util.Date and java.sql.Date
in Java?
There are many differences between them, but the most important one is that
java.sql.The date is from the JDBC package, and it acts as converted
between Date and Time data types in the database and Date in Java.
Question 21
How do you calculate the difference between two dates in Java?
There are multiple ways to calculate the difference between two dates in Java,
e.g., you can get the long millisecond values from two dates and get the
difference, but that's not very valuable; you mostly need the difference in days
or hours. See the program to learn more about those differences.
Question 22
How do you convert a string (YYYYMMDD) to date in Java?
That's all about the frequentlya sked Date, Time, and Calendar based Java
Interview Questions. A Java developer needs to have a solid understanding of
Java's Date and Time API, both old and new because you will not find Java 8 in
every project you work on. You still need to know how to work with the old
Date and Calendar API while maintaining the legacy project for a couple more
years.
— 88 —
CHAPTER 10:
Equals and
HashCode Interview
questions
E quals and HashCode methods in Java are two fundamental methods from
java.lang.Object class, which is used to compare the equality of objects, is
primarily inside hash-based collections such as Hashtable and HashMap.
Both equals() and hashCode() are defined in java.lang.Object
class and their default implementation are based upon Object information, e.g.,
the default equals() method returns true if two objects are exactly the same,
i.e., they are pointing to the same memory address, while the default
implementation of the hashcode method return int, and is implemented as
a native method. A similar default implementation of the toString()
method returns the type of class, followed by the memory address in hex String.
It's advised to override these methods based on logical and business rules,
e.g., String overrides equals to check the equality of two String based upon
content. We have also seen the example implementation of equals() and
— 89 —
GROKKING THE JAVA INTERVIEW
hashCode for custom classes. Because of their usefulness and usage, they are
also very popular in various levels of Java Interviews, and
In this tutorial, I am going to share some of the really interesting questions from
equals() and hashCode() methods in Java. This question not only tests
your concept of both methods but also gives you an opportunity to explore
them more.
Reading those items and trying examples will give you enough confidence to
face any question on equals and hashCode methods. I also suggest reading
Effective Java Items on equals() and hashCode() to fill your gaps in
knowledge of these two critical methods.
Question 1
When you are writing the equals() method, which other method or methods
do you need to override?
Hashcode is the right answer. Since equals and hashCode have their
contract, so overriding one and not the other will break the contract between
them. By the way, this question can lead to an interesting discussion if the
Interviewer likes to go on deep, e.g., he may ask what those contracts are, what
happens if those contracts break, etc.
I like to give an example of How equals and hashcode are used in hash-
based collections, e.g., Hashtable, which leaves a positive impression more
often. You can also mention compareTo() here to score some additional
— 90 —
EQUALS AND HASHCODE INTERVIEW QUESTIONS
points. This method should also need to be consistent with equals, which is
another interesting question on our list.
Question 2
Can two objects which are not equal have the same hashCode?
YES, two objects which are not equal to equals() method can still return the
same hashCode. By the way, this is one of the confusing bits of equals and
hashcode contracts.
Question 3
How does the get() method of HashMap work if two keys have the same
hashCode?
Question 4
Where have you written equals() and hashCode in your project?
This is to see if the developer has even written these methods or not. Of course,
almost all Java programmers are exposed to this. You can point out value
objects and Hibernate entities from your domain, where you have overridden
equals and hashCode. Always give examples from your domain and from your
project rather than a trivial example from a test program because if the
Interviewer is asking this question, it means he is interested in examples from
your domain.
— 91 —
GROKKING THE JAVA INTERVIEW
Question 5
Suppose your Class has an Id field; should you include it in equals()? Why?
Question 6
What happens if equals() is not consistent with the compareTo() method?
This is an interesting question, which is asked along with the equals() and
hashCode() contracts. Some java.util.Set implementations, e.g.,
SortedSet or its concrete implementation TreeSet uses the
compareTo() method for comparing objects. If compareTo() is not
consistent means it doesn't return zero, and if the equals() method returns
true, it may break Set contract, which is not to avoid any duplicates.
Question 7
What happens if you compare an object to a null using equals()?
— 92 —
EQUALS AND HASHCODE INTERVIEW QUESTIONS
Question 8
What is the difference in using instanceof and getClass() method for
checking type inside equals?
This question was asked multiple times, sometimes by looking at your equals()
and hashCode implementation. Well, the key difference comes from the point
that instanceof operator returns true, even if compared with the subclass,
e.g., Subclass instanceof Superclass is true, but with getClass(), it's false.
Question 9
How do you avoid NullPointerException, while comparing two Strings in
Java?
Since when compared to null, equals return false and doesn't throw
NullPointerException, you can use this property to avoid NPE while
using comparing String. Suppose you have a known String "abc" and you are
comparing with an unknown String variable str, then you should call equals as
"abc".equals(str). This will not throw an Exception in thread Main:
java.lang.NullPointerException, even if str is null.
— 93 —
GROKKING THE JAVA INTERVIEW
Question 10
What is the difference between the "==" and the equals() method in Java?
One of the most classic interview questions on equals(). It has been asked
numerous times during the past decade and its also one of the basic concept
every Java developer should be aware of.
When comparing two objects using "==", Java checks whether the two
references point to the same memory location. In contrast, when using the
equals() method, Java compares the contents of the two objects to check for
equality.
That's all on this list of Java Interview Questions on Equals and HashCode
methods in Java. It's one of the fundamental concepts of Java programming
language, but yet it has several subtle things which are unknown to many Java
programmers. I strongly suggest getting yourself really good on equals(),
hashCode(), compareTo(), and compare() methods, not only to do
well on Java Interviews but also to write correct code in Java.
— 94 —
CHAPTER 11:
H ello guys, if you are preparing for a Java developer interview, then you may
know that Networking and Socket Programming is one of the important
areas of Java programming language, especially for those programmers who are
working in client server-based applications. Knowledge of important protocols
like TCP and UDP in detail is very important, especially if you are in the
business of writing high-frequency trading applications which communicate
via FIX Protocol or native exchange protocol. In this article, we will discuss
some of the frequently asked questions on networking and socket programming,
mostly based on TCP IP protocol.
This chapter is kinda light on NIO, though, as it doesn't include questions from
multiplexing, selectors, ByteBuffer, and FileChannel, but it does
include classical questions like the difference between IO and NIO.
The main focus of this post is to make Java developers familiar with low-level
parts like how TCP and UDP protocol works, socket options, and writing multi-
threaded servers in Java.
— 95 —
GROKKING THE JAVA INTERVIEW
The questions discussed here are not really tied up with Java programming
language and can be used in any programming language, which allows
programmers to write client-server applications.
By the way, If you are going for an interview on Investment banks for a core
Java developer role, you better prepare well on Java NIO, Socket Programming,
TCP, UDP, and Networking, along with other popular topics like multi-
threading, Collections API, and Garbage Collection tuning. You can also
contribute any question which is asked of you or related to socket
programming and networking and can be useful for Java interviews.
Question 1
What is the difference between TCP and UDP protocol?
There are many differences between TCP (Transmission Control Protocol) and
UDP (User Datagram Protocol), but the main is that TCP is connection-
oriented, while UDP is connectionless. This means TCP provides guaranteed
delivery of messages in the order they are sent, while UDP doesn't provide any
delivery guarantee.
— 96 —
NIO, SOCKET, AND NETWORKING INTERVIEW QUESTIONS
like order and trade messages in electronic trading, wire transfers in banking
and finance, etc. UDP is more suited for media transmission, where the loss of
one packet, known as datagrams, is affordable and doesn't affect the quality of
service.
This answer is enough for most of the interviews, but you need to be more
detailed when you are interviewing as a Java developer for a high-frequency
trading desk. Some of the points which many candidates forget to mention are
order and data boundary.
In TCP, messages are guaranteed to be delivered in the same order as they are
sent, but data boundary is not preserved, which means multiple messages can
be combined and sent together, or the receiver may receive one part of the
message in one packet and other parts of the message in next packet.
Though the application will receive the full message in the same order, TCP
protocol will do the assembling of the message for you. On the other hand,
UDP sends a full message in a datagram packet. If clients receive the packet, it
is guaranteed that they will get the full message, but there is no guarantee that
the packet will come in the same order they are sent.
In short, you must mention the following differences between TCP and UDP
protocols while answering during the interview:
— 97 —
GROKKING THE JAVA INTERVIEW
Question 2
How does TCP handshake work?
Three messages are exchanged as part of the TCP head-shake, e.g., Initiator
sends SYN. Upon receiving this, Listener sends SYN-ACK, and finally, the
initiator replies with ACK. At this point, the TCP connection is moved to the
ESTABLISHED state. This process is easily understandable by looking at the
following diagram.
Question 3
How do you implement reliable transmission in UDP protocol?
If the receiver finds that it has missed a sequence number, it can ask for a replay
of that message from the Server. TRDP protocol, which is used by Tibco
Rendezvous (a popular high-speed messaging middleware), uses UDP for
faster messaging and provides a reliability guarantee by using sequence
numbers and retransmission.
Question 4
What is Network Byte Order? How do two hosts communicate if they have
different byte-ordering?
There are two ways to store two bytes in memory, little-endian (least significant
byte at the starting address) and big-endian (most significant byte at the
starting address). They are collectively known as host byte orders.
For example, an Intel processor stores the 32-bit integer as four consecutive
bytes in memory in the order 1-2-3-4, where 1 is the most significant byte.
— 98 —
NIO, SOCKET, AND NETWORKING INTERVIEW QUESTIONS
IBM PowerPC processors would store the integer in the byte order 4-3-2-1.
Networking protocols such as TCP are based on a specific network byte order,
which uses big-endian byte ordering. If two machines are communicating with
each other and they have different byte ordering, they are converted to network
byte order before sending or after receiving.
Question 5
What is Nagle's algorithm?
If the interviewer is testing your knowledge of TCP/IP protocol, then it's very
rare for him not to ask this question. Nagle's algorithm is a way of improving
the performance of TCP/IP protocol and networks by reducing the number of
TCP packets that need to be sent over the network. It works by buffering small
packets until the buffer reaches Maximum Segment Size.
Small packets, which contain only 1 or 2 bytes of data, have more overhead in
terms of the TCP header, which is 40 bytes. These small packets can also lead
to congestion in a slow network. Nagle's algorithm tries to improve the
efficiency of TCP protocol by buffering them to send a larger packet.
Also, Nagle's algorithm has a negative effect on non-small writes, so if you are
writing large data on packets, then it's better to disable Nagle's algorithm.
— 99 —
GROKKING THE JAVA INTERVIEW
Here is also a nice diagram that explains the network traffic with and without
Nagle's algorithm:
Question 6
What is TCP_NODELAY?
Where a read after two successive writes on the socket may get delayed up to
500 milliseconds until the second write has reached the destination.
Question 7
What is multicasting or multicast transmission? Which Protocol is
generally used for multicast? TCP or UDP?
— 100 —
NIO, SOCKET, AND NETWORKING INTERVIEW QUESTIONS
Though UDP is not reliable, messages may be lost or delivered out of order.
Reliable multicast protocols such as Pragmatic General Multicast (PGM) have
been developed to add loss detection and retransmission on top of IP multicast.
Question 8
What is the difference between Topic and Queue in JMS?
The main difference between Topic and Queue in Java Messaging Service is
that Queue is used for point-to-point communication, which is generally one-
to-one, while the publisher is used for publish and subscribe communication
which is one-to-many.
You should use Topic to send messages when we have multiple consumers to
consumer messages. If we set up multiple listener threads to consume messages
from Queue, each message will be dispatched to only one thread and not all
threads. On the other hand, in the case of a Topic, each subscriber gets their
own copy of the message.
Question 9
What is the difference between IO and NIO in Java?
The main difference between NIO and IO is that NIO provides asynchronous,
non-blocking IO, which is critical to write faster and scalable networking
systems. In contrast, most of the utilities from IO classes are blocking and slow.
— 101 —
GROKKING THE JAVA INTERVIEW
The select() system call identifies if data is pending or not, then read()
or write() may be used, knowing that they will be complete immediately.
Question 10
How do you write a multi-threaded server in Java?
A multi-threaded server is one that can serve multiple clients without blocking.
Java provides excellent support to developers, such as servers. Prior to Java 1.4,
you could write a multi-threaded server using traditional socket IO and
threads.
This had a severe limitation on scalability because it creates a new thread for
each connection, and you can only create a fixed number of threads, depending
upon the machine's and platform's capability.
Though this design can be improved by using thread pools and worker threads,
it is still a resource-intensive design. After JDK 1.4 and NIO's introduction,
writing scalable and multi-threaded servers became a bit easier. You can easily
create it in a single thread by using Selector, which takes advantage of the
asynchronous and non-blocking IO model of Java NIO.
Question 11
What is the ephemeral port?
In TCP/IP, connection usually contains four things, Server IP, Server port,
Client IP, and Client Port. Out of these four, three are well-known most of the
time. What is not known is the client port; this is where ephemeral ports come
into the picture.
— 102 —
NIO, SOCKET, AND NETWORKING INTERVIEW QUESTIONS
Ephemeral ports are dynamic ports assigned by your machine's IP stack from
a specified range, known as the ephemeral port range when a client connection
explicitly doesn't specify a port number.
These are short-lived, temporary ports, which can be reused once the
connection is closed, but most IP software doesn't reuse ephemeral ports until
the whole range is exhausted. Similar to TCP, UDP protocol also uses an
ephemeral port while sending the datagram.
Question 12
What is the sliding window protocol?
Question 13
When do you get the "too many files open" error?
Just like File connection, Socket Connection also needs file descriptors. Since
every machine has a limited number of file descriptors, it's possible that they
may run out of file descriptors. When it happens, you will see a "too many files
open" error. You can check how many file descriptor per process is allowed on
— 103 —
GROKKING THE JAVA INTERVIEW
Question 14
What is the TIME_WAIT state in TCP protocol? When does a socket
connection go to the TIME_WAIT state?
When one end of the TCP Connection closes it by making a system call, it goes
into the TIME_WAIT state. Since TCP packets can arrive in the wrong order,
the port must not be closed immediately to allow late packets to arrive. That's
why that end of the TCP connection goes into the TIME_WAIT state.
Question 15
What will happen if you have too many socket connections in the
TIME_WAIT state on the Server?
When a socket connection or port goes into the TIME_WAIT state, it doesn't
release the file descriptor associated with it. The file descriptor is only released
when the TIME_WAIT state is gone, i.e., after some specified configured time.
If too many connections are in the TIME_WAIT state, then your Server may
run out of file descriptors and start throwing a "too many files open" error, and
stop accepting new connections.
That's all about in this list of networking and socket programming interview
questions and answers. Though I originally intended this list for Java
programmers, it is equally useful for any programmer.
— 104 —
NIO, SOCKET, AND NETWORKING INTERVIEW QUESTIONS
In fact, this is the bare minimum knowledge of sockets and protocols every
programmer should have. I have found that C and C++ programmers are better
at answering these questions than the average Java programmers.
One reason for this may be because Java programmers have got so many useful
libraries like Apache MINA, which does all the low-level work for them.
Anyway, knowledge of fundamentals is very important, and everything else is
just an excuse, but at some point, I also recommend using tried and tested
libraries like Apache MINA for production code.
— 105 —
CHAPTER 12:
W eb Services interview questions are part of J2EE interviews for jobs that
are looking for some experience in the Java web services Space. Most of
the Web services questions come from two different ways of implementing
Web Services like SOAP and REST. SOAP is a standard and mature way of
calling Web Services, which uses XML, while REST is a new way of
implementing Web Services, which is based on HTTP protocol. In fact, REST
Web Service interview questions are getting more and more popular in web
services interviews in Java, So if you are going for any Java J2EE interview
which requires some web service experience, be prepared with both SOAP and
REST Web services questions.
Following is a list of Java web services interview questions that I have prepared
for practice. Answers to these web services questions can be easily found in
many places on the Internet, and I will update this list whenever I have new
web services interview questions.
— 106 —
JAVA WEB SERVICE INTERVIEW QUESTIONS
Question 1
What is Web Service?
It's like a website where you send requests and receive responses, but unlike
traditional websites where you receive HTML responses, web services generally
respond with JSON or XML. In today’s world web services implements API,
client call them and server return response in JSON.
Question 2
What is SOAP?
It's a technology to implement web services. SOAP stands for Simple Object
Access Protocol which is a messaging protocol that allows distributed elements
of an application to communicate. SOAP can be carried over a variety of lower-
level protocols, including the web-related Hypertext Transfer Protocol
(HTTP).
Question 3
What is REST Web Service?
— 107 —
GROKKING THE JAVA INTERVIEW
Question 4
What is the difference between REST Web Service and SOAP web service?
The main differences between REST and SOAP web services are as follows:
3. Data format: REST web services use simple data formats such as JSON
or XML, while SOAP web services use a more complex data format that
can include type information, metadata, and error details.
4. Ease of use: REST web services are generally easier to use and
understand than SOAP web services because they use simple data
formats and rely on HTTP's built-in features.
5. Scalability: REST web services are more scalable than SOAP web
services because they are stateless and require less bandwidth.
Overall, REST web services are lightweight, simple, and flexible, while SOAP
web services are powerful, complex, and rigid. The choice of architecture
depends on the specific needs and requirements of the application. REST is also
an architectural-style protocol, unlike SOAP which is an XML-based protocol.
Also, SOAP is invoked using the RPC method, while REST web services can be
simply called using a URL path.
— 108 —
JAVA WEB SERVICE INTERVIEW QUESTIONS
Question 5
Can a Java client talk to C++ Server using Web Service?
Yes, the main advantage of web services is that the client and server can be
implemented on different technologies or programming languages. They can
also be independently development. Since they communicate over XML or
JSON, which is intended by any tech to transfer messages or data, you can
create a Java client to talk to a C++ server.
Question 5
What is WSDL?
WSDL stands for Web Service Description language, and it is used to describe
the services offered by any web service. In the case of SOAP-based web service,
you can find all the functions you can call in their WSDL document.
Question 7
What is UDDI?
Question 8
Is Web Service call synchronous or asynchronous?
It could be both, but generally, asynchronous web service calls are preferred
because the client doesn't need to wait for the response. It can asynchronously
process the response when it receives it and continues doing its work.
— 109 —
GROKKING THE JAVA INTERVIEW
Question 9
How do you handle errors in Web Service calls?
1. Try-Catch Block:
you can use try-catch block to handle exceptions thrown during the
web service call. This can be used to handle specific exceptions and
perform different actions based on the type of exception.
4. Logging:
You should log the error messages to help with debugging and
troubleshooting. This can be especially useful when errors occur in a
production environment.
5. Retrying:
You should retry the web service call if it fails due to a transient error.
This can be done by catching the exception and retrying the call a
certain number of times before giving up.
6. Circuit Breaker:
You can also use a circuit breaker pattern to detect when a web service
is not responding and prevent further requests from being sent until
the service is available again.
— 110 —
JAVA WEB SERVICE INTERVIEW QUESTIONS
Question 10
What is JAX-RPC?
JAX-RPC is a Java specification that defines the Java APIs for making XML-
based remote procedure calls (RPC). It's an essential library for calling SOAP
web services from Java applications.
Question 11
Have you worked on Spring and Web services?
You can answer this question based on your experience. Just be prepared if you
answer yes, then questions related to how to call a web service using spring may
be asked. If they are RESTful web srvices then you can use RestTemplate or
WebClient class to call them. Both these classes allows you to send GET, PUT,
POST, and DELTE request to any RESTful Web services over HTTP.
Question 12
What is WebServiceTemplate etc.?
Question 13
What is the difference between RMI and Web Services?
RMI (Remote Method Invocation) and Web Services are two different
technologies used for distributed computing in Java.
RMI is a Java API used for invoking methods remotely between two Java Virtual
Machines (JVMs) over the network. It allows Java objects to be invoked remotely
and is suitable for Java-to-Java communication within an organization.
— 111 —
GROKKING THE JAVA INTERVIEW
In summary, Web Services are a more flexible and interoperable solution for
distributed computing over the internet, while RMI is more suitable for Java-
to-Java communication within a closed system.
— 112 —
JAVA WEB SERVICE INTERVIEW QUESTIONS
Question 14
What is gRPC? What benefits it offers over other Web service Alternatives?
Compared to other web service alternatives like REST or SOAP, gRPC offers
several benefits, such as:
4. Code Generation: gRPC provides code generation for both clients and
servers, making it easier to build and maintain RPC services.
— 113 —
GROKKING THE JAVA INTERVIEW
Question 15
What is Microservice Architecture?
Question 16
What is the difference between REST and Microservice?
Question 17
What is the difference between the POST and PUT on REST Web Service?
In REST web service, POST is used to create a new entity, while PUT is used
to update the existing entity on the server. For example, you can create a new
book on a BookService using POST, but if you want to update any attribute of
the book, like Title, then you can use the PUT method. But this difference is by
convention only. If your server implements it in a different way, then POST
and PUT methods will behave accordingly.
— 114 —
JAVA WEB SERVICE INTERVIEW QUESTIONS
Question 18
What is the purpose of different HTTP methods in REST?
POST is mainly used to create data, GET is to retrieve data, PUT is to update
data, and DELETE is to remove data on the server.
Question 19
How do you test REST web services?
You can test REST Web Service using tools like Postman or just by using the
curl command in Linux. You can also call them by putting the URL into the
browser, and you can see the JSON or XML returned on the browser itself.
Question 20
What is the difference between REST and GraphQL?
While both REST and GraphQL are technology to post and get the data from
the server, one major difference is that GraphQL optimizes what REST does. It
provides a structure that allows you to query multiple data from different
endpoints together, which means you need to make fewer calls to the server.
For example, to get both User and Order data using REST will require two
queries, one to the user endpoint and the other to the Order endpoint, but with
GraphQL, you can get both these data in just one query.
That's all about some common Java Web Service Interview Questions, which
you can practice before interviews. I have tried to cover all kinds of web services
like SOAP, REST, GraphQL, and gRPC so that you have a broad idea about
different kinds of web services. You can go through these questions before your
Java interview to revise key concepts.
— 115 —
CHAPTER 13:
Y ou will always see some interview questions from Exception and Error
handling in core Java Interviews. Exception handling is an important
aspect of Java application development, and its key to writing robust, stable
Java programs, which makes it a natural favorite in interviews. Questions from
Error and Exception in Java are mostly based on the concept of Exception and
Error in Java, How to handle Exception, best practices to follow during
Exception handling, etc. Though multithreading, garbage collection, JVM
concepts, and questions from object-oriented design rules these interviews, you
should always expect and prepare some questions on effective error handling.
— 116 —
JAVA EXCEPTION AND ERROR INTERVIEW QUESTIONS
In this article, we will see some Java Error and Exception interview questions
asked to fresher, experienced, and senior Java developers in Java developer
interviews.
Question 1
What is an Exception in Java?
This is always the first interview question on Exception and is mostly asked in
fresher-level interviews. I haven't seen anybody asking about what exception is
in senior and experienced-level interviews, but this is quite popular at the entry
level. In simple words, Exception is Java’s way of conveying both system and
programming errors.
— 117 —
GROKKING THE JAVA INTERVIEW
Question 2
What is the difference between Checked and Unchecked Exceptions in Java?
Question 3
What is the similarity between NullPointerException and ArrayIndexOut
OfBoundException in Java?
This Java Exception interview question was not very popular but appeared in
various fresher-level interviews to see whether the candidate was familiar with
the concept of checked and unchecked exceptions or not. By the way answer to
this interview question is both of them are an example of unchecked exceptions
derived from RuntimeException. This question also opens the door for
the difference between arrays in Java and C programming language, as arrays
in C are unbounded and never throw ArrayIndexOutOfBoundException.
— 118 —
JAVA EXCEPTION AND ERROR INTERVIEW QUESTIONS
Question 4
What best practices do you follow while doing Exception handling in Java?
This Exception interview question in Java is very popular when hiring a senior
java developer or Technical Lead. Since exception handling is a crucial part of
project design and good knowledge of this is desirable. There are a lot of best
practices that can help to make your code robust and flexible at the same time.
Here are a few of them:
3. Prefer Unchecked exception over checked until you have a very good
reason not to do so. It improves the readability of code by removing
boilerplate exception-handling code
4. Never let your database Exception flow till client error. Since most of
the application deal with databases and SQLException is a checked
Exception in Java, you should consider handling any database-related
errors in the DAO layer of your application and only returning an
alternative value or something meaningful RuntimeException
that that which client can understand and take action.
— 119 —
GROKKING THE JAVA INTERVIEW
Question 5
Why do you think Checked Exception exists in Java since we can also convey
errors using RuntimeException?
Most of the checked exceptions are in the java.io package, which makes
sense because if you request any system resource and it's not available, then a
robust program must be able to handle that situation gracefully. By declaring
IOException as a checked Exception, Java ensures that you provide that
gracefully exception handling.
Another possible reason could be to ensure that system resources like file
descriptors, which are limited in numbers, should be released as soon as you
are done with that using catch or finally block. Effective Java book from Joshua
Bloch has a couple of items on this topic, which is again worth reading.
Question 6
What is the difference between the throw and throws keywords in Java?
One more Java Exception interview question from beginner’s kitty. throw and
throws keyword may look quite similar, especially if you are new to Java
programming and haven't seen much of it. Though they are similar in terms of
both being used in Exception handling, they are different in how and where
they are used in code. The throws keyword is used in the method signature
to declare which checked exception method can throw. You can also declare
unchecked exceptions, but that is not mandatory by the compiler.
— 120 —
JAVA EXCEPTION AND ERROR INTERVIEW QUESTIONS
This signifies a lot of things, like the method is not going to handle an
Exception; instead, it's throwing it. If the method throws a checked Exception,
then the caller should provide compile-time exception handling, etc.
On the other hand, the throw keyword is actually used to throw any
Exception. Syntactically you can throw any Throwable (i.e., Throwable or
any class derived from Throwable); the throw keyword transfers control
of execution to the caller so it can be used in place of the return keyword. The
most common example of using throw in place of return is throwing
UnSupportedOperationException from an empty method, as shown
below :
Question 7
What is Exception chaining in Java?
Question 8
Have you written your own custom Exception in Java? How do you do that?
— 121 —
GROKKING THE JAVA INTERVIEW
Exception interview question is to find out how you use this feature. This can
be used for sophisticated and precise exception handling with tweaks involved
in whether you would choose a checked or unchecked exception.
By creating a specific exception for the specific case, you also give a lot of
options to the caller to deal with them elegantly. I always prefer to have a precise
exception than a general exception. Though creating lots of specific exceptions
increases the number of classes in your project quickly, maintaining a practical
balance between specific and general exceptions is key to success.
Question 9
What changes have been introduced in JDK7 related to Exception handling
in Java?
JDK7 has introduced two major features which are related to Error and
Exception handling. One is the ability to handle multiple exceptions in one
catch block, popularly known as multi-cache block, and the other is ARM
blocks in Java 7 for automatic resource management, also known as to try with
the resource.
Both of these features can certainly help to reduce boilerplate code required for
handling checked exceptions in Java and significantly improve the readability
of code. Knowledge of this feature not only helps to write better errors and
exception code in Java but also helps to do well during interviews. I also
recommend reading Java 7 Recipes book to get more insight into useful features
introduced in Java 7, including these two.
Question 10
Have you faced OutOfMemoryError in Java? How did you solve that?
— 122 —
JAVA EXCEPTION AND ERROR INTERVIEW QUESTIONS
matter which kind of project you are working on, so if you say no, it doesn't go
very well with the interviewer. I suggest even if you are not familiar with facing
it in reality but have 3 to 4 years of experience in Java, be prepared for it.
At the same time, this is also a chance to impress the interviewer by showing
your advanced technical knowledge related to finding memory leaks, profiling,
and debugging.
Question 11
Does code form finally execute if the method returns before finally blocking
or JVM exits?
This Java exception interview question can also be asked in code format, where
given a code with System.exit() in the try block and something in the
finally block. It’s worth knowing that, finally block in Java executes even when
the return keyword is used in the try block. The only time they don’t execute is
when you call JVM to exit by executing System.exit(0)from try block in
Java.
Question 12
What is the difference between the final, finalize, and finally keywords in
Java?
Another classic interview question in core Java was asked by one of my friends
on his telephone interview for a core Java developer with Morgan Stanley.
final and finally are keywords, while finalize is a method. The final
keyword is very useful for creating an ad Immutable class in Java. By making a
class final, we prevent it from being extended. Similarly, by making a method
final, we prevent it from being overridden. On the other hand, finalize()
method is called by the garbage collector before that object is collected, but this
is not guaranteed by Java specification. finally keyword is the only one
— 123 —
GROKKING THE JAVA INTERVIEW
which is related to error and exception handling, and you should always have
finally block in the production code for closing connections and resources.
Question 13
What is wrong with the following code :
This code will throw a compiler error on the line where the
RuntimeException variable “re” is written on the catch block. Since
Exception is a superclass of RuntimeException, all
RuntimeException thrown by the start() method will be captured by
the first catch block, and code will never reach the second catch block, and
that's the reason the compiler will flag error as “exception
java.lang.RuntimeException has already been caught".
Question 14
What is wrong with the following code in Java:
— 124 —
JAVA EXCEPTION AND ERROR INTERVIEW QUESTIONS
In this code, the compiler will complain about the subclass where the
start() method gets overridden. As per the rules of method overriding in
Java, an overridden method can not throw a Checked Exception, which is
higher in the hierarchy than the original method. Since here start() is
throwing IOException in the superclass, start() in the subclass can only
throw either IOException or any subclass of IOException but not the
superclass of IOException, e.g., Exception.
Question 15
What is wrong with the following Java Exception code:
— 125 —
GROKKING THE JAVA INTERVIEW
In this Java Exception example code, the compiler will complain about the line
where we are handling IOException; since IOException is a checked
Exception and the start() method doesn't throw IOException, the
compiler will flag the error as "exception java.io.IOException is
never thrown in body of corresponding try statement,"
but if you change IOException to Exception compiler error will disappear
because Exception can be used to catch all RuntimeException which
doesn't require a declaration in a throws clause.
I like this little tricky Java Exception interview question because it's not easy to
figure out the result by chaining IOException to Exception. You can also
check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions
based on Java Errors and Exceptions.
These are some of the Java Error and Exception interview questions I have
mostly seen in both fresher and experienced levels of Java interviews. There are
a lot more questions on Exception that I haven't included, and if you think you
have a good question missed out, then let me know, and I will make an effort
to include it on this list of java exceptions questions and answers.
One last question about Java Exception I am leaving for you guys is "Why is
Java Exception considered to be a better alternative for returning error codes"?
Ponder this question as its thought-provoking
— 126 —
CHAPTER 14:
Tricky Java
interview questions
W hat is a tricky question? Well, tricky Java interview questions are those
questions that have some surprise element to them. If you try to answer
a tricky question with common sense, you will most likely fail because they
require some specific knowledge. Most of the tricky Java questions come from
confusing concepts like method overloading and overriding, Multi-threading,
which is really tricky to master character encoding, checked vs. unchecked
exceptions, and subtle Java programming details like Integer overflow. The
most important thing to answer a tricky Java question is attitude and analytical
thinking, which helps even if you don't know the answer.
Anyway, in this Java article, we will see 10 Java questions that are really tricky
and requires more than average knowledge of Java programming language to
answer correctly. As per my experience, there are always one or two tricky or
tough Java interview questions on any core Java or Java EE interviews, so it's
good to prepare tricky questions from Java in advance.
If I take an interview, I purposefully put this kind of question to gauge the depth
of the candidate's understanding of Java. Another advantage of asking such a
— 127 —
GROKKING THE JAVA INTERVIEW
question is the surprising element, which is a key factor in putting the candidate
under some pressure during interviews.
Since these questions are less common, there is a good chance that many Java
developer doesn't know about them. You won't find these questions even on
popular Java interview courses like the Java Interview Guide: 200+ Interview
Questions and Answers, which is nevertheless an excellent guide for Java
interviews.
Question 1
Question: What does the following Java program print?
— 128 —
TRICKY JAVA INTERVIEW QUESTIONS
So unlike the obvious answer, this program will print 0.0 because of
Double.MIN_VALUE is greater than 0. I have asked this question to a Java
developer having experience of up to 3 to 5 years, and surprisingly almost 70%
of candidates got it wrong.
Question 2
What will happen if you put the return statement or System.exit () on the
try or catch block? Will finally block execute?
This is a very popular tricky Java question, and it's tricky because many
programmers think that no matter what, the finally block will always execute.
This question challenges that concept by putting a return statement in the try
or catch block or calling System.exit() from the try or catch block.
The answer to this tricky question in Java is that finally, the block will execute
even if you put a return statement in the try block or catch block, but finally
block won't run if you call System.exit() from the try or catch block.
Question 3
Can you override a private or static method in Java?
Similarly, you cannot override a private method in the subclass because it's not
accessible there. What you do is create another private method with the same
name in the child class.
— 129 —
GROKKING THE JAVA INTERVIEW
Question 4
What will the expression 1.0 / 0.0 return? Will it throw an Exception? Any
compile-time error?
This is another tricky question from the Double class. Though Java developers
know about the double primitive type and Double class, while doing floating-
point arithmetic, they don't pay enough attention to Double.INFINITY,
NaN, and -0.0 and other rules that govern the arithmetic calculations
involving them.
Question 5
Does Java support multiple inheritances?
This is the trickiest question in Java; if C++ can support direct multiple
inheritances, then why not Java? This is the argument Interviewer often gives.
The answer to this question is much more subtle than it looks because Java does
support multiple inheritances of Type by allowing an interface to extend other
interfaces. What Java doesn't support is multiple inheritances of
implementation.
This distinction also gets blurred because of the default method of Java 8, which
now provides Java multiple inheritances of behavior as well.
— 130 —
TRICKY JAVA INTERVIEW QUESTIONS
Question 6
What will happen if we put a key object in a HashMap which is already there?
This tricky Java question is part of another frequently asked question, How
HashMap works in Java. HashMap is also a popular topic for creating
confusing and tricky questions in Java.
The answer to this question is if you put the same key again, then it will replace
the old mapping because HashMap doesn't allow duplicate keys. The Same key
will result in the same hashcode and will end up at the same position in the
bucket.
Each bucket contains a linked list of Map.Entry object, which contains both
Key and Value. Now Java will take the Key object from each entry and compare
it with this new key using the equals() method. If that returns true, then the
value object in that entry will be replaced by the new value.
Question 7
What does the following Java program print?
The trickiness of this question lies in character encoding and how String to byte
array conversion works. In this program, we are first creating a String from a
character array, which just has one character '\u0097'. After that, we get the
byte array from that String and print that byte.
— 131 —
GROKKING THE JAVA INTERVIEW
Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable
to guess that the str.getBytes() call will return a byte array that contains
one element with a value of -105 ((byte) 0x97).
However, that's not what the program prints, and that's why this question is
tricky. As a matter of fact, the output of the program is operating system and
locale-dependent on a Windows XP with the US locale, the above program
prints [63]. If you run this program on Linux or Solaris, you will get different
values.
To answer this question correctly, you need to know about how Unicode
characters are represented in Java char values and in Java strings and what role
character encoding plays in String.getBytes().
In simple words, to convert a string to a byte array, Java iterates through all the
characters that the string represents and turns each one into a number of bytes,
and finally puts the bytes together. The rule that maps each Unicode character
into a byte array is called character encoding.
So It's possible that if the same character encoding is not used during both
encoding and decoding, then the retrieved value may not be correct. When we
call str.getBytes() without specifying a character encoding scheme, the
JVM uses the default character encoding of the platform to do the job.
No matter which character encoding scheme is used, Java will always translate
Unicode characters not recognized by the encoding to 63, which represents the
character U+003F (the question mark, ?) in all encodings.
— 132 —
TRICKY JAVA INTERVIEW QUESTIONS
Question 8
If a method throws NullPointerException in the superclass, can we override
it with a method that throws RuntimeException?
One more tricky Java question from the overloading and overriding concept.
The answer is you can very well throw a superclass of RuntimeException in
overridden method, but you can not do the same if it's a checked Exception.
Question 9
What is the issue with the following implementation of the compareTo()
method in Java, where an id is an integer number?
Well, there is nothing wrong with this Java question until you guarantee that
the id is always positive. This Java question becomes tricky when you can't
guarantee that the id is positive or negative. The tricky part is If the id becomes
negative, then subtraction may overflow and produce an incorrect result.
Question 10
How do you ensure that the N thread can access N resources without
deadlock?
If you are not well versed in writing multi-threading code, then this is a really
tricky question for you. This Java question can be tricky even for experienced
and senior programmers, who are not really exposed to deadlock and race
conditions.
The key point here is ordering. If you acquire resources in a particular order
and release resources in the reverse order, you can prevent deadlock.
— 133 —
GROKKING THE JAVA INTERVIEW
Question 11
Consider the following Java code snippet, which is initializing two variables,
and both are not volatile, and two threads T1 and T2, are modifying these
values as follows; both are not synchronized
int x = 0;
boolean bExit = false;
It's impossible for a list of tricky Java questions not to contain anything from
multi-threading. This is the simplest one I can get. The answer to this question
is Yes, and It's possible that thread T2 may print x=0. Why? Because without
any instruction to the compiler, e.g., synchronized or volatile, bExit=true
might come before x=1 in compiler reordering. Also, x=1 might not become
visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it?
But the best answer is you just need to make bExit as volatile, and then
Thread 2 can only print “x=1”. x does not need to be volatile because x cannot
be reordered to come after bExit=true when bExit is volatile.
— 134 —
TRICKY JAVA INTERVIEW QUESTIONS
Question 12
What is the difference between CyclicBarrier and CountDownLatch in Java?
Relatively newer Java tricky question, only been introduced from Java 5. The
main difference between both is that you can reuse CyclicBarrier even if the
Barrier is broken, but you cannot reuse CountDownLatch in Java.
CyclicBarrier is used when a group of threads need to wait for each other to
reach a certain point of execution before proceeding further. It works by
allowing a fixed number of threads to wait for each other at a barrier point until
all of them reach there. Once all threads have arrived, the barrier is released,
and the threads can continue their execution. CyclicBarrier can be reset and
reused, making it suitable for recurring synchronization tasks.
On the other hand, CountDownLatch is used when one or more threads need
to wait for a specific number of events to occur before proceeding further. It
works by initializing a latch with a count, and the threads wait until the count
reaches zero. Each time an event occurs, the count is decremented until it
reaches zero, and the threads can continue their execution. Unlike
CyclicBarrier, CountDownLatch cannot be reset and reused once it has been
counted down to zero.
Question 13
What is the difference between StringBuffer and StringBuilder in Java?
Classic Java questions which some people think are tricky and some consider
very easy. StringBuilder in Java was introduced in JDK 1.5, and the only
difference between both is that StringBuffer methods like length(), capacity(),
— 135 —
GROKKING THE JAVA INTERVIEW
Question 14
Can you access a non-static variable in the static context?
Another tricky Java question from Java fundamentals. No, you cannot access a
non-static variable from the static context in Java. If you try, it will give a
compile-time error. This is actually a common problem for beginners in Java
to face when they try to access instance variables inside the main method.
Because the main is static in Java, and instance variables are non-static, you can
not access the instance variable inside the main.
Question 15
How many String objects are created by the following code?
You might be thinking of "one" object, but that's wrong. Btw, if you don't find
these questions tricky enough, then you should check Joshua Bloch's other
classic book, Java Puzzlers, for super tricky questions. I am sure you will find
them challenging enough.
— 136 —
TRICKY JAVA INTERVIEW QUESTIONS
However, there are certain scenarios in Java where Singleton does not remain
Singleton. One such scenario is when multiple classloaders are involved. Each
classloader creates its own instance of the Singleton class, resulting in multiple
instances of the Singleton class in the memory.
Yes, it is possible to load a class with two ClassLoaders in Java. This is known
as ClassLoader hierarchy or ClassLoader delegation model. When a class is
loaded by a ClassLoader, it delegates the class loading to its parent ClassLoader.
If the parent ClassLoader is unable to load the class, then the child ClassLoader
loads the class.
— 137 —
GROKKING THE JAVA INTERVIEW
However, loading a class with multiple ClassLoaders can lead to issues such as
ClassCastException and linkage errors. It is important to understand the
ClassLoader hierarchy and ensure that the correct ClassLoader is used to load
a class.
Yes, it is possible for equals() to return false, even if the contents of two Objects
are the same. This can happen if the equals() method is not properly implemented
in the class of the objects being compared. By default, the equals() method checks
for object equality, which means that it returns true only if the two object
references are pointing to the same object in memory. However, if the equals()
method is overridden to compare the contents of the objects, it is important to
make sure that it follows the contract for equals(), which includes being reflexive,
symmetric, transitive, and consistent. If any of these conditions are not met,
equals() may return false even if the contents of the objects are the same.
The compareTo() and equals() methods are both used to compare objects in
Java. While the equals() method checks whether two objects are equal or not,
the compareTo() method compares two objects and returns an integer value to
indicate their order.
— 138 —
TRICKY JAVA INTERVIEW QUESTIONS
If the compareTo() method is not consistent with the equals() method, then it
can lead to unexpected behavior in collections such as SortedSet and
SortedMap. These collections rely on the ordering of objects returned by the
compareTo() method. If the ordering is inconsistent with the equals() method,
then it can lead to duplicate objects in the collection or objects being removed
unexpectedly.
For example, consider a Person class that has name and age fields. If the
compareTo() method only compares the name field, but the equals() method
compares both the name and age fields, then adding a Person object to a
SortedSet can lead to unexpected behavior.
5. When do Double and BigDecimal give different answers for equals() and
compareTo() == 0?
Double and BigDecimal can give different answers for equals() and
compareTo() == 0 when dealing with decimal values that cannot be
represented exactly in binary format. For example, the value of 0.1 cannot be
represented exactly in binary format, and so there is a possibility of loss of
precision when performing arithmetic operations on it.
In the case of Double, the value is stored in binary format using a fixed number
of bits. This can result in rounding errors and inaccuracies when performing
arithmetic operations. When comparing two Double values using equals() or
compareTo() == 0, these inaccuracies can result in a false comparison.
— 139 —
GROKKING THE JAVA INTERVIEW
In Java, "happens before" is a concept in the Java Memory Model (JMM) that
defines the order of execution of instructions and their effects on memory. The
"happens before" relationship ensures that memory writes made by one thread
are visible to other threads in the correct order.
In the JMM, "happens before" is defined by a set of rules. These rules include:
Program order rule: Each action in a thread happens before every action in that
thread that comes later in the program order.
Thread start rule: The start of a thread happens before any action in the started
thread.
Thread join rule: All actions in a thread happen before any other thread
successfully returns from a join on that thread.
— 140 —
TRICKY JAVA INTERVIEW QUESTIONS
In Java, the double data type represents decimal values as binary fractions.
However, not all decimal values can be represented precisely in binary. This
can lead to rounding errors when performing calculations involving decimal
values.
In the case of 0.1 * 3, the decimal value 0.1 cannot be represented precisely in
binary, and so it is rounded to the nearest representable binary fraction. This
rounded value is then multiplied by 3, leading to a small rounding error in the
result.
When this result is compared to the exact decimal value 0.3, the comparison
returns false due to the small rounding error in the calculated value. This is why
0.1 * 3 != 0.3 in Java.
In Java, for integer values between -128 and 127, the JVM caches these values
and returns the same object reference when autoboxing is used. This means
that two Integer objects containing the same value will be equal only if their
values are within this range.
So, when we compare two Integer objects that have values between -128 and
127, they will return true for both == and equals() methods. However, for
values outside of this range, the == operator will return false even if the values
are the same, because the objects are different.
— 141 —
GROKKING THE JAVA INTERVIEW
In Java, notify() and notifyAll() are methods used to wake up threads that are
waiting for a particular monitor. The main difference between these two
methods is in the number of threads that they wake up.
When notify() is called, it wakes up only one thread that is waiting for the
monitor. The thread that is woken up is not specified and is chosen by the Java
Virtual Machine.
On the other hand, when notifyAll() is called, it wakes up all the threads that
are waiting for the monitor. This ensures that all threads that are waiting for
the monitor are notified and can resume execution.
— 142 —
TRICKY JAVA INTERVIEW QUESTIONS
can be used in situations where waking up only one thread is sufficient and can
lead to better performance
The System.exit() method in Java terminates the currently running JVM, while
the System.halt() method immediately terminates the JVM without running
any shutdown hooks. The exit() method can be used to initiate a graceful
shutdown of the JVM, allowing the running threads to complete their
execution before terminating. On the other hand, the halt() method is used to
terminate the JVM abruptly, without giving the running threads a chance to
clean up their resources.
— 143 —
GROKKING THE JAVA INTERVIEW
And
The first two methods are an example of method overloading in Java because
they have the same method name but different parameter types. The third
method, however, is not valid Java syntax because it has a return type of void
but also attempts to return a value. It should be modified to public void
getDescription(String obj) { System.out.println(obj); } to properly print the
input String.
This was my list of Some of the most common tricky questions in Java. It's not
a bad idea to prepare a tricky Java question before appearing for any core Java
interview. One or two open-ended or tricky questions are quite common in
Java interviews.
— 144 —
CHAPTER 15:
W hen the experience of a Java Programmer grows in the years, e.g., when
it goes from beginner years ( 2 to 4) to more experience or sort of senior
level ( 5 to 7 years), Core Java Interview Questions also change a bit. Of course,
basics like data structure, algorithms, and object-oriented programming
remain the same, but the types of questions will become more advanced, and
their answers will definitely need to be more detailed and accurate. I often
receive queries about core Java questions asked by a senior developer with 5 to
6-year experience, or, sometimes, I am going for an interview with a senior Java
developer what kind of questions I should expect.
This sometimes puzzles me that once you become a senior, you automatically
start taking part in the interview, and you should have an idea of what to expect
in Interviews, but at the same time, I can understand that having an idea of
questions before going on Interview, helps preparation.
Of course, you are not going to get a question like the one you have faced on 2
to 3 years level Java Interviews, but It also depends on different rounds of
Interviews.
— 145 —
GROKKING THE JAVA INTERVIEW
I have not seen many changes in the questions asked on the telephone round,
which almost remains the same. You will find some fact-based, some coding
questions, and a few tricky questions. On the other hand, face-to-face interviews
have become more detailed and more tricky, especially with nasty follow-ups.
It also covers knowledge of other JVM languages like Scala and Groovy and other
platforms like Android. A perfect companion to do well in Java interviews.
Question 1
What is Busy Spinning? Why Should You Use It in Java?
— 146 —
TECHNICAL CORE JAVA INTERVIEW QUESTIONS
By not releasing the CPU or suspending the thread, your thread retains all the
cached data and instructions, which may be lost if the thread was suspended
and resumed back in a different core of the CPU.
Question 2
What is Read-Write Lock? Does ConcurrentHashMap in Java Use the
ReadWrite Lock?
This core Java question is also very popular in senior and more experienced
level Java interviews, e.g., 4 to 6 years, where you expect the Interviewer to go
into more detail, like by asking you to provide an implementation of the read-
write lock with different policies.
— 147 —
GROKKING THE JAVA INTERVIEW
Question 3
How to Make an Object Immutable in Java? Why Should You Make an
Object Immutable?
Question 4
Which Design Patterns have You Used in Your Java Project?
Always expect some design patterns-related questions for the Core Java
Interview for the senior developer position. It's a better strategy to mention any
GOF design pattern rather than Singleton or MVC, which almost every Java
developer uses.
It's common that once you mention a particular design pattern, say Factory or
Abstract Factory, Interviewer's next question would be, have you used this
pattern in your project? So be ready with proper examples and explain why you
choose a particular pattern.
Question 5
Do you know about Open Closed Design Principle or Liskov Substitution
Principle?
— 148 —
TECHNICAL CORE JAVA INTERVIEW QUESTIONS
a basic idea of, these principles and how they help you write better object-
oriented code. I
Suppose you don't know the answer to this question. In that case, you can
politely say No, as it's not expected from you to know the answer to every
question, but by answering this question, you can make your claim stronger, as
many experienced developers fail to answer basic questions like this.
Question 6
Which Design Pattern Will You Use to Shield Your Code From a Third
Party library? Which Another Will Likely replace in a Couple of Months?
You can expect more real-world design problems in different formats, some
with more detailed explanations with the context or some with only intent
around.
One way to shield your code from a third-party library is to code against an
interface rather than implementation and then use dependency injection to
provide a particular implementation. This kind of question is also asked quite
frequently by experienced and senior Java developers with 5 to 7 years of
experience.
Question 7
How do you prevent SQL Injection in Java Code?
This question is asked more by J2EE and Java EE developers than core Java
developers, but it is still a good question to check the JDBC and Security skill
of experienced Java programmers.
— 149 —
GROKKING THE JAVA INTERVIEW
You can use PreparedStatement to avoid SQL injection in Java code. Use of the
PreparedStatement for executing SQL queries not only provides better
performance but also shields your Java and J2EE application from SQL
Injection attacks.
On a similar note, If you are working more on Java EE or J2EE side, then you
should also be familiar with other security issues, including Session Fixation
attacks or Cross-Site Scripting attacks, and how to resolve them. These are some
fields and questions where a good answer can make a lot of difference in your
selection.
Question 8
Tell me about different Reference types available in Java, e.g.,
WeakReference, SoftReference, or PhantomReference? and Why should you
use them?
Question 9
How does the get method of HashMap work in Java?
Yes, this is still one of the most popular core Java questions for senior developer
interviews. You can also expect this question on a telephonic round, followed
by lots of follow-up questions.
— 150 —
TECHNICAL CORE JAVA INTERVIEW QUESTIONS
The short answer to this question is that HashMap is based upon hash table
data structure and uses the hashCode() method to calculate hash code to
find the bucket location on the underlying array and the equals() method
to search the object in the same bucket in case of a collision.
Question 10
Which Two Methods HashMap key Object Should Implement?
This is one of the follow-up questions I was talking about in the previous
questions. Since the working of HashMap is based upon hash table data
structure, any object which you want to use as a key for HashMap or any other
hash-based collection, e.g., Hashtable or ConcurrentHashMap must
implement equals() and hashCode() method.
The hashCode() is used to find the bucket location, i.e., the index of the
underlying array, and the equals() method is used to find the right object
in a linked list stored in the bucket in case of a collision.
By the way, from Java 8, HashMap also started using a tree data structure to
store the object in case of a collision to reduce the worst-case performance of
HashMap from O(n) to O(logN).
Question 11
Why Should an Object Used As the Key should be Immutable?
This is another follow-up to the previous core Java interview questions. It's
good to test the depth of technical knowledge of candidates by asking more and
more questions on the same topic. If you know about Immutability, you can
answer this question by yourself.
— 151 —
GROKKING THE JAVA INTERVIEW
Since the hash code returned by the hashCode(,) method depends on the
content of the object, i.e., values of member variables. If an object is mutable,
then those values can change, and so is the hash code. If the same object returns
a different hash code once you insert the value in HashMap, you will end up
searching in different bucket locations and will not be able to retrieve the
object.
That's why the key objective should be immutable. It's not a rule enforced by
the compiler, but you should take care of it as an experienced programmer.
Question 12
How does ConcurrentHashMap achieve its Scalability?
Question 13
How do you share an object between threads? Or How to pass an object from
one thread to another?
There are multiple ways to do that, like Queues, Exchanger, etc., but
BlockingQueue using the Producer-Consumer pattern is the easiest way to
pass an object from one thread to another.
— 152 —
TECHNICAL CORE JAVA INTERVIEW QUESTIONS
Question 14
How do you find out if your program has a deadlock?
By taking thread dump using kill -3, using JConsole or VisualVM), I suggest
preparing this core java interview question in more detail, as the Interviewer
definitely likes to go with more detail, e.g., they will press with questions like,
have you really done that in your project or not?
Question 15
How do you avoid deadlock while coding?
That's all on this list of Core Java Interview Questions for senior developers and
experienced programmers. You can go through all these chapters and quickly
revise all Java concept based questions before your interview.
— 153 —
Conclusion
I n this book, we have covered some of the most common and important
technical core Java interview questions that you are likely to encounter. We
started with the basics of object-oriented programming and Java syntax, then
moved on to more advanced topics such as class loaders, enums, strings, and
collections.
— 154 —
— 155 —