1000 Java Interview Questions-1
1000 Java Interview Questions-1
Java
Interview Question & Answers
Knowledge Powerhouse
No part of this book can be copied in any form. The publisher and the author have used good
faith efforts to ensure that the information in this book is correct and accurate. The
publisher and the author disclaim all responsibility for errors or omissions. Use of the
information in this book is at your own risk.
www.KnowledgePowerhouse.com
DEDICATION
To our readers!
CONTENTS
Java Basics
1. What is the difference between JDK and JRE?
2. What is Java Virtual Machine (JVM)?
3. What are the different types of memory areas allocated by JVM?
4. What is JIT compiler?
5. How Java platform is different from other platforms?
6. Why people say that Java is 'write once and run anywhere' language?
7. How does ClassLoader work in Java?
8. Do you think ‘main’ used for main method is a keyword in Java?
9. Can we write main method as public void static instead of public static
void?
10. In Java, if we do not specify any value for local variables, then what
will be the default value of the local variables?
11. Let say, we run a java class without passing any arguments. What will
be the value of String array of arguments in Main method?
12. What is the difference between byte and char data types in Java?
OOPS
13. What are the main principles of Object Oriented Programming?
14. What is the difference between Object Oriented Programming
language and Object Based Programming language?
15. In Java what is the default value of an object reference defined as an
instance variable in an Object?
16. Why do we need constructor in Java?
17. Why do we need default constructor in Java classes?
18. What is the value returned by Constructor in Java?
19. Can we inherit a Constructor?
20. Why constructors cannot be final, static, or abstract in Java?
Inheritance
21. What is the purpose of ‘this’ keyword in java?
22. Explain the concept of Inheritance?
23. Which class in Java is superclass of every other class?
24. Why Java does not support multiple inheritance?
25. In OOPS, what is meant by composition?
26. How aggregation and composition are different concepts?
27. Why there are no pointers in Java?
28. If there are no pointers in Java, then why do we get
NullPointerException?
29. What is the purpose of ‘super’ keyword in java?
30. Is it possible to use this() and super() both in same constructor?
31. What is the meaning of object cloning in Java?
Static
32. In Java, why do we use static variable?
33. Why it is not a good practice to create static variables in Java?
34. What is the purpose of static method in Java?
35. Why do we mark main method as static in Java?
36. In what scenario do we use a static block?
37. Is it possible to execute a program without defining a main() method?
38. What happens when static modifier is not mentioned in the signature
of main method?
39. What is the difference between static method and instance method in
Java?
Method Overloading and Overriding
40. What is the other name of Method Overloading?
41. How will you implement method overloading in Java?
42. What kinds of argument variations are allowed in Method
Overloading?
43. Why it is not possible to do method overloading by changing return
type of method in java?
44. Is it allowed to overload main() method in Java?
45. How do we implement method overriding in Java?
46. Are we allowed to override a static method in Java?
47. Why Java does not allow overriding a static method?
48. Is it allowed to override an overloaded method?
49. What is the difference between method overloading and method
overriding in Java?
50. Does Java allow virtual functions?
51. What is meant by covariant return type in Java?
Polymorphism
52. What is Runtime Polymorphism?
53. Is it possible to achieve Runtime Polymorphism by data members in
Java?
54. Explain the difference between static and dynamic binding?
Abstraction
55. What is Abstraction in Object Oriented programming?
56. How is Abstraction different from Encapsulation?
57. What is an abstract class in Java?
58. Is it allowed to mark a method abstract method without marking the
class abstract?
59. Is it allowed to mark a method abstract as well as final?
60. Can we instantiate an abstract class in Java?
61. What is an interface in Java?
62. Is it allowed to mark an interface method as static?
63. Why an Interface cannot be marked as final in Java?
64. What is a marker interface?
65. What can we use instead of Marker interface?
66. How Annotations are better than Marker Interfaces?
67. What is the difference between abstract class and interface in Java?
68. Does Java allow us to use private and protected modifiers for
variables in interfaces?
69. How can we cast to an object reference to an interface reference?
Final
70. How can you change the value of a final variable in Java?
71. Can a class be marked final in Java?
72. How can we create a final method in Java?
73. How can we prohibit inheritance in Java?
74. Why Integer class in final in Java?
75. What is a blank final variable in Java?
76. How can we initialize a blank final variable?
77. Is it allowed to declare main method as final?
Package
78. What is the purpose of package in Java?
79. What is java.lang package?
80. Which is the most important class in Java?
81. Is it mandatory to import java.lang package every time?
82. Can you import same package or class twice in your class?
83. What is a static import in Java?
84. What is the difference between import static com.test.Fooclass and
import com.test.Fooclass?
Internationalization
85. What is Locale in Java?
86. How will you use a specific Locale in Java?
Serialization
87. What is the serialization?
88. What is the purpose of serialization?
89. What is Deserialization?
90. What is Serialization and Deserialization conceptually?
91. Why do we mark a data member transient?
92. Is it allowed to mark a method as transient?
93. How does marking a field as transient makes it possible to serialize an
object?
94. What is Externalizable interface in Java?
95. What is the difference between Serializable and Externalizable
interface?
Reflection
96. What is Reflection in Java?
97. What are the uses of Reflection in Java?
98. How can we access private method of a class from outside the class?
99. How can we create an Object dynamically at Runtime in Java?
Garbage Collection
100.What is Garbage Collection in Java?
101. Why Java provides Garbage Collector?
102.What is the purpose of gc() in Java?
103.How does Garbage Collection work in Java?
104.When does an object become eligible for Garbage Collection in Java?
105.Why do we use finalize() method in Java?
106.What are the different types of References in Java?
107.How can we reference an unreferenced object again?
108.What kind of process is the Garbage collector thread?
109.What is the purpose of the Runtime class?
110. How can we invoke an external process in Java?
111. What are the uses of Runtime class?
Inner Classes
112. What is a Nested class?
113. How many types of Nested classes are in Java?
114. Why do we use Nested Classes?
115. What is the difference between a Nested class and an Inner class in
Java?
116. What is a Nested interface?
117. How can we access the non-final local variable, inside a Local Inner
class?
118. Can an Interface be defined in a Class?
119. Do we have to explicitly mark a Nested Interface public static?
120.Why do we use Static Nested interface in Java?
String
121. What is the meaning of Immutable in the context of String class in
Java?
122.Why a String object is considered immutable in java?
123.How many objects does following code create?
124.How many ways are there in Java to create a String object?
125.How many objects does following code create?
126.What is String interning?
127.Why Java uses String literal concept?
128.What is the basic difference between a String and StringBuffer
object?
129.How will you create an immutable class in Java?
130.What is the use of toString() method in java ?
131. Arrange the three classes String, StringBuffer and StringBuilder in
the order of efficiency for String processing operations?
Exception Handling
132.What is Exception Handling in Java?
133.In Java, what are the differences between a Checked and
Unchecked?
134.What is the base class for Error and Exception classes in Java?
135.What is a finally block in Java?
136.What is the use of finally block in Java?
137.Can we create a finally block without creating a catch block?
138.Do we have to always put a catch block after a try block?
139.In what scenarios, a finally block will not be executed?
140.Can we re-throw an Exception in Java?
141. What is the difference between throw and throws in Java?
142.What is the concept of Exception Propagation?
143.When we override a method in a Child class, can we throw an
additional Exception that is not thrown by the Parent class method?
Multi-threading
144.How Multi-threading works in Java?
145.What are the advantages of Multithreading?
146.What are the disadvantages of Multithreading?
147.What is a Thread in Java?
148.What is a Thread’s priority and how it is used in scheduling?
149.What are the differences between Pre-emptive Scheduling Scheduler
and Time Slicing Scheduler?
150.Is it possible to call run() method instead of start() on a thread in
Java?
151. How will you make a user thread into daemon thread if it has already
started?
152.Can we start a thread two times in Java?
153.In what scenarios can we interrupt a thread?
154.In Java, is it possible to lock an object for exclusive use by a thread?
155.How notify() method is different from notifyAll() method?
Collections
156.What are the differences between the two data structures: a Vector
and an ArrayList?
157.What are the differences between Collection and Collections in Java?
158.In which scenario, LinkedList is better than ArrayList in Java?
159.What are the differences between a List and Set collection in Java?
160.What are the differences between a HashSet and TreeSet collection
in Java?
161. In Java, how will you decide when to use a List, Set or a Map
collection?
162.What are the differences between a HashMap and a Hashtable in
Java?
163.What are the differences between a HashMap and a TreeMap?
164.What are the differences between Comparable and Comparator?
165.In Java, what is the purpose of Properties file?
166.What is the reason for overriding equals() method?
167.How does hashCode() method work in Java?
168.Is it a good idea to use Generics in collections?
Mixed Questions
169.What are Wrapper classes in Java?
170.What is the purpose of native method in Java?
171. What is System class?
172.What is System, out and println in System.out.println method call?
173.What is the other name of Shallow Copy in Java?
174.What is the difference between Shallow Copy and Deep Copy in
Java?
175.What is a Singleton class?
176.What is the difference between Singleton class and Static class?
Java Collection
177.What is the difference between Collection and Collections
Framework in Java?
178.What are the main benefits of Collections Framework in Java?
179.What is the root interface of Collection hierarchy in Java?
180.What are the main differences between Collection and Collections?
181. What are the Thread-safe classes in Java Collections framework?
182.How will you efficiently remove elements while iterating a
Collection?
183.How will you convert a List into an array of integers like- int[]?
184.How will you convert an array of primitive integers int[] to a List
collection?
185.How will you run a filter on a Collection?
186.How will you convert a List to a Set?
187.How will you remove duplicate elements from an ArrayList?
188.How can you maintain a Collection with elements in Sorted order?
189.What is the difference between Collections.emptyList() and creating
new instance of Collection?
190.How will you copy elements from a Source List to another list?
191. What are the Java Collection classes that implement List interface?
192.What are the Java Collection classes that implement Set interface?
193.What is the difference between an Iterator and ListIterator in Java?
194.What is the difference between Iterator and Enumeration?
195.What is the difference between an ArrayList and a LinkedList data
structure?
196.What is the difference between a Set and a Map in Java?
197.What is the use of a Dictionary class?
198.What is the default size of load factor in a HashMap collection in
Java?
199.What is the significance of load factor in a HashMap in Java?
200.What are the major differences between a HashSet and a HashMap?
201.What are the similarities between a HashSet and a HashMap in Java?
202.What is the reason for overriding equals() method?
203.How can we synchronize the elements of a List, a Set or a Map?
204.What is Hash Collision? How Java handles hash-collision in
HashMap?
205.What are the Hash Collision resolution techniques?
206.What is the difference between Queue and Stack data structures?
207.What is an Iterator in Java?
208.What is the difference between Iterator and Enumeration in Java?
209.What is the design pattern used in the implementation of Enumeration
in Java?
210.Which methods do we need to override to use an object as key in a
HashMap?
211. How will you reverse a List in Java?
212.How will you convert an array of String objects into a List?
213.What is the difference between peek(), poll() and remove() methods
of Queue interface in java?
214.What is the difference between Array and ArrayList in Java?
215.How will you insert, delete and retrieve elements from a HashMap
collection in Java?
216.What are the main differences between HashMap and
ConcurrentHashMap in Java?
217.What is the increasing order of performance for following collection
classes in Java?
218.Why does Map interface not extend Collection interface in Java?
219.What are the different ways to iterate elements of a list in Java?
220.What is CopyOnWriteArrayList? How it is different from ArrayList
in Java?
221.How remove() method is implemented in a HashMap?
222.What is BlockingQueue in Java Collections?
223.How is TreeMap class implemented in Java?
224.What is the difference between Fail-fast and Fail-safe iterator in
Java?
225.How does ConcurrentHashMap work in Java?
226.What is the importance of hashCode() and equals() methods?
227.What is the contract of hashCode() and equals() methods in Java?
228.What is an EnumSet in Java?
229.What are the main Concurrent Collection classes in Java?
230.How will you convert a Collection to SynchronizedCollection in Java?
231.How IdentityHashMap is different from a regular Map in Java?
232.What is the main use of IdentityHashMap?
233.How can we improve the performance of IdentityHashMap?
234.Is IdentityHashMap thread-safe?
235.What is a WeakHashMap in Java?
236.How can you make a Collection class read Only in Java?
237.When is UnsupportedOperationException thrown in Java?
238.Let say there is a Customer class. We add objects of Customer class
to an ArrayList. How can we sort the Customer objects in ArrayList by
using customer firstName attribute of Customer class?
239.What is the difference between Synchronized Collection and
Concurrent Collection?
240.What is the scenario to use ConcurrentHashMap in Java?
241.How will you create an empty Map in Java?
242.What is the difference between remove() method of Collection and
remove() method of Iterator?
243.Between an Array and ArrayList, which one is the preferred
collection for storing objects?
244.Is it possible to replace Hashtable with ConcurrentHashMap in Java?
245.How CopyOnWriteArrayList class is different from ArrayList and
Vector classes?
246.Why ListIterator has add() method but Iterator does not have?
247.Why do we sometime get ConcurrentModificationException during
iteration?
248.How will you convert a Map to a List in Java?
249.How can we create a Map with reverse view and lookup in Java?
250.How will you create a shallow copy of a Map?
251.Why we cannot create a generic array in Java?
252.What is a PriorityQueue in Java?
253.What are the important points to remember while using Java
Collections Framework?
254.How can we pass a Collection as an argument to a method and ensure
that method will not be able to modify it?
255.Can you explain how HashMap works in Java?
256.Can you explain how HashSet is implemented in Java?
257.What is a NavigableMap in Java?
258.What is the difference between descendingKeySet() and
descendingMap() methods of NavigableMap?
259.What is the advantage of NavigableMap over Map?
260.What is the difference between headMap(), tailMap() and subMap()
methods of NavigableMap?
261.How will you sort objects by Natural order in a Java List?
262.How can we get a Stream from a List in Java?
263.Can we get a Map from a Stream in Java?
264.What are the popular implementations of Deque in Java?
Advanced Multi-threading
265.What is a Thread in Java?
266.What is the priority of a Thread and how it is used in scheduling?
267.What is the default priority of a thread in Java?
268.What are the three different priorities that can be set on a Thread in
Java?
269.What is the purpose of join() method in Thread class?
270.What is the fundamental difference between wait() and sleep()
methods?
271.Is it possible to call run() method instead of start() on a thread in
Java?
272.What is a daemon thread in Java?
273.How can we make a regular thread Daemon thread in Java?
274.How will you make a user thread into daemon thread if it has already
started?
275.Can we start a thread two times in Java?
276.What is a Shutdown hook in Java?
277.What is synchronization in Java?
278.What is the purpose of Synchronized block in Java?
279.What is static synchronization?
280.What is a Deadlock situation?
281.What is the meaning of concurrency?
282.What is the main difference between process and thread?
283.What is a process and thread in the context of Java?
284.What is a Scheduler?
285.What is the minimum number of Threads in a Java program?
286.What are the properties of a Java thread?
287.What are the different states of a Thread in Java?
288.How will you set the priority of a thread in Java?
289.What is the purpose of Thread Groups in Java?
290.Why we should not stop a thread by calling its stop() method?
291.How will you create a Thread in Java?
292.How can we stop a thread in the middle of execution in Java?
293.How do you access the current thread in a Java program?
294.What is Busy waiting in Multi-threading?
295.How can we prevent busy waiting in Java?
296.Can we use Thread.sleep() method for real-time processing in Java?
297.Can we wake up a thread that has been put to sleep by using
Thread.sleep() method?
298.What are the two ways to check if a Thread has been interrupted?
299.How can we make sure that Parent thread waits for termination of
Child thread?
300.How will you handle InterruptedException in Java?
301.Which intrinsic lock is acquired by a synchronized method in Java?
302.Can we mark a constructor as synchronized in Java?
303.Can we use primitive values for intrinsic locks?
304.Do we have re-entrant property in intrinsic locks?
305.What is an atomic operation?
306.Can we consider the statement i++ as an atomic operation in Java?
307.What are the Atomic operations in Java?
308.Can you check if following code is thread-safe?
309.What are the minimum requirements for a Deadlock situation in a
program?
310.How can we prevent a Deadlock?
311. How can we detect a Deadlock situation?
312.What is a Livelock?
313.What is Thread starvation?
314.How can a synchronized block cause Thread starvation in Java?
315.What is a Race condition?
316.What is a Fair lock in multi-threading?
317.Which two methods of Object class can be used to implement a
Producer Consumer scenario?
318.How JVM determines which thread should wake up on notify()?
319.Check if following code is thread-safe for retrieving an integer value
from a Queue?
320.How can we check if a thread has a monitor lock on a given object?
321.What is the use of yield() method in Thread class?
322.What is an important point to consider while passing an object from
one thread to another thread?
323.What are the rules for creating Immutable Objects?
324.What is the use of ThreadLocal class?
325.What are the scenarios suitable for using ThreadLocal class?
326.How will you improve the performance of an application by multi-
threading?
327.What is scalability in a Software program?
328.How will you calculate the maximum speed up of an application by
using multiple processors?
329.What is Lock contention in multi-threading?
330.What are the techniques to reduce Lock contention?
331.What technique can be used in following code to reduce Lock
contention?
332.What is Lock splitting technique?
333.Which technique is used in ReadWriteLock class for reducing Lock
contention?
334.What is Lock striping?
335.What is a CAS operation?
336.Which Java classes use CAS operation?
337.Is it always possible to improve performance by object pooling in a
multi-threading application?
338.How can techniques used for performance improvement in a single
thread application may degrade the performance in a multi-threading
application?
339.What is the relation between Executor and ExecutorService
interface?
340.What will happen on calling submit() method of an ExecutorService
instance whose queue is already full?
341.What is a ScheduledExecutorService?
ACKNOWLEDGMENTS
We thank our readers who constantly send
feedback and reviews to motivate us in creating
these useful books with the latest information!
INTRODUCTION
Java byte code can run on any supported platform in same way.
Where as other languages require libraries compiled for a specific
platform to run.
6. Why people say that Java is 'write
once and run anywhere' language?
You can write Java code on Windows and compile it in Windows
platform. The class and jar files that you get from Windows
platform can run as it is on Unix environment. So it is a truly
platform independent language.
Behind all this portability is Java byte code. Byte code generated by
Java compiler can be interpreted by any JVM. So it becomes much
easier to write programs in Java and expect those to run on any
platform.
Java compiler javac compiles java code and JVM java runs that
code.
7. How does ClassLoader work in
Java?
In Java, ClassLoader is a class that is used to load files in JVM.
ClassLoader loads files from their physical file locations e.g.
Filesystem, Network location etc.
We can write static public void main() instead of public static void
main().
10. In Java, if we do not specify any
value for local variables, then what
will be the default value of the local
variables?
Java does not initialize local variables with any default value. So
these variables will be just null by default.
11. Let say, we run a java class without
passing any arguments. What will be
the value of String array of
arguments in Main method?
By default, the value of String array of arguments is empty in Java.
It is not null.
12. What is the difference between
byte and char data types in Java?
Both byte and char are numeric data types in Java. They are used to
represent numbers in a specific range.
Major difference between them is that a byte can store raw binary
data where as a char stores characters or text data.
The issue with Multiple Inheritance is that both the parent classes
may have different implementation for the same method. So they
have different ways of doing the same thing. Now which
implementation should the child class choose?
Lets say you have a class TV and another class AtomBomb. Both
have method switchOn() but only TV has switchOff() method. If
your class inherits from both these classes then you have an issue
that you can switchOn() both parents, but switchOff will only
switchOff() TV.
Also a static method can access and modify static data members.
This also helps in keeping the behavior as well as state at the class
level.
35. Why do we mark main method as
static in Java?
The main method in Java is marked as static, so that JVM can call it
to start the program. If main method is not static, then which
constructor will be called by Java process?
Before Java 5, any method that overrides the method of parent class
would have same return type.
E.g.
Person p = new Person();
p.walk(); // Java compiler resolves this binding at compile time.
There are interfaces that do not have any data member or methods.
These interfaces are called Marker interface.
E.g. Serializable, Cloneable, Remote etc.
65. What can we use instead of
Marker interface?
We can use annotations instead of Marker interface.
66. How Annotations are better than
Marker Interfaces?
Annotations serve the purpose of conveying metadata about the
class to its consumers without creating a separate type for it.
Integer class is a wrapper for int. If it is not marked final, then any
other class can extend it and modify the behavior of Integer
operations. To avoid this Integer wrapper class is marked as final.
75. What is a blank final variable in
Java?
When we declare a final variable without giving any initial value,
then it is called blank final variable.
76. How can we initialize a blank final
variable?
A blank final instance variable can be initialized in a constructor.
If you have two classes with same name, then you may get name
collision on importing the class erroneously.
FileName: Foo.java
public class Foo {
private void message(){System.out.println("hello java"); }
}
FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("Foo");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}
99. How can we create an Object
dynamically at Runtime in Java?
We can use Reflection to create an Object dynamically at Runtime
in Java. We can use Class.newInstance() or
Constructor.newInstance() methods for creating such Objects.
Garbage Collection
100. What is Garbage Collection in
Java?
Java has an internal mechanism called Garbage collection to
reclaim the memory of unused projects at run time.
1. Strong Reference
2. Soft Reference
3. Weak Reference
4. Phantom Reference
107. How can we reference an
unreferenced object again?
We can provide implementation in finalize() method to reference
and unreferenced object. For an unreferenced object, finalize()
method is called at the time of Garbage Collection. At this time,
Object can pass its reference ‘this’ to finalize() method and revive
itself.
108. What kind of process is the
Garbage collector thread?
Garbage Collection is a Daemon process in JVM. It is an internal
process that keep checking Memory usage and cleans up the
memory.
109. What is the purpose of the
Runtime class?
The purpose of the Runtime class is to provide access to the Java
Runtime system. This class provides certain important methods like:
// Client Code
Abc.registerCallback(new Abc.Xyz() {
public void callback() {...}
});
Any code that cannot access Abc can not access interface Xyz also.
The above code creates only one object. Since there is only one
String Literal “HelloWorld” created, all the references point to
same object.
124. How many ways are there in
Java to create a String object?
Java provides two ways to create a String object. One is by using
String Literal, the other is by using new operator.
125. How many objects does
following code create?
Code:
String s = new String("HelloWorld");
The above code creates two objects. One object is created in String
constant pool and the other is created on the heap in non-pool area.
126. What is String interning?
Stack
Properties
Vector
Hashtable
BlockingQueue
ConcurrentMap
ConcurrentNavigableMap
149. How will you efficiently
remove elements while iterating a
Collection?
The right way to remove elements from a collection while iterating
is by using ListIterator.remove() method.
E.g.
An iterator is first created to traverse the list. But at the same time
the list is changed by remove() method.
The other option would be to use a for loop and explicitly adding
integers to a List.
int[]intArray = {10,20,30};
List<Integer> intList = new ArrayList<Integer>();
for (int i: intArray) {
intList.add(i);
}
152. How will you run a filter on a
Collection?
We can use CollectionUtils of Apache for this purpose. We will
have to create a Predicate that will define the condition for our
filter. Then we can apply this Predicate in filter() method.
In this example we filter any names that are less than 5 characters
long.
2. Null values: A HashMap allows only one null key and any
number of null values. A Hashtable does not allow null
keys and null values.
Properties files are used for many purposes in all kinds of Java
applications. Some of the uses are to store configuration, initial
data, application options etc.
When we change the value of a key in a properties file, there is no
need to recompile the Java application. So it provides benefit of
changing values at runtime.
166. What is the reason for overriding
equals() method?
The equals() method in Object class is used to check whether two
objects are same or not. If we want a custom implementation we can
override this method.
For example, a Person class has first name, last name and age. If we
want two Person objects to be equal based on name and age, then
we can override equals() method to compare the first name, last
name and age of Person objects.
AbstractList
AbstractSequentialList
ArrayList
AttributeList
CopyOnWriteArrayList
LinkedList
RoleList
RoleUnresolvedList
Stack
Vector
172. What are the Java Collection
classes that implement Set interface?
Java classes that implement Set interface are:
AbstractSet
ConcurrentSkipListSet
CopyOnWriteArraySet
EnumSet
HashSet
JobStateReasons
LinkedHashSet
TreeSet
173. What is the difference between an
Iterator and ListIterator in Java?
Iterator and ListIterator are two interfaces in Java to traverse data
structures. The differences between these two are: