1. Why is Java a platform-independent language?
Ans: Java is platform-independent because of the
Java Virtual Machine (JVM). Java code is compiled into bytecode, which can run on any system with
a JVM, regardless of the underlying OS. So, "Write Once, Run Anywhere."
Follow-up: What is bytecode? Ans: Bytecode is an intermediate code generated by the Java compiler.
It is not machine-specific but understood by the JVM.
2. Why is Java not a pure object-oriented language? Ans: Java is not 100% object-oriented because
it supports primitive data types (int, char, etc.) which are not objects.
3. Difference between Heap and Stack Memory in Java. How Java uses them? Ans:
• Stack Memory: Stores method calls and local variables. It's fast and organized in LIFO.
• Heap Memory: Stores objects and instance variables. It's managed by the Garbage Collector.
Java uses stack for execution (method calls) and heap for storing objects.
4. Can Java be said to be a complete object-oriented programming language? Ans: No, because of
the presence of primitive types. Pure OOP requires everything to be an object.
5. How is Java different from C++? Ans:
• Java is platform-independent; C++ is not.
• Java has no pointers; C++ does.
• Java has automatic garbage collection; C++ requires manual memory management.
• Java doesn't support multiple inheritance with classes (uses interfaces).
6. Why does Java not use pointers? Ans: Pointers are removed in Java to make it secure and simple.
They can lead to memory leaks and unsafe code.
7. What do you understand by an instance variable and a local variable? Ans:
• Instance Variable: Declared inside a class, outside methods. Each object has its own copy.
• Local Variable: Declared inside methods or blocks. Only accessible within that scope.
8. What are default values assigned in Java? Ans: Only instance and static variables have default
values.
• int = 0, double = 0.0, boolean = false, Object = null. Local variables don’t have default
values.
9. What do you mean by data encapsulation? Ans: Wrapping data (variables) and code (methods)
together in a single unit (class) and restricting access using access modifiers. Promotes data hiding
and security.
10. Tell us something about JIT Compiler. Ans: JIT (Just-In-Time) compiler improves performance. It
compiles bytecode into native machine code at runtime, making execution faster.
11. Difference between equals() and == operator? Ans:
• == compares reference (memory address).
• equals() compares content/values (if overridden properly).
12. How is an infinite loop declared in Java? Ans: while(true){} or for(;;){}
13. Constructor Overloading Concept? Ans: Defining multiple constructors in a class with different
parameters.
class A {
A() {}
A(int x) {}
A(String s, int x) {}
14. Define Copy Constructor in Java. Ans: Java doesn’t have an inbuilt copy constructor like C++, but
we can define one:
class A {
int x;
A(A obj) {
this.x = obj.x;
15. Can the main() method be overloaded? Ans: Yes, main can be overloaded, but JVM always calls
the one with public static void main(String[] args).
16. Method Overloading vs Overriding
• Overloading: Same method name, different parameters (compile-time).
• Overriding: Child class redefines parent method (runtime).
17. Single try and multiple catch blocks? Ans: Yes, Java allows multiple catch blocks with one try. The
most specific exception must be caught first.
try {
// code
} catch (ArithmeticException e) {
} catch (Exception e) {
18. Use of final keyword?
• final variable: Constant (value cannot change).
• final method: Cannot be overridden.
• final class: Cannot be extended.
19. Difference: final, finally, finalize
• final: Keyword for constants, methods, and classes.
• finally: Block always executed after try/catch.
• finalize(): Method called before object is garbage collected (rarely used now).
20. When finally block is not executed? Ans: If JVM crashes or System.exit() is called inside try or
catch.
21. Output-Based Questions Ans: Carefully check for:
• Scope of variables
• Static vs instance
• Inheritance flow
• Output due to overloading/overriding
22. When to use super keyword? Ans:
• Call parent class constructor.
• Access parent class methods/variables.
super();
super.method();
23. Can static methods be overloaded? Ans: Yes. Static methods can have different parameter lists.
24. Why is the main() method static? Ans: Because JVM does not create an object to call it. Static
allows it to run without instantiating the class.
25. Can static methods be overridden? Ans: No. They belong to class, not objects. But can be hidden
if redefined in subclass (called method hiding).
26. Static methods vs variables vs classes
• Static Method: Belongs to class, no need to create object.
• Static Variable: Shared among all objects.
• Static Class: Only nested classes can be static.
27. Main objective of garbage collection? Ans: Free up memory by deleting unused objects
automatically.
28. What is a ClassLoader? Ans: Part of JVM that loads class files during runtime into memory.
29. Which memory is cleaned in GC? Ans: Heap memory. Stack is not handled by GC.
30. Shallow vs Deep Copy
• Shallow Copy: Copies object reference (same memory).
• Deep Copy: Creates a new object with copied values.
Java Interview Questions and Answers (Quick Recall + Explanation Friendly)
Core Java Concepts
1. What are the main features of Java?
Ans: Java is known for its powerful and robust features like Platform Independence, Object-Oriented
Programming, Automatic Garbage Collection, Multithreading, Security, High Performance via JIT
compiler, and Rich Standard Libraries, which together make it highly suitable for modern application
development.
Follow-up: Which feature makes Java suitable for web-based applications?
Ans: Java’s platform independence and strong security model make it ideal for web-based
applications.
2. Explain the concept of platform independence in Java.
Ans: Platform independence means that Java code written once can run anywhere. This is achieved
because Java programs are compiled into bytecode, which can be executed on any machine having a
Java Virtual Machine (JVM), regardless of the operating system.
3. What is the difference between JDK, JRE, and JVM?
Ans:
• JDK (Java Development Kit): Contains JRE + development tools like compiler and debugger
to write and compile code.
• JRE (Java Runtime Environment): Provides JVM + libraries required to run Java programs.
• JVM (Java Virtual Machine): The engine that executes Java bytecode and makes the code
platform-independent.
Follow-up: Can we run Java programs without JDK?
Ans: Yes, if only execution is needed and the code is already compiled, the JRE is sufficient.
Object-Oriented Programming (OOP)
4. What are the four main principles of OOP?
Ans:
1. Encapsulation: Bundling of data and methods into a single unit (class) and restricting direct
access to some components.
2. Abstraction: Hiding internal implementation and showing only essential details.
3. Inheritance: Acquiring properties and behaviors from a parent class.
4. Polymorphism: Ability of an object to take many forms—same method name with different
implementations.
5. Difference between interface and abstract class?
Ans: An interface is a contract that contains only abstract methods (Java 8+ allows default and static
methods), while an abstract class can have both abstract and non-abstract methods, constructors,
and instance variables. Abstract classes provide partial implementation; interfaces are pure
abstraction.
Follow-up: Can an abstract class implement an interface?
Ans: Yes, an abstract class can implement an interface but must implement the interface methods or
remain abstract.
6. How does Java achieve encapsulation?
Ans: Java achieves encapsulation by declaring variables private and providing public getters and
setters. This hides the internal state of the object and controls its modification.
Multithreading
7. What is a thread in Java, and how is it created?
Ans: A thread is the smallest unit of a process that can run concurrently with other threads. In Java,
threads can be created by extending the Thread class or implementing the Runnable interface. It
allows multiple operations to run in parallel.
Follow-up: Which method is better—Thread or Runnable?
Ans: Implementing Runnable is better because it supports multiple inheritance and resource sharing.
8. Difference between synchronized and volatile?
Ans:
• synchronized ensures that only one thread can access a block or method at a time to avoid
data inconsistency.
• volatile ensures that changes to a variable are visible to all threads by reading/writing from
main memory instead of thread cache.
9. What are the benefits of multithreading?
Ans:
• Enhances performance by executing multiple tasks simultaneously
• Efficient CPU utilization
• Improves application responsiveness, especially in GUIs
• Useful in real-time systems and background task handling
Exception Handling
10. Difference between checked and unchecked exceptions?
Ans:
• Checked exceptions are checked at compile time and must be handled (e.g., IOException,
SQLException).
• Unchecked exceptions occur at runtime and are not mandatory to handle (e.g.,
NullPointerException, ArithmeticException).
11. How do you create a custom exception in Java?
Ans: Create a class that extends either Exception (for checked) or RuntimeException (for unchecked),
and use the constructor to pass custom messages.
class MyException extends Exception {
MyException(String msg) {
super(msg);
12. Explain try-catch-finally block.
Ans: A try block contains code that might throw an exception. A catch block handles specific
exceptions. A finally block always executes after try/catch, used for cleanup code like closing files or
connections.
Follow-up: Can we have only try block?
Ans: No, try must be followed by at least one catch or finally block.
Java Collections Framework
13. Difference between List, Set, and Map?
Ans:
• List: Ordered collection that allows duplicates (e.g., ArrayList).
• Set: Unordered collection that doesn’t allow duplicates (e.g., HashSet).
• Map: Stores key-value pairs; keys are unique (e.g., HashMap).
14. How does HashMap work internally?
Ans: HashMap uses a hash function to convert keys into hash codes. These codes determine the
index in an internal array (buckets). If collisions occur (same index), entries are stored in a linked list
or a tree (Java 8+).
Follow-up: What happens if two keys have same hashCode?
Ans: They are stored in the same bucket using a linked list or red-black tree.
15. Advantages of ArrayList over LinkedList?
Ans: ArrayList provides fast random access using indexing, better cache locality, and less memory
overhead compared to LinkedList, which is better for frequent insertions and deletions.
Follow-up: When to use LinkedList?
Ans: When there are frequent insertions or deletions in the middle of the list.
Java 8 Features
16. What are lambda expressions and how are they used?
Ans: Lambda expressions enable us to write functional-style code by providing a concise way to
represent anonymous methods. They are used mainly with functional interfaces.
(a, b) -> a + b
This allows writing inline behavior for methods like filter, map, etc.
17. Explain Stream API and its benefits.
Ans: Stream API allows functional-style operations on collections. It supports operations like filter,
map, reduce. Benefits include cleaner code, parallel processing, and lazy evaluation for performance.
list.stream().filter(x -> x > 10).map(x -> x*2).collect(Collectors.toList());
18. Purpose of Optional class?
Ans: Optional is a container that may or may not hold a non-null value. It’s used to avoid
NullPointerException by providing methods to safely access the value.
Optional<String> name = Optional.ofNullable(user.getName());
name.orElse("Unknown");
31. Why are strings immutable in Java apart from security reasons? Ans: Strings are immutable to
ensure thread safety, caching efficiency (like in String pool), safe class loading, and to avoid
unintended changes (since strings are often used as keys in collections). Immutability leads to better
memory optimization and integrity of application data.
Follow-up: How does immutability help with string pooling? Ans: Since strings don’t change after
creation, the JVM can safely store one copy in the pool and reuse it across the application, saving
memory.
32. What is a Singleton class in Java? How to implement it? Ans: A Singleton class ensures that only
one instance of the class exists throughout the JVM. It is used in logging, caching, and configuration.
Implementation (Eager):
class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
Follow-up: How do you implement a lazy-initialized thread-safe singleton? Ans: Use double-checked
locking with synchronization.
33. Which of the below generates a compile-time error? State the reason. Ans: This is a contextual
question. A compile-time error typically occurs when:
• A method has an incorrect return type.
• There’s a static context calling a non-static method.
• Access modifiers or data types are wrongly declared.
Follow-up: Can we overload methods with only different return types? Ans: No. Java doesn't allow
method overloading by return type alone.
34. Difference between String, StringBuffer, and StringBuilder? Ans:
• String: Immutable, thread-safe, creates a new object on every modification.
• StringBuffer: Mutable, thread-safe, slower in single-threaded.
• StringBuilder: Mutable, not thread-safe, faster for single-threaded modifications.
Follow-up: Which should be used in a multithreaded environment? Ans: StringBuffer because it's
synchronized.
35. Differences between Interface and Abstract Class (with properties)?
Feature Interface Abstract Class
Methods Abstract (default, static allowed) Abstract + concrete
Constructors Not allowed Allowed
Multiple Inheritance Yes No
Variables static final only instance, static, final allowed
Follow-up: Can a class implement multiple interfaces? Ans: Yes. Java supports multiple interface
inheritance.
36. Is this program giving compile-time error? (Need code) Ans: Generally, compile-time errors arise
from missing return statements, wrong method names, or uninitialized variables.
Follow-up: What happens if a method doesn't return a value but has a return type? Ans: Compiler
error: "missing return statement."
37. What is a Comparator in Java? Ans: Comparator is an interface used to define custom sorting
logic, especially when natural ordering isn't suitable.
Comparator<Employee> bySalary = (e1, e2) -> e1.salary - e2.salary;
Follow-up: What’s the difference between Comparable and Comparator? Ans: Comparable is used
for natural ordering within a class. Comparator is external and allows multiple custom sortings.
38. Can static and private methods be overridden? Ans: No. Static methods are class-level and can
only be hidden. Private methods are not inherited, so cannot be overridden.
Follow-up: What is method hiding? Ans: Defining a static method with the same signature in a
subclass. It doesn’t override but hides the superclass method.
39. Difference between HashSet and TreeSet? Ans:
• HashSet: No order, allows null, fast.
• TreeSet: Sorted, no nulls, slower due to tree structure.
Follow-up: Which uses more memory? Ans: TreeSet uses more memory due to tree node storage.
40. Why use char[] over String for storing passwords? Ans: Strings are immutable and stored in
memory until garbage collected. char[] can be wiped manually for better security.
Follow-up: How can char[] be cleared? Ans: Use Arrays.fill(charArray, '\0') to wipe it.
41. What do we get in the JDK file? Ans: The JDK includes:
• JRE (libraries + JVM)
• Development tools like compiler (javac), debugger (jdb), and other utilities (jar, javadoc)
Follow-up: Do we need both JDK and JRE to run Java apps? Ans: JRE is enough to run, JDK is required
to compile.
42. Differences between JVM, JRE, and JDK? (Same as Q3 – already explained.)
Follow-up: Is JVM platform-independent? Ans: No. JVM is platform-specific. Bytecode is platform-
independent.
43. HashMap vs Hashtable Ans:
• HashMap: Not thread-safe, allows nulls, fast.
• Hashtable: Thread-safe, no null keys or values, legacy.
Follow-up: Which should be used in multi-threading? Ans: Use ConcurrentHashMap instead of
Hashtable for better performance.
44. Importance of Reflection in Java? Ans: Reflection allows runtime access to class metadata. It is
used in frameworks like Spring, JUnit, Hibernate.
Follow-up: Is reflection slow? Ans: Yes, it’s slower and can break encapsulation.
45. Ways to use threads in Java? Ans:
• Extend Thread class
• Implement Runnable
• Use Callable + Future
• Use ExecutorService
Follow-up: Why is Executor framework preferred? Ans: It manages thread pooling, task scheduling,
and lifecycle more efficiently.
46. Thread Priorities in Java? Ans: Priority ranges from 1 to 10. Default is 5. Thread with higher
priority gets more CPU time (not guaranteed).
Follow-up: Can we rely on thread priority for scheduling? Ans: No. It's platform dependent.
47. Program vs Process? Ans:
• Program: Passive code on disk.
• Process: Active instance in memory with execution context.
Follow-up: Can multiple processes run the same program? Ans: Yes. Each has separate memory
space.
48. throw vs throws Ans:
• throw: Used to throw a specific exception.
• throws: Declares exceptions a method might throw.
Follow-up: Can we use both together? Ans: Yes. Method declares with throws, body uses throw.
49. Constructor vs Method Ans: Constructor is invoked at object creation, has no return type.
Methods define behaviors, can be called anytime.
Follow-up: Can we overload constructors? Ans: Yes. Constructor overloading is common.
50. Output-based program (Need actual code) (Answer depends on shared code snippet.)
Follow-up: If code has multiple main() methods, which gets executed? Ans: Only the one with
signature public static void main(String[] args) is called by JVM.