Java Interview Question
Q1. What is JDBC?
JDBC is an abstraction layer that allows users to choose
between databases. JDBC enables developers to write database
applications in Java without having to concern themselves with
the underlying details of a particular database.
Q2. What is the Difference between JDK and JRE?
• The Java Runtime Environment (JRE) is basically the Java
Virtual Machine (JVM) where your Java programs are being
executed. It also includes browser plugins for applet
execution.
• The Java Development Kit (JDK) is the full-featured
Software Development Kit for Java, including the JRE, the
compilers, and tools (like JavaDoc, and Java Debugger), in
order for a user to develop, compile and execute Java
applications.
Q3. What is JVM? Why is Java called the "Platform
Independent Programming Language”?
A Java virtual machine (JVM) is a process virtual machine that
can execute Java bytecode. Each Java source file is compiled
into a bytecode file, which is executed by the JVM. Java was
designed to allow application programs to be built that could be
run on any platform, without having to be rewritten or
recompiled by the programmer for each separate platform.
A Java virtual machine makes this possible because it is aware
of the specific instruction lengths and other particularities of
the underlying hardware platform.
Q4. Why is Java not a pure object oriented language?
Java supports primitive data types - byte, boolean, char, short,
int, float, long, and double and hence it is not a pure object
oriented language.
Q5. Difference between Heap and Stack Memory in java. And
how java utilizes this.
Stack memory is the portion of memory that was assigned to
every individual program. And it was fixed. On the other hand,
Heap memory is the portion that was not allocated to the java
program but it will be available for use by the java program
when it is required, mostly during the runtime of the program.
Java Utilizes this memory as -
• When we write a java program then all the variables,
methods, etc are stored in the stack memory.
• And when we create any object in the java program then
that object was created in the heap memory. And it was
referenced from the stack memory.
Q6. What do you understand by an instance variable and a
local variable?
Instance variables are those variables that are accessible by all
the methods in the class. They are declared outside the
methods and inside the class. These variables describe the
properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables
for utilization. If any modification is done on these variables,
then only that instance will be impacted by it, and all other
class instances continue to remain unaffected.
Local variables are those variables present within a block,
function, or constructor and can be accessed only inside them.
The utilization of the variable is restricted to the block scope.
Whenever a local variable is declared inside a method, the
other class methods don’t have any knowledge about the local
variable.
Q7. What are the main features of Java?
• Simple and easy to learn
• Object-Oriented
• Platform-independent (WORA – Write Once, Run
Anywhere)
• Secure and Robust
• Distributed (supports RMI, sockets)
• Multithreaded
• High performance with JIT compiler
• Automatic memory management (Garbage Collection)
Q8 . Explain JVM, JRE, and JDK.
• JVM (Java Virtual Machine): Runs Java bytecode, provides
platform independence.
• JRE (Java Runtime Environment): JVM + libraries + class
loaders (needed to run Java apps).
• JDK (Java Development Kit): JRE + development tools
(compiler, debugger). Used to develop Java programs.
Q9. What is the difference between Java and other
programming languages like C++?
• Java is platform-independent, C++ is not.
• Java has automatic memory management (GC), C++ uses
manual memory management.
• Java does not support multiple inheritance (uses
interfaces instead), C++ does.
• Java is purely object-oriented (almost everything is an
object), while C++ supports both procedural and OOP.
Q10. Why is Java platform-independent?
Because Java programs are compiled into bytecode, which is
executed by the JVM.
Since JVM is available for all platforms (Windows, Linux, Mac,
etc.), the same bytecode can run anywhere without
recompilation.
Q11. What are wrapper classes in Java?
Wrapper classes convert primitive data types into objects.
• Example: int → Integer, double → Double.
They are used in collections (like ArrayList) since
collections work only with objects.
Q12. Explain the difference between primitive data types and
objects.
• Primitive: Predefined in Java, stores simple values (e.g.,
int, char, boolean). Stored in stack.
• Object: Instances of classes, more complex. Stored in
heap.
Example:
int a = 10; // primitive
Integer b = [Link](10); // object
Q13. What are the different types of memory areas allocated
by JVM?
1. Method Area – stores class structure, metadata, static
variables.
2. Heap – stores objects.
3. Stack – stores method calls, local variables.
4. PC Register – holds address of current instruction.
5. Native Method Stack – for native (C/C++) method calls.
Q14. Explain the difference between Heap and Stack memory.
• Heap: Stores objects and instance variables, shared among
all threads. Slower.
• Stack: Stores local variables and method calls, each thread
has its own stack. Faster.
Q15. What is the difference between == and .equals() in Java?
• == → Compares references (memory addresses).
• .equals() → Compares content/values (can be overridden
in classes like String).
Example:
String s1 = new String("Java");
String s2 = new String("Java");
[Link](s1 == s2); // false (different objects)
[Link]([Link](s2)); // true (same content)
Q16. Explain the difference between final, finally, and
finalize().
• final (keyword): Used with classes (no inheritance),
methods (no override), variables (constant).
• finally (block): Used in exception handling. Code inside
always executes, even if exception occurs.
• finalize() (method): Called by garbage collector before
destroying an object (rarely used).
Q17. What are the four main principles of OOP?
1. Encapsulation – Binding data and methods together
(class).
2. Abstraction – Hiding implementation details, showing only
essentials.
3. Inheritance – One class acquires properties of another
(code reuse).
4. Polymorphism – One interface, many implementations
(method overloading/overriding).
Q18. Explain the difference between abstraction and
encapsulation.
• Abstraction: Focuses on what an object does (hides
implementation). Done via abstract classes & interfaces.
• Encapsulation: Focuses on how data is protected (hides
data). Done via access modifiers + getters/setters.
Q19. What is method overloading and method overriding?
• Overloading: Same method name, different parameter list
(compile-time polymorphism).
• Overriding: Subclass provides a specific implementation of
a method already defined in the parent class (runtime
polymorphism).
Q20. Can we override a static method in Java? Why or why
not?
• No, static methods cannot be overridden.
• They belong to the class, not the object.
• But, they can be hidden (same method in subclass will
hide parent method).
Q21. What is the difference between an abstract class and an
interface?
• Abstract class: Can have abstract + non-abstract methods,
constructors, instance variables.
• Interface: Only abstract methods (till Java 7), from Java 8
supports default and static methods.
• A class can extend only one abstract class, but can
implement multiple interfaces.
Q22. Can an interface have default or static methods?
• Yes (from Java 8).
• default method – provides body inside interface (can be
overridden).
• static method – belongs to interface itself (cannot be
overridden).
Q23. What is a constructor in Java? Can constructors be
overloaded?
• A constructor is a special method used to initialize objects.
• It has the same name as the class and no return type.
• Yes, constructors can be overloaded (different parameter
lists).
Q24. What is the difference between constructor and method?
• Constructor: Initializes object, no return type, called
automatically when object is created.
• Method: Defines behavior, must be called explicitly, can
have return type.
Q25. What is a copy constructor in Java? Does Java support it?
• Copy constructor: A constructor that creates a new object
as a copy of another object.
• Java doesn’t provide it by default (unlike C++), but you can
define your own.
Example:
class Student {
String name;
Student(Student s) { [Link] = [Link]; } // custom copy
constructor
}
Q26. Explain this keyword and super keyword with examples.
• this: Refers to the current object. Used to access instance
variables, methods, or call another constructor.
• super: Refers to parent class object. Used to access
parent’s variables, methods, or call parent constructor.
Example:
class Parent {
String name = "Parent";
}
class Child extends Parent {
String name = "Child";
void show() {
[Link]([Link]); // Child
[Link]([Link]); // Parent
}
}
Q27. What are access modifiers in Java?
Access modifiers control the scope/visibility of classes,
methods, and variables.
• public → Accessible everywhere.
• protected → Accessible within the package + subclasses.
• default (no modifier) → Accessible only within the same
package.
• private → Accessible only within the same class.
Q28. Difference between public, private, protected, and
default access.
Modifier Same Same Subclass Other
Class Package Packages
public
protected
default
private
Q29. What is the difference between static variable and
instance variable?
• Static variable → Belongs to class, shared by all objects.
• Instance variable → Belongs to each object, every object
has its own copy.
Example:
class Demo {
static int count = 0; // shared
int id; // per object
}
Q30. What is the transient keyword in Java?
• Used in serialization.
• If a variable is declared transient, it will not be saved in the
serialized object.
Q31. What is the volatile keyword in Java?
• Ensures visibility of changes across threads.
• If a variable is declared volatile, every thread reads its
latest value from main memory (not from cache).
Q32. Difference between checked and unchecked exceptions.
• Checked exceptions: Checked at compile-time (e.g.,
IOException, SQLException). Must be handled with try-
catch or throws.
• Unchecked exceptions: Occur at runtime (e.g.,
NullPointerException, ArithmeticException).
Q33. What is the difference between throw and throws?
• throw: Used to explicitly throw an exception. (inside
method)
• throws: Declares exceptions that a method might throw.
(in method signature)
Example:
void test() throws IOException { // declaration
throw new IOException("Error"); // throwing
}
Q34. What is the difference between try-catch-finally and try-
with-resources?
• try-catch-finally: Used for exception handling, finally
ensures cleanup code runs.
• try-with-resources (Java 7+): Automatically closes
resources like files, DB connections without finally block.
Q35. Can we have a try block without a catch block?
• Yes , but it must be followed by a finally block.
Example:
try {
// code
} finally {
// cleanup
}
Q36. What happens if an exception is not handled in Java?
• The program terminates abruptly.
• JVM prints the stack trace (exception name, description,
and line number).
Collections Framework
Q37. What is the difference between List, Set, and Map?
• List: Ordered collection, allows duplicates. (e.g., ArrayList,
LinkedList)
• Set: Unordered, unique elements only. (e.g., HashSet,
TreeSet)
• Map: Key-value pairs, keys are unique. (e.g., HashMap,
TreeMap)
Q38. Difference between ArrayList and LinkedList.
• ArrayList: Uses dynamic array, faster random access,
slower insertion/deletion.
• LinkedList: Uses doubly linked list, faster
insertion/deletion, slower random access.
Q39. Difference between HashSet and TreeSet.
• HashSet: Stores elements in random order, allows null,
faster.
• TreeSet: Stores elements in sorted order, no null allowed,
slower.
Q40. Difference between HashMap and Hashtable.
• HashMap: Non-synchronized, allows one null key +
multiple null values. Faster.
• Hashtable: Synchronized, doesn’t allow any null key or
value. Slower.
Q41. Difference between ConcurrentHashMap and HashMap.
• HashMap: Not thread-safe.
• ConcurrentHashMap: Thread-safe with better
performance (uses lock stripping).
Q42. Explain fail-fast and fail-safe iterators in Java.
• Fail-fast: Immediately throws
ConcurrentModificationException if collection is modified
(e.g., Iterator of ArrayList).
• Fail-safe: Works on a copy, so no exception (e.g., Iterator of
ConcurrentHashMap).
Q43. Difference between Iterator and ListIterator.
• Iterator: Traverses forward only, works on all collections.
• ListIterator: Traverses forward & backward, works only on
List (ArrayList, LinkedList).
Q44. What is the difference between Comparable and
Comparator?
• Comparable: Defines default sorting (implements
compareTo).
• Comparator: Defines custom sorting (implements
compare).
Multithreading & Concurrency
Q45. Difference between process and thread.
• Process: Independent execution unit with separate
memory.
• Thread: Lightweight process, shares memory with other
threads.
Q46. What is the lifecycle of a thread in Java?
1. New
2. Runnable
3. Running
4. Waiting/Timed Waiting
5. Terminated
Q47. What are daemon threads in Java?
• Background threads that provide services (e.g., Garbage
Collector).
• JVM exits when only daemon threads are running.
Q48. Difference between wait() and sleep().
• wait(): Releases lock, used in synchronization, called on
objects.
• sleep(): Doesn’t release lock, just pauses execution, called
on threads.
Q49. Difference between synchronized method and
synchronized block.
• Synchronized method: Locks entire method → less
efficient.
• Synchronized block: Locks only specific code → more
efficient.
Q50. What is the difference between notify() and notifyAll()?
• notify(): Wakes up one waiting thread.
• notifyAll(): Wakes up all waiting threads.
Q51. What is the difference between ExecutorService and
traditional thread creation?
• Traditional: Uses Thread class → less scalable.
• ExecutorService: Manages thread pool, reuses threads →
more efficient.
Advanced Java
Q52. What is the difference between JDBC Statement,
PreparedStatement, and CallableStatement?
• Statement: Executes static SQL queries.
• PreparedStatement: Precompiled SQL, faster, prevents SQL
injection.
• CallableStatement: Used to call stored procedures.
Q53. What are Java 8 features like streams, lambda
expressions, and functional interfaces?
• Lambda expressions: Shorter way to write anonymous
functions.
• Streams API: Process collections in functional style.
• Functional interfaces: Interfaces with a single abstract
method (e.g., Runnable, Comparator).
Q54. Explain garbage collection in Java. What are different GC
algorithms?
• JVM automatically deletes unused objects to free memory.
• Algorithms: Mark and Sweep, Generational GC, G1 GC.
Q55. Difference between String, StringBuffer, and
StringBuilder.
• String: Immutable, thread-safe.
• StringBuffer: Mutable, thread-safe (synchronized).
• StringBuilder: Mutable, not thread-safe, faster than
StringBuffer.
Q56. What are design patterns in Java? Name a few commonly
used ones.
• Design patterns: Standard solutions to common software
design problems.
• Common ones:
o Creational: Singleton, Factory, Builder.
o Structural: Adapter, Decorator.
o Behavioral: Observer, Strategy.