Java Interview Questions (240) – Easy & Clear Explanation
1) What are static blocks and static initializers in Java?
Answer:
Static blocks in Java are used to initialize static variables. They run automatically only once when the class is
loaded, even before any object or constructor runs.
Example:
class Example {
static int value;
static {
value = 10;
[Link]("Static block called");
}
}
2) How to call one constructor from another constructor?
Answer:
To call one constructor from another within the same class, use this() keyword.
Rules:
this() must be the first statement in the constructor.
You can’t use multiple this() in one constructor.
Example:
class Test {
Test() {
this(5);
[Link]("Default constructor");
}
Test(int x) {
[Link]("Parameterized constructor");
}
}
3) What is method overriding in Java?
Answer:
If a subclass defines a method with the same name, return type, and parameters as its superclass, then the
method is said to be overridden.
Use: To provide different behavior for the same method in subclass.
Example:
class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}
4) What is the use of super keyword in Java?
Answer:
The super keyword is used to access:
Superclass constructor
Superclass methods
Superclass variables
Note: super() must be the first statement if used in a constructor.
Example:
class A {
int x = 5;
}
class B extends A {
int x = 10;
void show() {
[Link](super.x); // prints 5
}
}
5) Difference between Method Overloading and Method Overriding
Feature Method Overloading Method Overriding
Location Same class Superclass & Subclass
Parameters Must be different Must be same
Return type Can be different Must be same
Polymorphism Compile time (Static) Runtime (Dynamic)
Inheritance Not required Required
6) Difference between Abstract Class and Interface
Feature Interface Abstract Class
Abstract + normal
Methods Only abstract
methods
Variables public static final Can be non-final
Access Modifiers Only public public, protected, etc.
Multiple Inheritance Supported Not supported
Keyword implements extends
7) Why is Java platform independent?
Answer:
Java source code is compiled into bytecode (.class file).
This bytecode runs on any OS using the Java Virtual Machine (JVM), making Java platform-independent.
8) What is method overloading in Java?
Answer:
When a class has multiple methods with the same name but different parameters, it is called method
overloading.
Use: To perform similar tasks with different inputs.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
}
9) What is the difference between C++ and Java?
Feature Java C++
Platform Independent Dependent
Not
Pointers Supported
supported
Garbage Collection Yes No
Operator Overload Not allowed Allowed
Multithreading Supported Not built-in
Not
Global Variables Supported
supported
10) What is JIT Compiler?
Answer:
JIT stands for Just-In-Time compiler. It converts Java bytecode into native machine code at runtime, improving
performance.
11) What is bytecode in Java?
Answer:
Bytecode is the compiled form of Java code. It is a .class file that is understood only by the JVM, not by the
operating system.
12) Difference between this() and super()
Feature this() super()
Calling constructor of
Used for Calling constructor of same class
superclass
Must be first
Placement Must be first statement
statement
13) What is a class in Java?
Answer:
A class is a template or blueprint for creating objects. It contains variables and methods.
Example:
public class Car {
int speed;
void drive() {
[Link]("Car is moving");
}
}
14) What is an object in Java?
Answer:
An object is an instance of a class. It represents a real-world entity like a car, pen, etc.
Example:
Car c = new Car(); // 'c' is the object
15) What is a method in Java?
Answer:
A method is a block of code that performs a specific task. It can have parameters and a return type.
Syntax:
returnType methodName(parameters) {
// code
}
16) What is encapsulation?
Answer:
Encapsulation means wrapping data (variables) and methods into a single unit — a class.
It keeps data safe from outside access.
Use private variables + public getters/setters.
17) Why is main() method public static void in Java?
public: So JVM can access it.
static: JVM calls it without creating an object.
void: It returns nothing.
Signature:
public static void main(String[] args) { }
18) Explain main() method in Java.
Answer:
It is the starting point of any Java program.
Java program cannot run without a main() method.
19) What is a constructor in Java?
Answer:
Constructor is a special method used to initialize objects when they are created.
Types:
Default constructor (no parameters)
Parameterized constructor
Example:
class A {
A() { [Link]("Constructor called"); }
}
20) Difference between length and length()
Feature length (for arrays) length() (for strings)
Use To get array size To get number of characters
Example [Link] [Link]()
Q21. What is ASCII Code?
Answer:
ASCII means American Standard Code for Information Interchange. It includes characters from 0 to 255.
It only supports English characters, so in languages like C, you can only write code in English. You can’t use
other languages like Hindi, Telugu, etc.
Q22. What is Unicode?
Answer:
Unicode is a character set created to support all world languages.
In Java, Unicode is used to allow writing in any language.
It uses 16-bit encoding, so it can represent characters from 0 to 65,535.
Example: In Java, you can use Telugu or Hindi for comments or identifiers.
Q23. Difference between Character Constant and String Constant in Java
Character Constant String Constant
Enclosed in single quotes ' ' Enclosed in double quotes " "
Stores only one character Stores multiple characters
Example: 'A', '1' Example: "Hello", "123"
Q24. What are Constants in Java?
Answer:
Constants are fixed values which do not change during program execution.
In Java, we create constants using the final keyword.
final int number = 10;
final String message = "Hello";
Q25. Difference between >> and >>> in Java
>> is right shift operator with sign.
>>> is unsigned right shift, fills vacant bits with 0.
int a = 15;
a = a >> 2; // Moves bits right by 2
Q26. Java Coding Standards for Classes
Class names should start with Capital letters.
If name has multiple words, use CamelCase.
Examples:
Employee, EmployeeDetails, BankAccount
Q27. Java Coding Standards for Interfaces
Interface names should be Adjectives.
Start with uppercase.
Examples:
Runnable, Serializable, Comparable
Q28. Java Coding Standards for Methods
Start with lowercase letter.
Should be verbs.
Use camelCase if method has more than one word.
Examples:
getName(), printData(), calculateInterest()
Q29. Java Coding Standards for Variables
Should start with lowercase letter.
Use short and meaningful names.
Use camelCase for multiple words.
Examples:
salary, empName, totalMarks
Q30. Java Coding Standards for Constants
Constants are written in uppercase.
Words are separated with underscore _.
Examples:
MAX_VALUE, PI, MIN_SIZE
Q31. Difference between Overriding and Overloading
Overriding Overloading
Method name and arguments are same Method name same, arguments different
Happens in subclass Happens in same class
Runtime polymorphism Compile-time polymorphism
Return type can be same or covariant Return type can be different
Uses inheritance Does not require inheritance
Q32. What is ‘IS-A’ relationship in Java?
Answer:
It means inheritance. It is created using the extends keyword.
It allows code reuse.
Example:
Car is a Vehicle, so Car extends Vehicle
Q33. What is ‘HAS-A’ relationship in Java?
Answer:
This is Composition or Aggregation.
It means one object contains another object.
Example:
Car has an Engine. We write: Engine engine = new Engine();
Q34. Difference between ‘IS-A’ and ‘HAS-A’ relationship
IS-A (Inheritance) HAS-A (Composition)
Uses extends keyword Uses object references
IS-A (Inheritance) HAS-A (Composition)
Example: Car is a Vehicle Example: Car has an Engine
Promotes code reuse Also promotes code reuse
Q35. What is instanceof operator in Java?
Answer:
instanceof checks if an object is of a specific type.
Integer a = new Integer(5);
[Link](a instanceof Integer); // true
If object is null → instanceof returns false.
Q36. What does null mean in Java?
Answer:
If a reference variable is not pointing to any object, it holds null.
Employee emp; // emp is null
Q37. Can we have multiple classes in one file?
Answer:
Yes, but only one class can be public.
If you try to make two classes public, you’ll get a compilation error.
Q38. Which access modifiers can be used for top-level classes?
Only two are allowed:
public → accessible everywhere
Default (no modifier) → accessible in same package
private and protected are not allowed.
Q39. What are packages in Java?
Answer:
Packages group related classes/interfaces together.
They help manage code and avoid name conflicts.
package [Link];
Q40. Can we have multiple package statements in a file?
Answer:
No. A Java file can have only one package statement.
If you try to add more, it will give compile-time error.
Q41) Can we define a package statement after the import statement in Java?
No, we can't.
• The package statement must always be the first line in a Java file.
• Only comments are allowed before it.
• The import statement should come after the package declaration.
Correct Format:
// comment allowed
package mypackage;
import [Link];
Q42) What are Identifiers in Java?
Identifiers are names used for:
• Classes
• Variables
• Methods
• Objects
Rules for Identifiers:
Rule No. Description
1 Must start with a letter, $, or _
2 Cannot start with a digit
3 Can include numbers after the first character
4 Cannot be a Java keyword
5 Java is case-sensitive (Var ≠ var)
6 Use meaningful names (ex: age, studentName)
Q43) What are Access Modifiers in Java?
Access modifiers control the visibility of classes, variables, and methods in Java.
• They help us apply encapsulation (hide internal details).
• There are 4 types of access modifiers in Java.
Q44) What is the difference between Access Specifiers and Access Modifiers?
• In Java, both terms are mostly used interchangeably.
• Officially, Java uses the term "Access Modifiers" (public, private, protected, default).
• Other keywords like final, static are called Non-Access Modifiers.
So, in Java:
Term Meaning
Access Modifiers Control access (e.g., public, private)
Non-Access Modifiers Define other properties (e.g., static, final, abstract)
Q45) What Access Modifiers are allowed for a Class?
Only two access levels are allowed for top-level classes:
Modifier Meaning
public The class is visible to all packages
default (no keyword) The class is visible only inside the same package
You cannot use private or protected for top-level classes.
Q46) What Access Modifiers can be used for Methods?
All 4 modifiers can be used for methods.
Access Modifiers in Java (Easy Table with Explanation)
Access modifiers control who can see or use a class, method, or variable.
We have 4 types:
Same Same Subclass in Different Non-subclass in Different
Modifier
Class Package Package Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default (no
Yes Yes No No
keyword)
private Yes No No No
Q47) What Access Modifiers can be used for Variables?
Same as methods — all 4 access levels are valid:
• public
• private
• protected
• default (no keyword)
Use according to your requirement and data sensitivity.
Q48) What is final Modifier in Java?
The final keyword means: "cannot be changed."
Used With Meaning
final class Cannot be extended (no subclass)
final method Cannot be overridden in child classes
Becomes a constant — value can't be
final variable
changed
final helps in security and integrity of code.
Q49) What is an Abstract Class in Java?
An abstract class is a partial blueprint.
• It can have abstract methods (without body).
• It can have normal methods (with body).
• You cannot create objects of abstract class.
• It is designed to be extended by subclasses.
Example:
abstract class Animal {
abstract void sound(); // no body
void eat() {
[Link]("eating");
}
}
Q50) Can we create a Constructor in an Abstract Class?
Yes, absolutely!
• Abstract classes can have constructors.
• You can't create an object of abstract class directly.
• But when a subclass object is created, it can call the constructor of the abstract class using super().
Q51) What is an Interface in Java?
An interface is like a contract in Java that contains abstract methods (methods without body).
• All methods in interface are public and abstract by default.
• A class implements an interface and provides code for the methods.
Example:
interface Animal {
void sound(); // abstract method
}
class Dog implements Animal {
public void sound() {
[Link]("Bark");
}
}
Q52) Difference between Abstract Class and Interface?
Feature Abstract Class Interface
Keyword used abstract interface
Can have concrete methods? Yes Yes (from Java 8)
Constructors allowed? Yes No
Variables Can have variables Only public static final
Multiple Inheritance No Yes
Purpose Partial abstraction Complete abstraction
Q53) What is Multiple Inheritance in Java?
Multiple Inheritance means a class inherits from more than one class.
• Java does not support multiple inheritance with classes (to avoid ambiguity).
• But it supports it using interfaces.
interface A { void show(); }
interface B { void display(); }
class C implements A, B {
public void show() { }
public void display() { }
}
Q54) What is Polymorphism in Java?
Polymorphism means "one thing behaves in many ways".
Types of Polymorphism:
Type Description
Compile-time (Static) Achieved by method overloading
Runtime (Dynamic) Achieved by method overriding
Q55) What is Method Overloading in Java?
Overloading means: same method name, but different parameters.
class Math {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Decided at compile time.
Q56) What is Method Overriding in Java?
Overriding means redefining a method of the parent class in the child class.
class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Bark"); } // overriding
}
Happens at runtime.
Q57) Difference Between Overloading and Overriding?
Feature Overloading Overriding
Method Name Same Same
Parameters Must be different Must be same
Class Relation Same class Parent-child relationship needed
Polymorphism Type Compile-time Runtime
Access Modifier Can be any Should not reduce visibility
Q58) What is Inheritance in Java?
Inheritance allows one class (child) to use the properties and methods of another class (parent).
• Keyword: extends
• Promotes code reusability
class Animal {
void eat() { [Link]("eating"); }
}
class Dog extends Animal {
void bark() { [Link]("barking"); }
}
Q59) What is Encapsulation in Java?
Encapsulation means:
• Hiding internal data using private access
• Exposing through getters and setters
class Student {
private int age;
public void setAge(int a) { age = a; }
public int getAge() { return age; }
}
Encapsulation = Data Hiding + Controlled Access
Q60) What is Abstraction in Java?
Abstraction means:
• Hiding implementation details
• Showing only functionality
Achieved using:
• Abstract Classes
• Interfaces
Q61) What are Static Variables and Methods?
• static keyword means belong to the class, not objects.
• Shared across all objects.
class Counter {
static int count = 0;
Counter() { count++; }
}
Q62) Difference between static and non-static?
Feature static non-static
Belongs to Class Object
Memory Once per class Every time per object
Access Can access only static members Can access all members
Example static int count; int age;
Q63) What is ‘this’ keyword in Java?
• this refers to current class object.
• Used to avoid confusion between instance variable and parameter.
class A {
int x;
A(int x) {
this.x = x;
}
}
Q64) What is the ‘super’ keyword?
• super refers to parent class object.
• Used to call parent class constructor or method.
class Animal {
void eat() { [Link]("eat"); }
}
class Dog extends Animal {
void eat() {
[Link](); // calls Animal's eat()
[Link]("bark");
}}
Q65) What is Constructor in Java?
Constructor is:
• A special method
• Same name as class
• No return type
• Called automatically when object is created
class A {
A() { [Link]("Constructor called"); }
}
Q66) Types of Constructors in Java?
Type Description
Default Constructor Created by Java if none is written
No-arg Constructor Constructor with no parameters
Parameterized Constructor with parameters
Copy Constructor Java doesn’t have built-in one, but can be created manually
Q67) What is the difference between Constructor and Method?
Feature Constructor Method
Name Same as class name Any name
Return type No return type Must have return type
Call Automatically called on object creation Manually called
Q68) Can Constructors be Overloaded?
Yes.
Just like methods, constructors can also be overloaded.
class A {
A() {}
A(int x) {}
}
Q69) Can Constructors be Inherited?
No.
• Constructors are not inherited in Java.
• But subclass constructors can call superclass constructors using super().
Q70) What is Object in Java?
An object is an instance of a class.
It has:
• State (variables)
• Behavior (methods)
class Dog {
void bark() { [Link]("bark"); }
}
class Main {
public static void main(String[] args) {
Dog d = new Dog(); // object created
[Link]();
}}
71) Can we write code after throw statement?
No, you can’t write any code after a throw statement because it immediately ends the execution of that
method. Writing code after throw gives a compile-time error called "unreachable code".
72) What is the use of throws keyword in Java?
The throws keyword tells that a method might throw an exception, and it is the caller’s responsibility to
handle it. It is used mainly for checked exceptions like IOException.
Example:
public void readFile() throws IOException {
// code that may throw IOException
}
73) Why is finally block more important than return statement?
If both return and finally are present, the finally block always runs first. Even if a return statement is executed,
the finally block runs before it returns the value.
74) When does finally block NOT run?
If you use [Link](0) (which shuts down JVM), the finally block will not run. In all other cases, it executes.
75) Can we use catch block for checked exceptions?
Yes, but only if there is a chance that the exception can happen. If not, the compiler will give an error.
76) What are User-defined Exceptions?
These are custom exceptions created by users to show specific errors. You can create them by extending:
• Exception → for checked exceptions
• RuntimeException → for unchecked exceptions
77) Can we rethrow an exception from a catch block?
Yes, you can rethrow an exception using throw in the catch block. For checked exceptions, you must declare it
using throws in the method signature.
78) Can we use nested try blocks in Java?
Yes, you can put one try block inside another. This is useful when each block may throw different exceptions.
79) What is the Throwable class in Java?
It is the parent class of all exceptions and errors in Java.
Important methods:
• printStackTrace() → prints full error
• getMessage() → prints error message
• toString() → prints type + message
80) When does ClassNotFoundException occur?
When Java can’t find a class at runtime using its name (like with reflection or [Link]), this exception is
thrown.
81) When does NoClassDefFoundError occur?
When a class was available during compile-time but missing during runtime. Common reasons:
• Wrong classpath
• Class deleted or renamed
Java Threads – Simple Q&A
82) What is a Process?
A process is a program in execution. It has its own memory. It's heavier than a thread.
83) What is a Thread?
A thread is a lightweight unit of execution inside a process. It shares memory with other threads of the same
process.
84) Difference Between Process and Thread
Feature Process Thread
Weight Heavy Light
Memory Separate for each process Shared between threads
Cost More expensive Less expensive
85) What is Multitasking?
Multitasking means running multiple tasks at the same time.
Example: Listening to music and typing in Word.
86) Types of Multitasking
1. Process-based: Multiple programs (Word + Chrome)
2. Thread-based: Multiple threads in the same program (printing + typing)
87) Benefits of Multithreading
• Efficient CPU usage
• Faster program execution
• Tasks can run simultaneously
88) What is a Thread in Java?
• It's a path of execution.
• Java threads are objects of Thread class.
• All threads share code and memory.
89) Java APIs for Threading
• Thread class
• Runnable interface
• Object class methods: wait(), notify(), etc.
• [Link] package
90) What is the Main Thread?
It is the first thread that runs when a Java program starts. All other threads are started from it.
91) How to Create Threads in Java?
Two ways:
1. Extend Thread class
2. Implement Runnable interface
92) Creating Thread by Runnable
class MyClass implements Runnable {
public void run() {
// task
}
}
93) Creating Thread by Extending Thread
class MyClass extends Thread {
public void run() {
// task
}
}
94) Which is better: Extending Thread or Implementing Runnable?
Runnable is better because:
• You can extend another class (Java supports single inheritance)
• It is more flexible
95) What is a Thread Scheduler?
It decides which thread to run next from the Runnable threads. It uses:
• Priority
• Round Robin (turn-by-turn)
96) Thread Lifecycle in Java
State Meaning
New Thread is created but not started
Runnable Ready to run (waiting for CPU)
Running Actively executing
Waiting Waiting for another thread or condition
Terminated Finished execution
97) Can we restart a dead thread?
No, once a thread is finished (dead), you cannot restart it. Calling start() again will throw an error.
98) Can one thread block another?
No, a thread cannot block another directly. But it can make itself wait (using sleep, wait, etc.)
99) Can we start a thread twice?
No, starting the same thread twice using start() causes IllegalThreadStateException.
100) What happens if run() is not overridden?
The default run() method of the Thread class will run, but it does nothing, so your thread will do nothing.
101) Can we overload the run() method?
Yes, but only the no-argument version of run() is called by the thread. Others you must call manually.
102) What is a Lock in Java?
A lock is used to control access to a shared resource.
Only one thread can acquire a lock on an object at a time.
103) Ways to Synchronize in Java
1. Synchronized method
public synchronized void method() {}
2. Synchronized block
synchronized(this) {
// code
}
104) What is a Synchronized Method?
A method where only one thread can execute at a time for an object.
It automatically acquires and releases the lock on the object.
105) When to Use Synchronized Method?
Use it when:
• Multiple threads are changing shared data
• You want to avoid inconsistent data or race conditions
106) Can two threads execute two synchronized methods at the same time on the same object?
No, if one thread is running a synchronized method, the other must wait — even for a different synchronized
method.
107) Can the same thread access other synchronized methods of the same object?
Yes, the thread already has the lock, so it can enter other synchronized methods of the same object.
108) When do we use synchronized methods in Java?
We use synchronized methods when multiple threads are trying to access and modify the same object.
Synchronizing ensures that only one thread at a time can access the method.
109) Can other threads execute synchronized methods while one thread is already inside a synchronized
method?
No, other threads cannot execute synchronized methods on the same object until the current thread releases
the lock.
110) Can the same thread access other synchronized methods of the object?
Yes, the same thread can call other synchronized methods of the object if it already holds the lock.
111) What are synchronized blocks in Java?
Synchronized blocks allow only a portion of code to be synchronized instead of the entire method. This
improves performance.
Syntax:
synchronized (object) {
// synchronized code
}
112) When to use synchronized blocks?
When only a few lines of code require synchronization, it's better to use a synchronized block. This improves
performance by reducing the waiting time of threads.
113) What is a class level lock?
Locking the class itself instead of an object. It uses [Link] to get a lock on the class.
114) Can we synchronize static methods in Java?
Yes, static methods can be synchronized. It acquires a lock on the class, not on the instance.
115) Can we use synchronized blocks on primitive data types?
No, synchronized blocks work only on objects. Using it on primitives will cause a compile-time error.
116) What are thread priorities?
Thread priorities help the thread scheduler decide which thread to run first if multiple threads are waiting.
117) Types of thread priorities:
Thread.MIN_PRIORITY = 1;
Thread.NORM_PRIORITY = 5;
Thread.MAX_PRIORITY = 10;
118) How to set and get thread priority?
[Link](int value); // 1 to 10
[Link]();
Note: JVM may not always obey the priority set.
119) If two threads have the same priority, which runs first?
There is no guarantee. It depends on the thread scheduler. It can:
• Pick any thread
• Use time slicing
120) Methods to prevent thread execution:
1. yield()
2. join()
3. sleep()
121) What does yield() method do?
It pauses the current thread temporarily to allow other threads of the same priority to run.
[Link]();
Note: It does not release any lock.
122) Can a yielded thread run again?
Yes, but it depends on the thread scheduler. It's not guaranteed.
123) Purpose of join() method:
It lets one thread wait for another to finish. If thread A calls [Link](), thread A will wait until thread t2 finishes.
124) Purpose of sleep() method:
It pauses the current thread for a specific time.
[Link](1000); // 1 second
Note: It does not release any lock.
125) Does sleep() release the lock?
No, the lock is not released while a thread is sleeping.
126) Can sleep() cause another thread to sleep?
No, it only affects the current thread.
127) What is interrupt() method?
interrupt() politely asks a thread to stop. It sets the thread’s interrupted status to true.
If the thread is sleeping or waiting, it throws an InterruptedException.
128) What is inter-thread communication?
When threads share a task, they can communicate using:
• wait()
• notify()
• notifyAll()
129) Explain wait(), notify(), notifyAll():
• wait() → releases lock and waits
• notify() → wakes one waiting thread
• notifyAll() → wakes all waiting threads
All must be called within a synchronized block.
130) Why are wait(), notify(), notifyAll() in Object class?
Because threads call these methods on shared objects. So, they belong to Object class, not Thread class.
131) What is IllegalMonitorStateException?
Thrown when wait(), notify(), or notifyAll() are used outside of a synchronized block.
132) Do wait(), notify(), notifyAll() release the lock?
• wait() ✔ Yes
• notify() ✔ Yes (after completing synchronized block)
• notifyAll() ✔ Yes (after completing synchronized block)
133) Which methods release the lock?
Method Releases Lock?
yield() No
sleep() No
join() No
wait() Yes
notify() Yes
Method Releases Lock?
notifyAll() Yes
134) What are Thread Groups?
A Thread Group is a group of threads. We can manage multiple threads easily using groups. Threads in one
group can't affect threads in another group.
135) What are ThreadLocal variables?
ThreadLocal gives each thread its own copy of a variable. Useful when you don’t want threads to share data.
136) What are Daemon threads?
Daemon threads run in the background and support other threads. They end when all user threads finish.
Example: Garbage Collector.
137) How to make a thread Daemon?
[Link](true);
Note: Set before calling start() or it throws IllegalThreadStateException.
138) Can we make main() thread a Daemon?
No. The main thread is always non-daemon.
139) What are Nested Classes?
A class defined inside another class is a nested class. Types:
1. Static nested class
2. Non-static nested class (Inner class)
140) What are Inner Classes?
Inner classes are non-static nested classes. They include:
1. Local inner class
2. Member inner class
3. Anonymous inner class
141) Why to use nested classes in Java?
Purpose of nested classes:
1. Grouping related code – When a helper class is only used by one class, put it inside that class.
2. Better encapsulation – Inner classes can access private members of the outer class.
3. More readable code – Makes code cleaner by avoiding separate classes.
4. Hiding implementation – Hides logic that isn’t needed outside.
142) Explain about static nested classes in Java?
A static nested class is defined with the static keyword inside another class.
• It doesn’t need an object of the outer class to be created.
• It can’t access non-static members of the outer class.
143) How to instantiate static nested classes in Java?
You can create it without creating an object of the outer class.
Syntax:
[Link] obj = new [Link]();
144) What is method local inner class?
It is a class declared inside a method.
• Only accessible within that method.
• It gets destroyed when the method finishes.
145) Features of method local inner class?
1. No access modifiers like public, private, etc.
2. Can use final or abstract.
3. Cannot have static variables/methods.
4. Can only be used inside the method.
5. Can access only final or effectively final local variables.
6. Can be created inside loops or if-blocks.
146) What is an anonymous inner class in Java?
An inner class without a name used when:
• You need one-time implementation (like for interfaces or listeners).
• Created using new keyword.
Compiler creates a separate class file like Outer$[Link].
147) Restrictions on anonymous inner classes?
1. No constructor (no class name).
2. Can’t have static members.
3. Can’t define interfaces inside.
4. Can only create one instance of it.
148) Is this valid in Java: can we instantiate interface?
Runnable r = new Runnable() {
public void run() {}
};
This doesn't create an object of the interface, but of an anonymous class that implements the interface.
149) What is a member inner class in Java?
A non-static class inside another class.
• It can access all outer class members including private ones.
• Defined at class level (not inside method).
150) How to instantiate member inner class?
You need an instance of the outer class first.
Syntax:
[Link] obj = [Link] InnerClass();
151) How to do encapsulation in Java?
• Make variables private.
• Provide getter and setter methods to access them.
152) What are reference variables in Java?
A reference variable points to an object in memory.
Example:
Employee emp = new Employee();
• emp is the reference.
• A final reference can’t point to a new object.
153) Will compiler create default constructor if a parameterized constructor exists?
No. If you define any constructor, the compiler won’t create the default constructor automatically.
154) Can we have a method name same as class name?
Yes, but it's not recommended. It may confuse others.
You’ll get a warning, but it will compile.
155) Can we override constructors in Java?
No. Constructors can’t be overridden, only methods can.
156) Can static methods access instance variables?
No. Static methods cannot use non-static (instance) variables.
You’ll get a compile-time error.
157) How to access static members in Java?
Use the class name:
[Link]();
[Link](ClassName.STATIC_VAR);
158) Can we override static methods in Java?
No. You can declare the same static method in subclass, but it's not overriding. It’s method hiding.
159) Difference between object and reference?
• Object: Real memory of class created in heap.
• Reference: Variable pointing to that object.
You can have many references to one object.
160) Which gets garbage collected: object or reference?
Only the object gets garbage collected, not the reference variable.
161) How many times is finalize() method called? Who calls it?
• Called once by Garbage Collector before destroying the object.
• Used to clean up resources.
162) Can we pass objects as arguments in Java?
Technically, you pass the reference to the object, not the object itself.
163) What are wrapper classes in Java?
They convert primitive types to objects.
Example: int → Integer, char → Character
164) Types of wrapper classes in Java?
Primitive Wrapper Class
int Integer
boolean Boolean
char Character
float Float
long Long
double Double
byte Byte
short Short
165) What are transient variables in Java?
During serialization, if you don’t want to save a variable’s value, make it transient.
Example:
transient int id;
166) Can we serialize static variables?
No. Static variables are not part of an object, so they cannot be serialized.
167) What is type conversion in Java?
Changing one data type to another.
Example:
int a = 10;
long b = a; // widening (auto conversion)
168) What is automatic type conversion in Java?
Also called widening. Happens when:
• The destination type is larger.
• Types are compatible (e.g. int → float, char → int)
169) What is narrowing conversion in Java?
Manual conversion when destination type is smaller.
Use casting:
long a = 100;
byte b = (byte) a;
170) What is the use of import keyword in Java?
Used to bring classes or entire packages into your file.
Example:
import [Link];
It tells Java to use Scanner from that package.
171) Explain naming conventions for packages?
Answer: Sun suggested some rules for naming packages:
• Package names should be in all lowercase.
• Start with the reverse of your domain name (like [Link]), followed by the team or project name.
• Example: [Link].
172) What is classpath?
Answer: Classpath tells the JVM where to find your .class files.
• It can be set using the CLASSPATH environment variable.
• You can list multiple paths separated by ;.
• Example:
set CLASSPATH=C:\Program Files\Java\jdk1.6.0_25\bin;. ;
173) What is JAR?
Answer: JAR stands for Java Archive.
• It combines many .class files and resources into one file.
• Created using the [Link] tool.
• It also includes a manifest file that tells which class has the main() method.
174) What is the scope or life of instance variables?
Answer:
• Instance variables belong to objects.
• They are created when you use new.
• They exist until the object is deleted (garbage collected).
175) What is the scope or life of static variables?
Answer:
• Static variables belong to the class, not objects.
• They are created when the program starts.
• They stay until the program ends.
176) What is the scope or life of local variables in Java?
Answer:
• Local variables are created inside methods.
• They are created when the method runs.
• They are destroyed when the method finishes.
177) What is static import in Java?
Answer:
• From Java 5, you can import static members directly.
• This means you don’t need to use the class name every time.
• Example:
import static [Link];
import static [Link].*;
178) Can we define static methods in interfaces?
Answer:
• In old versions (before Java 8), static methods were not allowed in interfaces.
• Only public and abstract methods were allowed.
• It gave a compile-time error.
179) Define interface in Java?
Answer:
• An interface is a group of method declarations.
• It’s like a contract for what a class must do.
• It only has abstract methods (no body).
• A class uses implements keyword to use an interface.
180) What is the purpose of interface?
Answer:
• Interface defines what needs to be done, not how.
• It helps different classes work together even if they are unrelated.
• It supports dynamic behavior at runtime.
181) Features of interfaces in Java?
Answer:
1. All methods are abstract (even if you don’t write it).
2. All methods are public.
3. All variables are public, static, and final.
4. Interfaces can’t be instantiated.
5. Use implements to use them.
6. Interface can extend multiple interfaces.
7. You can define a class inside interface.
8. An interface can extend a class and another interface.
9. Interfaces support multiple inheritance.
182) What is enumeration in Java?
Answer:
• From Java 5, you can define enums (list of constant values).
• Declared using enum keyword.
• Example:
• public enum Days { SUN, MON, TUE, WED, THU, FRI, SAT }
183) Restrictions on enums?
Answer:
1. Enums cannot extend other classes.
2. You can’t create objects of enums.
3. You can add fields and methods, but only after constants.
184) What is field hiding in Java?
Answer:
• If both parent and child classes have same variable, the child hides the parent’s variable.
• To use parent’s variable, use super keyword.
185) What is Varargs in Java?
Answer:
• From Java 5, you can pass variable number of arguments using Varargs.
• Use ... in method parameter.
• Example:
public static void showNames(String... names)
186) Where are variables created in memory?
Answer:
• Variables are created in stack memory.
• When out of scope, they are removed automatically.
187) Can we use switch with Strings?
Answer:
• From Java 7, yes.
• Before Java 7, switch only supported int, char, byte, short, and enums.
188) How do we copy objects in Java?
Answer:
• You don’t copy objects directly.
• You copy references:
obj2 = obj1;
• Now both point to same object.
189) What is procedural or structured programming?
Answer:
• It focuses on procedures/functions.
• Top-down approach.
• Suitable for small problems.
• Example: C, Pascal.
190) What is object-oriented programming (OOP)?
Answer:
• Everything is treated as an object.
• Bottom-up approach.
• Objects talk to each other.
• Good for large applications.
191) Benefits of OOP?
Answer:
1. Easy to maintain
2. Reusable code
3. Easy to extend
4. Reliable
192) Difference between traditional and OOP languages?
Traditional Programming Object-Oriented Programming
Based on functions Based on objects
No encapsulation Supports encapsulation
Works well for small apps Works well for large apps
193) What are OOP concepts?
Answer:
1. Inheritance
2. Encapsulation
3. Polymorphism
194) What is Encapsulation?
Answer:
• Keeping data and code in one unit (class).
• It hides inner details.
• Supported using access modifiers (private, public, etc.)
195) What is Inheritance?
Answer:
• A class can inherit (reuse) features of another class.
• Use extends keyword.
• Helps in code reuse.
196) Importance of Inheritance in Java?
Answer:
• Reusability: No need to write same code again.
• Extendability: Add new features without changing existing code.
197) What is Polymorphism in Java?
Answer:
• One method behaves differently based on the object.
• Type of object, not reference, decides which method is called.
198) What is Collections Framework?
Answer:
• Set of classes/interfaces to manage groups of objects.
• Found in [Link] package.
• Benefits: High performance, reusability, less coding effort.
199) What is a Collection?
Answer:
• A container to store group of objects.
• Example: List of numbers, names, etc.
200) Difference between collection, Collection, and Collections?
Term Description
collection A group of objects
Collection Interface from Java API
Collections Utility class with methods like sort(), reverse() etc.
Sure! Here's the full content from 201 to 240 in simple English, with all questions exactly as they are and
answers expanded just a bit for better understanding. Tables are used where needed, and examples are
included for clarity:
201) What is the root interface in collection hierarchy?
In Java, Collection is the root interface of the Collection Framework. But technically, Iterable is at the top.
• Iterable is the top-most interface (used for for-each loops).
• Collection extends Iterable.
202) What are the main interfaces in the Java Collections Framework?
Answer:
The main interfaces are:
• Collection
• List
• Set
• SortedSet
• NavigableSet
• Queue
• Deque
• Map
• SortedMap
• NavigableMap
203) What is the difference between List and Set?
Feature List Set
Duplicates Allows duplicates Does not allow duplicates
Order Maintains insertion order Order not guaranteed (except LinkedHashSet)
Example ArrayList, LinkedList HashSet, TreeSet
204) What is the difference between HashSet and TreeSet?
Feature HashSet TreeSet
Order No specific order Sorted order
Performance Faster Slower
Null Elements Allows one null element Does not allow null elements
205) What is the difference between HashMap and TreeMap?
Feature HashMap TreeMap
Order No specific order Keys sorted in natural order
Null Key Allows one null key Does not allow null keys
Speed Faster Slower
206) What is the difference between Map and HashMap?
Answer:
• Map is an interface that defines key-value storage.
• HashMap is a class that implements the Map interface.
207) What is the difference between Iterator and ListIterator?
Feature Iterator ListIterator
Direction Forward only Forward and backward
Can modify Only remove Add, remove, and update
Works on All collections Only on Lists
208) What is the difference between fail-fast and fail-safe iterators?
Feature Fail-Fast Fail-Safe
Behavior Throws exception if structure is changed Works safely even if modified
Feature Fail-Fast Fail-Safe
Examples ArrayList, HashMap ConcurrentHashMap, CopyOnWriteArrayList
209) What is ConcurrentHashMap?
Answer:
A thread-safe version of HashMap.
Multiple threads can access it at the same time without locking the whole map. It's used in multi-threaded
applications.
210) What is the default size of ArrayList and HashMap?
Answer:
• ArrayList: 10
• HashMap: 16 (with load factor 0.75)
211) What is the load factor in HashMap?
Answer:
Load factor decides when to increase the map size.
Default is 0.75 – when 75% is full, the map resizes (rehashing).
212) What is the difference between ArrayList and LinkedList?
Feature ArrayList LinkedList
Access speed Fast for read Slow for read
Insert/Delete Slow in middle Fast in middle
Memory Less (uses arrays) More (stores links)
213) What is the difference between ArrayList and Vector?
Feature ArrayList Vector
Thread-safe No Yes
Speed Faster Slower (because of sync)
Legacy? No Yes (older class)
214) What is the difference between HashMap and Hashtable?
Feature HashMap Hashtable
Thread-safe No Yes
Null keys One null key allowed Not allowed
Performance Faster Slower
215) What is PriorityQueue in Java?
Answer:
A queue where elements are ordered by priority, not insertion.
Example:
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](30);
[Link](10);
[Link](20);
[Link](pq); // Output: [10, 30, 20] internally sorted
216) What is the use of Collections class in Java?
Answer:
It contains utility methods like:
• sort()
• reverse()
• max(), min(), etc.
Used to perform common operations on collections.
217) What is the difference between Collection and Collections?
Feature Collection (interface) Collections (class)
Type Interface Utility class
Use Represents group of objects Provides static methods like sort(), reverse()
218) What is the difference between Comparable and Comparator?
Feature Comparable Comparator
Method compareTo() compare()
Used For Natural sorting Custom sorting
Example [Link](list) [Link](list, comparator)
219) What is a LinkedHashMap?
Answer:
It is a subclass of HashMap that maintains insertion order.
It’s a combination of HashMap and linked list.
220) What is WeakHashMap?
Answer:
A map where keys are stored using weak references. If no reference to the key exists, it is garbage collected.
221) What is IdentityHashMap?
Answer:
It uses == (reference equality) instead of equals() for comparing keys.
Used when you want to compare object references, not values.
222) What is EnumSet in Java?
Answer:
A Set for use with enum types. It’s faster and more efficient than regular sets for enums.
223) What is NavigableMap in Java?
Answer:
An extension of SortedMap. It provides methods like:
• lowerKey()
• higherKey()
• ceilingKey(), etc.
Used for navigating through map keys.
224) What is BlockingQueue in Java?
It is a thread-safe queue used in multithreading.
It blocks the thread when:
• Queue is full (on put())
• Queue is empty (on take())
225) What is CopyOnWriteArrayList?
A thread-safe version of ArrayList.
It makes a new copy of the list on every update.
226) What is TreeMap?
It is a Map that keeps keys in sorted (ascending) order.
227) What is TreeSet?
A Set that stores elements in sorted order and does not allow duplicates.
228) What is the difference between Set and Map?
Feature Set Map
Stores Only values (no keys) Key-value pairs
Duplicate No duplicates Keys are unique, values can repeat
229) What is Deque in Java?
Answer:
A Deque (Double-Ended Queue) allows adding/removing from both ends.
230) What is the use of LinkedBlockingQueue?
Answer:
Used in producer-consumer problems.
Thread-safe and supports blocking on put() and take().
231) What is the purpose of Queue interface in Java?
Answer:
A queue stores elements in FIFO order (First In, First Out).
Used in messaging, scheduling tasks, etc.
232) What is the difference between HashSet and LinkedHashSet?
Feature HashSet LinkedHashSet
Order No order Maintains insertion order
Speed Faster Slightly slower
233) What is EnumMap in Java?
Answer:
A Map specially designed for enum keys. It’s fast and memory efficient.
234) What is BitSet in Java?
Used to handle binary flags efficiently (bits).
Each bit can be true/false (1/0).
235) What is difference between SynchronizedList and CopyOnWriteArrayList?
Feature SynchronizedList CopyOnWriteArrayList
Type Wrapper on regular list Separate thread-safe class
Performance Faster for write-heavy tasks Better for read-heavy tasks
236) What is BlockingDeque?
A thread-safe version of Deque.
Supports blocking operations from both ends.
237) What is Stack in Java?
A collection that works on LIFO (Last In First Out) principle.
Common methods: push(), pop(), peek().
238) What is Properties class in Java?
Used to handle .properties files (key-value pairs as strings).
Often used for config files.
239) What is difference between Array and ArrayList?
Feature Array ArrayList
Size Fixed Dynamic
Type Can store primitives Only objects
Methods No methods Many useful methods
240) What is Collection Framework in Java?
A standard architecture to store and manipulate groups of objects.
Includes interfaces, classes, and algorithms (like sort, search, etc.).