Java IQ by Pratap Sr
Java IQ by Pratap Sr
An abstract class is like a blueprint for other classes. It can have both normal (fully defined)
methods and abstract (only declared, not defined) methods. You cannot create an object of
an abstract class directly.
An interface is like a contract. It only has method declarations, and the class that
implements the interface must provide the actual implementation.
• Abstract class can have both abstract and normal methods, while interface only has
abstract methods (till Java 8).
• A class can extend only one abstract class but can implement multiple interfaces.
Example:
Polymorphism means "many forms." It allows one method to behave differently based on
how it is used.
o When multiple methods have the same name but different parameters.
Example:
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
2. Method Overriding (Runtime Polymorphism):
• When a subclass provides a new definition of a method from the parent class.
Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
3. Explain the concept of encapsulation and how it can be achieved in Java.
Encapsulation means hiding the details of a class and allowing controlled access.
How to Achieve Encapsulation?
1. Declare variables as private.
2. Provide public getter and setter methods to access and update data.
Example:
class Person {
private String name; // Private variable
public String getName() { // Getter method
return name;
}
public void setName(String newName) { // Setter method
name = newName;
}
}
4. What is method hiding in Java?
Method Hiding happens when a static method in a child class has the same name as a static
method in the parent class. Unlike method overriding, here the method is hidden, not
overridden.
Example:
class Parent {
static void show() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void show() {
System.out.println("Static method in Child");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.show(); // Output: Static method in Parent (Method
Hiding)
}
}
5.Explain the concept of composition and aggregation in Java with examples.
Both describe relationships between objects, but they have different levels of dependency.
Composition (Strong Relationship - "Has-A")
• One object owns another, and if the owner is destroyed, the child object is also
destroyed.
• Example: A Car has an Engine. If the car is destroyed, the engine is useless.
class Engine {
void start() {
System.out.println("Engine starting...");
}
}
class Car {
private final Engine engine = new Engine(); //Strong
relationship
void startCar() {
engine.start();
}
}
Aggregation (Weak Relationship - "Has-A")
• Example: A Student has a College, but even if a student leaves, the college still exists.
class College {
String name;
College(String name) {
this.name = name;
}
}
class Student {
String studentName;
College college;
Abstraction means hiding unnecessary details and showing only important features.
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
JVM and Performance
1. What Are the Different Garbage Collection Algorithms in Java?
Garbage Collection (GC) in Java automatically removes unused objects to free up memory.
The main GC algorithms are:
1. Serial GC → Best for small applications; uses a single thread for GC.
2. Parallel GC (Throughput Collector) → Uses multiple threads to speed up GC; best for
multi-core machines.
4. G1 (Garbage First) GC → Default in Java 9+; divides heap into regions and cleans up
the most garbage-filled regions first.
Minor GC
1. Method Area → Stores class metadata, static variables, and method code.
2. Heap Memory → Stores objects. Divided into Young Generation (Eden, Survivor
Spaces) and Old Generation.
3. Stack Memory → Stores method execution details, local variables, and function calls.
Class loading is the process where JVM loads .class files into memory when needed. It
follows these steps:
3. Initialization → Runs static initializers (static {} blocks) and initializes static variables.
Example:
A memory leak happens when objects that are no longer needed remain in memory
because references to them still exist.
Common Causes:
• Using static collections (like List or Map) that hold objects indefinitely.
• Use memory profiling tools like VisualVM, JProfiler, or Eclipse MAT to detect leaks.
System.gc() requests garbage collection, but it does not guarantee it will run immediately.
JVM decides whether to execute it based on optimization.
Better Approach:
finalize() Method:
• A method in Object class that JVM calls before an object is garbage collected.
• Not recommended in modern Java because it’s unpredictable and deprecated in Java
9.
Example:
• Instead of finalize(), it's better to create a custom cleanup method and call it
manually.
• Example:
class Resource {
void cleanUp() {
System.out.println("Cleaning up resources...");
}
}
8. Difference Between JDK, JRE, and JVM
Heap Memory
Stack Memory
• Stores method calls, local variables, and references to objects in the heap.
class Demo {
int x = 10; // Stored in Heap
void show() {
int y = 20; // Stored in Stack
}
}
Exception Handling
1. What is an exception in Java?
What: An exception is an event that occurs during program execution and disrupts
the normal flow of instructions.
Why: It helps in handling runtime errors and prevents abnormal termination of
programs.
Example:
int a = 5, b = 0;
int result = a / b; // This will throw ArithmeticException
What is an Exception?
An exception is an error that happens during program execution and disrupts the
normal flow of the program.
What is a Checked Exception?
Checked exceptions are the ones that Java forces you to handle at compile-time. If
you don’t handle them using try-catch or declare them with throws, your program
won’t compile.
Example of a Checked Exception:
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("data.txt"); // File
might not exist
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
Why is this checked?
Because Java checks for IOException at compile-time, and you must handle it.
Some common checked exceptions:
• IOException (File not found, input/output issues)
• SQLException (Database-related errors)
• ClassNotFoundException (Class not found in classpath)
What is an Unchecked Exception?
Unchecked exceptions occur at runtime and are caused by logic errors, such as
accessing an invalid array index or dividing by zero. Java does not force you to handle
them, but you should do it for safer code.
Example of an Unchecked Exception:
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println(numbers[10]); // Accessing an invalid
index
}
}
Why is this unchecked?
Because ArrayIndexOutOfBoundsException occurs only at runtime, and Java does
not check for it at compile-time.
Some common unchecked exceptions:
• NullPointerException (Accessing a null object)
• ArithmeticException (Dividing by zero)
• ArrayIndexOutOfBoundsException (Invalid array index access)
Why Does Java Have Both?
Java uses checked exceptions for errors beyond programmer control (like missing
files) so they must be handled.
Unchecked exceptions usually occur due to programming mistakes and should be
fixed by writing better code.
a. throw is used inside a method to explicitly throw an exception, while throws is used
in the method declaration to specify possible exceptions.
c. throw is used for triggering exceptions, while throws informs the caller that an
exception might occur and needs handling.
try {
int num = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught.");
} finally {
System.out.println("Finally block executed.");
}
6. Can we have multiple catch blocks in Java? How?
What: Yes, multiple catch blocks can be used to handle different exceptions
separately.
Why: This ensures specific handling for different exceptions.
Example:
try {
int num = Integer.parseInt("abc"); // NumberFormatException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error.");
} catch (NumberFormatException e) {
System.out.println("Number format error.");
} catch (Exception e) {
System.out.println("Some other exception.");
}
7. What is the StackOverflowError in Java?
What: It is an error that occurs when a method calls itself too many times (infinite
recursion).
Why: It happens when the stack memory is exhausted.
Example:
What:
• HashMap is not synchronized (not thread-safe).
• Hashtable is synchronized (thread-safe but slower).
Why:
• Use HashMap for better performance in single-threaded applications.
• Use Hashtable if thread safety is required.
Example:
Map<String, String> hashMap = new HashMap<>();
Map<String, String> hashtable = new Hashtable<>();
7. What is the Iterator interface?
What:
• Iterator is an interface used to traverse (loop through) collections one by one.
Why:
• It is safer than using a for loop because it prevents modification issues.
Example:
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
8. What is the difference between fail-fast and fail-safe iterators?
What:
• Fail-fast iterators throw a ConcurrentModificationException if the collection is
modified while iterating (ArrayList).
• Fail-safe iterators allow modifications (CopyOnWriteArrayList).
Why:
• Fail-fast helps detect issues early.
• Fail-safe helps avoid crashes in multi-threaded environments.
Example:
What:
• Thread class: You create a thread by extending Thread and overriding run().
• Runnable interface: You create a thread by implementing Runnable and passing it to
a Thread object.
Why:
• Runnable is better because Java does not support multiple inheritance.
• If you extend Thread, you cannot extend any other class.
Example (Preferred Approach - Runnable)
class MyTask implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}
4. What is the purpose of synchronized keyword in Java?
What?
• It ensures thread safety by allowing only one thread to execute a block of code at a
time.
Why?
• Prevents data inconsistency when multiple threads try to modify a shared resource.
Example:
class Counter {
private int count = 0;
public synchronized void increment() { // Only one thread can
access at a time
count++;
}
public int getCount() {
return count;
}
}
public class SyncExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Count: " + counter.getCount());
}
}
5. What is thread synchronization in Java?
What?
• Synchronization is the process of controlling access to shared resources.
• It prevents race conditions, where multiple threads try to update a variable at the
same time.
Why?
• Without synchronization, the output can be inconsistent.
Example (Without Synchronization - Incorrect Output)
class SharedResource {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
• If multiple threads call increment(), count may not update correctly.
Example (Deserialization):
import java.io.*;
Example:
Using map():
List<String> names = Arrays.asList("John", "Jane");
// StringBuilder (Mutable)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
// StringBuffer (Thread-Safe)
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
System.out.println(sbf); // Output: Hello World
}
}
2. What is a singleton class in Java? How do you implement it?
What?
• A singleton class ensures only one instance exists.
Why?
• Used for logging, database connections, thread pools.
• Saves memory and prevents multiple instances.
Example (Lazy Initialization Singleton):
class Singleton {
private static Singleton instance;
class Test {
private String message = "Hello, Reflection!";
What?
• The Math class provides mathematical functions like sqrt(), pow(), random(), etc.
Why?
• Used for calculations in scientific, financial, and gaming applications.
Example:
public class MathExample {
public static void main(String[] args) {
System.out.println(Math.sqrt(16)); // Output: 4.0
System.out.println(Math.pow(2, 3)); // Output: 8.0
System.out.println(Math.random()); // Output: Random value
between 0.0 and 1.0
}
}
9. What are the different types of inner classes in Java?
What?
• Member Inner Class - Defined inside another class.
• Static Nested Class - Uses static keyword, behaves like a normal class.
• Local Inner Class - Inside a method, limited scope.
• Anonymous Inner Class - No name, used for short-lived tasks.
Why?
• Used to group related classes for better readability and organization.
Example (Member Inner Class):
class Outer {
class Inner {
void display() {
System.out.println("Inside Inner Class");
}
}
}
public class InnerClassExample {
public static void main(String[] args) {
Outer.Inner obj = new Outer().new Inner();
obj.display(); // Output: Inside Inner Class
}
}