Java Interview Q&A
Complete Reference · 0 to 1 Year Experience
Core Java · OOP · Collections · Multithreading · Serialization
STATIC & NON-STATIC MEMBERS
Q6. How to access static members?
Static members are accessed using the class name — [Link]. No object is needed.
Example: [Link], [Link](). Accessing them through an object reference is allowed by the compiler but
not recommended, as it is misleading.
Q7. How to access non-static members of class?
Non-static members are accessed through an object. First create an object using new, then use the dot
operator. Example: MyClass obj = new MyClass(); [Link](). Each object gets its own separate copy of
non-static members.
Q8. Differences between static and non-static members?
Static members belong to the class and are shared by all objects. Non-static members belong to each
object individually. Static members are stored in the Method Area; non-static members are stored in the
Heap. Static members can be accessed without creating an object.
Q9. When to use static vs non-static variables?
Use static when the value is shared by all objects — like a counter tracking how many objects are created.
Use non-static when each object needs its own value — like a student's name or rollNumber. Example:
static int count; vs int name;
REFERENCE VARIABLES & TYPES
Q10. What is a reference variable? How to create it?
A reference variable stores the address of an object in heap memory — it does not hold the object itself.
We create one by declaring a class-type variable and assigning it an object using new. Example: Dog d =
new Dog(); — here d is the reference variable.
Q11. What is a primitive variable? How to declare it?
A primitive variable directly holds a simple value, not an object. Java has 8 primitive types: byte, short, int,
long, float, double, char, boolean. Declaration example: int age = 25; double salary = 50000.0; boolean
isActive = true; They are stored on the stack.
Q12. What is a non-primitive variable? How to declare it?
A non-primitive (reference) variable holds the address of an object, not the value itself. Examples are
String, arrays, and all class types. Declaration: String name = "John"; int[] arr = new int[5]; The actual
object is stored in heap memory.
CONSTRUCTORS
Q15. Does every class have a constructor?
Yes. Every class has at least one constructor. If we do not define any, the JVM automatically provides a
default no-argument constructor. If we define any parameterized constructor, the JVM stops providing the
default one — we must define it ourselves if still needed.
Q22. What does the new operator do and what does it return?
The new operator allocates memory for a new object in the heap, calls the constructor to initialize it, and
returns the reference (address) of the newly created object. This reference is then stored in a reference
variable.
Q23. Does Java support pass by reference? Why?
No. Java supports only pass by value. When we pass a primitive, its value is copied. When we pass an
object, the reference (address) is copied — not the object itself. So field changes reflect outside, but
reassigning the reference inside the method has no effect on the original.
Q24. Can a constructor be static?
No. A constructor cannot be static. Static members belong to the class and have no link to any object. A
constructor is meant to initialize a specific object — it always runs in the context of an object. The compiler
does not allow it to be declared static.
Q25. Can a constructor be inherited?
No. Constructors are never inherited. A subclass can call the parent's constructor using super(), but it does
not own that constructor. Each class must define its own constructors. If super() is not written, the JVM
inserts it automatically to call the parent's no-arg constructor.
Q27. What is the access level of the default constructor?
The default constructor provided by the JVM always has public access. If we define a constructor without
any access modifier, it gets default (package-level) access. The JVM-provided default is public so objects
can be created from any class.
Q28. Can we override a constructor?
No. Constructors cannot be overridden. Overriding requires a method to be inherited first. Since
constructors are not inherited, there is nothing to override. A subclass can have a constructor with the
same name (its own class name), but that is not overriding.
FINAL MEMBERS & REFERENCE VARIABLES
Q34. Explain final member variables and how to initialize them?
A final variable is a constant — its value cannot be changed once assigned. It must be initialized at
declaration, inside an instance initializer block, or inside the constructor. It cannot be left uninitialized.
Example: final int MAX = 100; Re-assignment is a compile-time error.
Q35. Give an example when to use a final instance variable?
Use a final instance variable when each object must have a fixed value that never changes after creation.
Example: a BankAccount class with final int accountNumber. Once the account is created, the account
number should never be changed — final enforces this.
Q37. Explain static reference variable?
A static reference variable is declared with the static keyword. It is shared by all objects of the class — all
instances see the same reference. Example: static Dog sharedDog = new Dog(); All instances of the class
point to the same sharedDog object.
Q38. Explain instance reference variable?
An instance reference variable is declared without static. Each object gets its own copy of this variable,
and each copy can point to a different object. Example: Dog myDog; declared as an instance field — every
object has its own separate myDog reference.
ACCESS MODIFIERS
Q44a. What are the access specifiers provided in Java?
Java provides four access modifiers: private — same class only. default — same package (no keyword).
protected — same package and subclasses. public — accessible from anywhere. They control visibility of
classes, methods, and fields.
Q45a. What is the use of private member variables?
Private member variables can only be accessed within the same class. They protect data from being
changed directly from outside. This is the core principle of encapsulation. We expose controlled access
through public getter and setter methods.
INHERITANCE
Q42. Which members of the super class can be inherited by the sub class?
A subclass inherits all public and protected members — fields, methods, and nested classes. Default
(package-level) members are inherited only if both classes are in the same package. Private members and
constructors are NOT inherited.
Q43. Can we inherit the constructor of a super class?
No. Constructors are never inherited. A subclass calls the parent's constructor using super(), but that
constructor does not become part of the subclass. If super() is not written explicitly, the JVM inserts it
automatically to call the parent's no-arg constructor.
Q44b. What is the role of a constructor in inheritance?
When a subclass object is created, the parent's constructor must run first to initialize the parent's part of
the object. This happens through constructor chaining via super(). The JVM adds super() automatically if
not written. This ensures the full object is initialized top-down.
Q45b. From which super class can the sub class NOT inherit?
A subclass cannot inherit from a final class — String is a well-known example. Also, if a super class has
only private constructors, the subclass cannot be instantiated because the JVM cannot call the parent
constructor. This blocks effective inheritance.
Q46. If super class has a private constructor, can sub class inherit its members?
Public and protected members may technically be inherited, but the subclass cannot be instantiated
because the JVM cannot call the parent's private constructor during object creation. This results in a
compile-time error, so the subclass is unusable.
METHOD OVERLOADING & OVERRIDING
Q50. When to use Method Overloading? Real-time examples?
Use overloading when the same operation works with different input types or counts. Example:
[Link]() is overloaded for int, String, double, etc. Another example: a Calculator class with
add(int, int) and add(double, double). It improves readability.
Q51. Can a sub class overload methods of the super class?
Yes. A subclass can overload a super class method by defining one with the same name but different
parameters. Overloading is resolved at compile time by signature. It does not conflict with the inherited
version — both exist independently in the subclass.
Q_ov. Which methods can and cannot be overridden?
Can be overridden: public and protected instance methods. Cannot be overridden: static methods (they
are hidden, not overridden), private methods (not inherited), and final methods (locked by compiler).
Constructors also cannot be overridden.
Q57a. What do you mean by declaring an instance method as final?
A final instance method cannot be overridden in any subclass. The compiler prevents it at compile time.
We use it to lock critical behavior that must remain unchanged. Example: getAccountNumber() in
BankAccount — no subclass should be allowed to change its logic.
STRING HANDLING
Q_str1. What are the types of creating a String object?
Two ways: (1) String literal — String s = "hello"; — the JVM checks the String Pool first and reuses an
existing object if the same value is present. (2) Using new — String s = new String("hello"); — always
creates a new object in heap outside the pool.
Q_str2. Explain Constant Pool and Non-Constant Pool?
The Constant Pool (String Pool) is a special area in heap where string literals are stored and reused by the
JVM. Non-constant pool means objects created using new String() — they always get a fresh heap object
and are never pooled, even for the same value.
ARRAYS
Q10b. What are class-type arrays?
A class-type array holds references to objects, not primitive values. Example: Dog[] dogs = new Dog[3]; —
this creates 3 Dog reference slots, all initially null. Each element must be separately assigned an object.
They are stored in heap memory.
COLLECTIONS — LIST
Q_list1. What are the types of List?
Main List implementations: ArrayList — backed by a dynamic array, fast for reads. LinkedList — backed by
a doubly linked list, fast for insertions/deletions at ends. Vector — like ArrayList but synchronized. Stack —
extends Vector, works on LIFO.
Q_al1. What are the constructors present in ArrayList?
ArrayList() — empty list with default capacity 10. ArrayList(int initialCapacity) — empty list with given
capacity. ArrayList(Collection c) — list pre-filled with all elements of the given collection in the same
iteration order.
Q37b. How many interfaces does ArrayList implement?
ArrayList implements: List, RandomAccess, Cloneable, and Serializable. Through List, it also indirectly
implements Collection and Iterable. RandomAccess signals fast index-based access. Cloneable allows
cloning. Serializable allows serialization.
Q_al2. How to convert ArrayList to List and ArrayList to Collection?
No explicit conversion is needed — ArrayList already implements both. Just upcast: List list = new
ArrayList<>(); and Collection col = new ArrayList<>(); This is standard upcasting and works automatically
without any copying.
Q39. How does ArrayList grow dynamically?
When the internal array is full, ArrayList creates a new array with 1.5x the old size (newCapacity =
oldCapacity + oldCapacity/2), copies all elements across, and lets the old array be garbage collected.
Setting a good initial capacity avoids frequent resizing.
Q40. When to use ArrayList?
Use ArrayList for frequent index-based reads (O(1)), when the list is read more than modified, and when
insertions/deletions happen mostly at the end. Avoid it for frequent insertions or deletions in the middle —
those are O(n) shift operations.
Q41. Explain LinkedList and its implementation data structure?
LinkedList is backed by a doubly linked list. Each element is a node holding data, a reference to the next
node, and a reference to the previous node. It gives O(1) insertion and deletion at ends. It also implements
Deque, so it can act as a stack or queue.
Q42b. How many interfaces does LinkedList implement?
LinkedList implements: List, Deque, Queue, Cloneable, and Serializable. Through these, it also indirectly
implements Collection and Iterable. Because it implements Deque, it works as a stack, queue, or
double-ended queue in addition to a regular list.
Q43b. Differences between ArrayList and LinkedList?
ArrayList — backed by array, O(1) get by index, O(n) insert/delete in middle, less memory. LinkedList —
backed by doubly linked list, O(1) insert/delete at ends, O(n) get by index, more memory due to node
pointers. Use ArrayList for reads; LinkedList for end insertions.
Q_al3. What is the implementation data structure of ArrayList?
ArrayList is internally backed by a dynamic Object[] array with a default initial capacity of 10. When it fills
up, a new array of 1.5x the old size is created and elements are copied. get() is O(1); insert/delete in the
middle is O(n) due to shifting.
Q44c. Explain Vector and its features?
Vector is similar to ArrayList but all its methods are synchronized, making it thread-safe. It doubles its size
on growth (ArrayList grows by 1.5x). It is a legacy class from Java 1.0. For modern thread-safe needs,
prefer CopyOnWriteArrayList or synchronized wrappers.
Q45c. How to sort elements of ArrayList?
Use [Link](list) for natural order — elements must implement Comparable. Use
[Link](list, comparator) for custom order. Since Java 8, also: [Link](Comparator) or
stream().sorted(). Example: [Link](names) sorts alphabetically.
Q46b. How to get a Synchronized List?
Use [Link](list). Example: List syncList = [Link](new
ArrayList<>()); Every method call is synchronized. For iteration, manually wrap the loop in a
synchronized(syncList) block.
EXCEPTION HANDLING
Q_ex1. Can we write a try block without a catch block?
Yes. try-finally without catch is valid. The exception is not handled here — it propagates to the caller. But
the finally block still runs before it propagates. We use this when we want cleanup code but do not need to
handle the exception in the current method.
Q_ex2. What is the use of a multi-catch block?
A multi-catch block handles multiple exception types in one catch using the pipe symbol. Example: catch
(IOException | SQLException e). It avoids duplicate catch blocks for exceptions that need the same
handling. The exceptions in multi-catch cannot be related by inheritance.
Q_ex3. Explain finally block?
The finally block always executes after try and catch — whether an exception occurred or not. It is used for
cleanup tasks like closing files, streams, or database connections. It does not run only if [Link]() is
called or the JVM itself crashes.
COLLECTIONS — SET
Q57b. How does Set maintain no duplicates?
When we add an element to a HashSet, it calls hashCode() to find the bucket. If elements already exist in
that bucket, it calls equals() to compare. If equals() returns true, the element is a duplicate and is silently
rejected. Both hashCode() and equals() must be correctly overridden.
Q58. Why should we override hashCode() and equals()?
If two objects are equal by equals(), they must return the same hashCode — this is the contract. HashMap
and HashSet use hashCode() to find the bucket and equals() to confirm the match. Overriding only
equals() means equal objects may land in different buckets — breaking duplicate detection.
Q61. Explain constructors of HashSet?
HashSet() — empty set, default capacity 16, load factor 0.75. HashSet(int capacity) — custom initial
capacity. HashSet(int capacity, float loadFactor) — custom capacity and load factor. HashSet(Collection c)
— set pre-filled from the collection, duplicates removed.
Q62. Explain constructors of TreeSet?
TreeSet() — empty set, natural sort order. TreeSet(Comparator c) — sorted by custom comparator.
TreeSet(Collection c) — built from the collection, sorted naturally. TreeSet(SortedSet s) — built from an
existing SortedSet, preserving its ordering.
EXCEPTIONS — CLASS LOADING
Q25b. Difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is a checked exception thrown at runtime when we try to load a class
dynamically using [Link]() and it is not found. NoClassDefFoundError is an Error thrown when a
class was present at compile time but is missing at runtime — for example, a jar was removed.
COLLECTIONS — COMPARABLE & LIST METHODS
Q76. Why do we need the Comparable interface?
Comparable defines the natural sort order of a class using compareTo(). When we call [Link]()
on a list of custom objects, Java uses compareTo() to compare them. Without it, Java does not know how
to sort the objects and throws a ClassCastException.
Q_lm. Explain the methods of List interface?
Key methods: add(e), add(index, e) — insert. get(index) — retrieve. set(index, e) — update.
remove(index) — delete. size() — count. contains(o) — check presence. indexOf(o) — find position.
listIterator() — bidirectional traversal. subList(from, to) — extract a portion.
Q63. How to convert Set to Collection?
No conversion needed — Set already extends Collection. Just assign: Collection col = new HashSet<>(); If
you have an existing Set, pass it to any method accepting Collection directly. No casting or copying is
required.
Q64. How to convert Set to ArrayList?
Pass the Set into the ArrayList constructor: new ArrayList<>(set). This copies all elements from the Set
into the ArrayList. Order depends on the Set type — HashSet is random, LinkedHashSet preserves
insertion order, TreeSet gives sorted order.
COLLECTIONS — MAP
Q67. How to use Iterator on Map?
Map does not directly implement Iterable. Use: [Link]().iterator() for key-value pairs,
[Link]().iterator() for keys only, [Link]().iterator() for values only. Example: Iterator> it =
[Link]().iterator(); then call hasNext() and next().
Q_map. Explain types of Map in detail?
HashMap — unordered, one null key allowed, not synchronized, O(1) get/put. LinkedHashMap —
maintains insertion order. TreeMap — sorted by key, no null key. Hashtable — synchronized, no null
key/value, legacy. ConcurrentHashMap — thread-safe, better performance than Hashtable.
Q69. What is HashMap and explain its implementation?
HashMap stores key-value pairs using an array of buckets. hashCode() of the key finds the bucket.
Collisions are stored as a linked list. Since Java 8, if a bucket exceeds 8 entries, it converts to a Red-Black
tree. get() uses hashCode() to find the bucket and equals() to find the key.
Q70. What is Hashtable and explain its implementation?
Hashtable is similar to HashMap but every method is synchronized, making it thread-safe. It does not allow
null keys or values. It is a legacy class from Java 1.0 with an array-of-buckets structure and linked list
chaining. Prefer ConcurrentHashMap for modern thread-safe use.
COLLECTIONS — QUEUE
Q56. Explain PriorityQueue implementation in detail?
PriorityQueue is backed by a min-heap internally using an array. The element with the smallest value (or
highest custom priority) is always at the head. Elements must implement Comparable or a Comparator
must be provided. Null is not allowed. Key methods: add(), poll(), peek().
MULTITHREADING
Q79. Explain Thread properties?
Every thread has: Name — identifier. Priority — integer 1 to 10, default 5. Daemon status — background
or foreground. State — New, Runnable, Blocked, Waiting, Timed Waiting, Terminated. ID — unique long
value assigned by JVM. Most can be read and some set using Thread methods.
Q81. Explain threads started by JVM?
When a Java program starts, the JVM creates the main thread to run main(). It also creates background
daemon threads — the Garbage Collector thread and the Finalizer thread. The JVM exits when all
non-daemon threads finish. The main thread is the only non-daemon thread started by JVM.
Q83. Explain methods provided by Thread to use thread properties?
getName() / setName(String) — read or set name. getPriority() / setPriority(int) — read or set priority.
isDaemon() / setDaemon(boolean) — check or set daemon status. getState() — current state. getId() —
unique thread ID. isAlive() — true if started and not finished.
Q84. What is Thread priority? What is the range and default?
Thread priority is a hint to the OS scheduler about which thread should get CPU time first. Range is 1
(MIN_PRIORITY) to 10 (MAX_PRIORITY). Default is 5 (NORM_PRIORITY). Higher priority increases the
chance of getting CPU time, but it is not guaranteed — it depends on the OS scheduler.
Q85. Explain the constructors of Thread?
Thread() — default name like Thread-0. Thread(String name) — custom name. Thread(Runnable r) —
runs the given Runnable. Thread(Runnable r, String name) — Runnable with a custom name.
Thread(ThreadGroup g, String name) — assigns thread to a group.
Q87. How to make a Runnable object run as a thread?
Create a class implementing Runnable and write the task in run(). Pass the Runnable to a Thread
constructor. Then call start() on the Thread. Example: MyTask task = new MyTask(); Thread t = new
Thread(task); [Link](); The JVM creates a new thread and calls run() on it.
Q90. What is object lock? When is it created?
Every object in Java has a monitor lock. It is created when the object is created in the heap. When a
thread enters a synchronized instance method or synchronized block on an object, it acquires that object's
lock. Other threads wait until the lock is released before entering.
Q91. What is class lock? When is it created?
Every class has a class-level lock associated with its Class object. It is created when the class is loaded by
the JVM. When a thread enters a synchronized static method, it acquires the class lock. Only one thread
can execute any synchronized static method of that class at a time.
Q92. How to get a reference to the current running thread?
Use [Link]() — a static method of the Thread class. It returns a reference to the thread
currently executing the call. Example: Thread t = [Link](); We can then use [Link](),
[Link](), and other methods on it.
Q95. Explain interthread communication and how to achieve it?
Interthread communication means threads coordinate — one waits for another to finish a task. It is
achieved using wait(), notify(), and notifyAll() inside synchronized blocks. One thread calls wait() to release
the lock and pause; another does its work and calls notify() to wake it up.
Q96. Explain wait() and wait(time) methods and where they are implemented?
wait() causes the current thread to release the object lock and wait indefinitely until notify() is called.
wait(long time) waits for the given milliseconds then wakes up automatically. Both are implemented in the
Object class and must be called inside a synchronized block.
Q97. Explain notify() and notifyAll() and where they are implemented?
notify() wakes up one thread waiting on the same object lock — the chosen thread is not guaranteed.
notifyAll() wakes up all waiting threads. Woken threads must still reacquire the lock before proceeding.
Both are in the Object class and must be called inside a synchronized block.
Q99. Difference between user thread and daemon thread?
A user thread is a main working thread — the JVM waits for all user threads to finish before exiting. A
daemon thread is a background service — JVM does not wait for it and kills it when all user threads are
done. Examples: GC, Finalizer. Set with [Link](true) before start().
Q100. How to pause execution of the current thread?
Use [Link](milliseconds) — a static method of Thread class. It pauses the current thread for the
specified time without releasing any held locks. After the time expires, the thread moves back to Runnable
state. It throws InterruptedException, which must be handled.
SERIALIZATION
Q105. What is Object deserialization?
Deserialization reconstructs a Java object from a stream of bytes — it is the reverse of serialization. We
use ObjectInputStream and its readObject() method. The class must implement Serializable, and the
serialVersionUID must match the saved stream, otherwise InvalidClassException is thrown.
Q108. What is the use of finalize()? In which class is it present?
finalize() is defined in the Object class. The Garbage Collector calls it just before destroying an
unreachable object — it was used for cleanup like closing connections. Deprecated since Java 9 because
GC timing is unpredictable. Use try-with-resources or AutoCloseable instead.