0% found this document useful (0 votes)
6 views

All in One Java Notes

Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects and classes, emphasizing principles like encapsulation, inheritance, polymorphism, and abstraction. Key concepts include the distinction between classes and objects, constructors, method overloading and overriding, and the use of access modifiers. OOP facilitates code reusability and maintainability, making it easier to model real-world entities in software development.

Uploaded by

Gaurav Dhakate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

All in One Java Notes

Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects and classes, emphasizing principles like encapsulation, inheritance, polymorphism, and abstraction. Key concepts include the distinction between classes and objects, constructors, method overloading and overriding, and the use of access modifiers. OOP facilitates code reusability and maintainability, making it easier to model real-world entities in software development.

Uploaded by

Gaurav Dhakate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

OOPs Concepts

1. What is Object-Oriented Programming?

Object-Oriented Programming, or OOP, is a programming approach that is based on real-world entities. It


focuses on using objects and classes to organize code in a modular and reusable way.
In OOP, data and the functions that operate on that data are bundled together into units called objects.

The main principles of OOP are:

• Encapsulation (binding data and methods together),

• Inheritance (reusing existing code),

• Polymorphism (having many forms), and

• Abstraction (hiding internal details).

This approach helps in building scalable and maintainable applications. For example, if we are building a
student management system, we can create a Student class and create multiple student objects from it.

2. What is the difference between a Class and an Object?

In Java, a class is a blueprint or template used to define the structure and behavior of objects. It contains
variables (data) and methods (functions) that define what the object will have and do.

An object, on the other hand, is an instance of a class. It is created in memory and holds specific data.

For example, if Car is a class, then myCar and yourCar can be two different objects of that class with their own
properties like color and speed.

3. What is a Constructor in Java? How is it different from a Method?

A constructor in Java is a special block of code that is called automatically when an object is created. It is used
to initialize the object.
The name of the constructor is always the same as the class name, and it does not have any return type, not
even void.

The main difference between a constructor and a method is:

• A constructor is called automatically when an object is created, whereas a method must be called
manually.

• A constructor is used for initialization, while a method is used for performing operations.

4. What are the types of Constructors in Java?

There are two types of constructors in Java:

1. Default Constructor – This is a constructor with no parameters. If we do not define any constructor in
our class, Java provides a default constructor automatically. It assigns default values to the object's
fields.

2. Parameterized Constructor – This constructor takes arguments so that we can assign custom values to
the object during creation.
5. What is Constructor Overloading? Give an Example.

Constructor overloading in Java means having more than one constructor in the same class with different
parameter lists. It allows us to create objects in different ways using different sets of data.

For example:
class Student {
Student() {
// default constructor
}
Student(String name) {
// constructor with one parameter
}
Student(String name, int age) {
// constructor with two parameters
}
}
In the above example, all three constructors are overloaded. Based on the number and type of parameters,
the appropriate constructor is called when the object is created.

6. What is Inheritance in Java? Explain with an Example.

Inheritance is one of the key features of Object-Oriented Programming. It allows a class (called the child or
subclass) to inherit properties and methods from another class (called the parent or superclass).

The main advantage of inheritance is code reusability. Instead of writing the same code again, we can extend
a class and reuse its functionality.

For example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
In this example, the Dog class inherits the eat() method from the Animal class.

7. What is the difference between Single and Multilevel Inheritance?

In single inheritance, a class inherits from one parent class only.


Example:
class A { }
class B extends A { }
In multilevel inheritance, a class inherits from a class that already inherited from another class. It forms a
chain of inheritance.
Example:

class A { }
class B extends A { }
class C extends B { }
The key difference is the number of levels of inheritance. Single inheritance has only one level, while multilevel
involves multiple levels.

8. What is Method Overriding?

Method overriding is a feature in Java where a child class provides its own specific implementation of a
method that is already defined in the parent class.
It occurs only in inheritance and must have the same method name, return type, and parameters.

The main purpose of overriding is to achieve runtime polymorphism and to allow a subclass to provide
specific behavior.

Example:

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}
9. What is Method Overloading? How is it different from Overriding?

Method overloading means defining multiple methods in the same class with the same name but different
parameters (number, order, or type of parameters).

It is done to perform a similar task in different ways and is an example of compile-time polymorphism.

Method overriding, on the other hand, means redefining a method from the parent class in the child class with
the same method signature. It is used for runtime polymorphism.

Example of Overloading:

class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
10. What is Polymorphism in Java? Explain Compile-time and Runtime Polymorphism.
Polymorphism in Java means the ability of a method, object, or class to take many forms. It allows the same
method or action to behave differently in different scenarios.
There are two types of polymorphism:
1. Compile-time Polymorphism (Static Binding)
This is achieved using method overloading. The decision of which method to call is made during
compile time.
Example:
class Demo {
void show(int a) { }
void show(String b) { }
}
2. Runtime Polymorphism (Dynamic Binding)
This is achieved using method overriding. The decision of which method to call is made at runtime
based on the object type.
Example:

class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Cat extends Animal {
void sound() { System.out.println("Meow"); }
}
Animal a = new Cat();
a.sound(); // Output: Meow

11. What is the role of the super keyword in Java?

In Java, the super keyword is used to refer to the immediate parent class. It is mainly used for three purposes:
1. To call the parent class constructor.
2. To access the parent class methods.
3. To access the parent class variables.
This is helpful when the child class has overridden the method or variable, and we still want to refer to the
parent class version.
Example:
class Animal {
String type = "Animal";
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super(); // calls parent constructor
System.out.println("Dog constructor");
}
void displayType() {
System.out.println(super.type); // accesses parent variable
}
}
12. Can a constructor be inherited? Why or why not?
No, constructors cannot be inherited in Java.
This is because constructors are not members of a class like methods are. They are special blocks used to
initialize objects, and each class must define its own constructor.
However, a subclass can call a constructor of the parent class using the super() keyword.
13. What is abstraction? How is it achieved in Java?
Abstraction is the process of hiding the internal implementation details and showing only the necessary
features of an object.
In Java, abstraction is achieved in two ways:
1. Abstract classes
2. Interfaces
This allows us to focus on what an object does, rather than how it does it.
Example using abstract class:

abstract class Vehicle {


abstract void start();
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with key");
}
}
14. What is the difference between an abstract class and an interface?
Use abstract classes when classes share some common code. Use interfaces when you need to define a
contract for unrelated classes.
Feature Abstract Class Interface
Keyword abstract interface
Methods Can have abstract and non-abstract All methods are abstract (until Java 7)
Variables Can have instance variables Only static and final variables
Inheritance Single inheritance only Multiple inheritance supported
Constructors Can have constructors Cannot have constructors
15. Can we create an object of an abstract class?
No, we cannot create an object of an abstract class directly because it may contain incomplete methods.
However, we can create an object of its subclass, which provides implementations for all abstract methods.
Example:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
Shape s = new Circle(); // allowed
16. What is encapsulation? How do you achieve it in Java?

Encapsulation is the binding of data and methods that operate on that data into a single unit.
In Java, it is achieved by:

• Making variables private,

• Providing public getters and setters.

This helps in data hiding and keeps the data safe from outside interference.

Example:

class Student {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
17. Why is encapsulation important in Java?

Encapsulation is important because:

• It protects data from unauthorized access.

• It improves maintainability and flexibility.

• It allows controlled access to the fields.

• It follows the principle of data hiding.

It also makes code modular and easy to debug or upgrade without affecting other parts of the program.

18. What is the difference between private, protected, public, and default access modifiers?

Modifier Access Level

private Accessible only within the same class

default Accessible within the same package

protected Accessible within the same package and subclasses

public Accessible from anywhere in the program

These access levels control visibility and help in achieving security and encapsulation.

19. How does Java achieve multiple inheritance?

Java does not support multiple inheritance through classes to avoid ambiguity (like the Diamond Problem).
However, Java supports multiple inheritance using interfaces.

A class can implement multiple interfaces and thus inherit behavior from multiple sources.
Example:

interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() { }
public void methodB() { }
}
20. What are the real-world examples of OOPs concepts?

Here are real-world analogies for OOPs concepts:

• Class: Blueprint of a car.

• Object: A specific car like "Toyota Corolla".

• Inheritance: A sports car inherits properties from a general car class.

• Polymorphism: A person acts as a teacher at school and a parent at home.

• Encapsulation: ATM hides the internal code and shows only options like withdraw and deposit.

• Abstraction: Using a smartphone—you interact with apps but don’t know the code behind them.

These examples make it easier to relate OOPs concepts to everyday objects.

21. Can you override a static method in Java?

No, we cannot override static methods in Java because they belong to the class, not the object.
However, if you define a static method with the same name in a subclass, it is method hiding, not overriding.

Example:

class Parent {
static void display() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
static void display() {
System.out.println("Child static method");
}
}
Calling Child.display() will call the child’s method, but it’s not runtime polymorphism.

22. Can you overload the main() method in Java?

Yes, the main() method can be overloaded like any other method in Java.
But the JVM always calls the main method with String[] args as the entry point.
Example:

public class Demo {


public static void main(String[] args) {
System.out.println("Main with String[] args");
main(10);
}
public static void main(int a) {
System.out.println("Overloaded main with int: " + a);
}
}
23. What is the use of final keyword in method, variable, and class?

The final keyword is used to restrict modifications in Java.

• final variable: Value cannot be changed after initialization.

• final method: Cannot be overridden in subclass.

• final class: Cannot be extended.

Example:

final class Vehicle {} // Cannot be subclassed


class Bike {
final void run() {
System.out.println("Running");
}
}
Use final for safety, security, and performance optimization.

24. What is the difference between this and super?

Keyword Refers to Use Case

this Current class instance To access current class members

super Immediate parent class instance To access parent class members

Example:

class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
System.out.println(this.x); // 20
System.out.println(super.x); // 10
}
}
25. Can a class extend multiple classes in Java? Why not?

No, Java does not support multiple inheritance with classes to avoid ambiguity like the Diamond Problem.
Instead, Java uses interfaces to achieve multiple inheritance.

Example (Not allowed):

// class C extends A, B { } // Error

Use interfaces if you need to inherit from multiple sources.

26. Can an interface extend another interface?

Yes, in Java, an interface can extend one or more interfaces using the extends keyword.

Example:

interface A {
void methodA();
}
interface B extends A {
void methodB();
}
This helps in creating a hierarchy of contracts.

27. What happens if a subclass does not override an abstract method?

If a subclass does not override all abstract methods, it must also be declared abstract.
Otherwise, it will cause a compile-time error.

Example:

abstract class Shape {


abstract void draw();
}
class Circle extends Shape {
// If draw() is not implemented, Circle must be abstract
}

28. How is upcasting and downcasting used in polymorphism?

• Upcasting: Assigning a subclass object to a parent class reference. It is safe and done automatically.

• Downcasting: Casting a parent class reference back to a subclass. Needs explicit casting and may throw
ClassCastException if not done carefully.

Example:

Animal a = new Dog(); // Upcasting


Dog d = (Dog) a; // Downcasting

Upcasting is commonly used in runtime polymorphism.


29. Explain the difference between IS-A and HAS-A relationships.

• IS-A: Inheritance relationship. One class is a type of another.

o Example: Dog IS-A Animal (Dog extends Animal)

• HAS-A: Composition or Aggregation. One class has an object of another.

o Example: Car HAS-A Engine (Car contains Engine object)

These relationships help in building realistic object models in OOP.

30. Write a code example that shows runtime polymorphism using method overriding.

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

public class TestPolymorphism {


public static void main(String[] args) {
Animal a; // parent reference

a = new Dog(); // upcasting


a.sound(); // Dog barks

a = new Cat(); // upcasting


a.sound(); // Cat meows
}
}

This is runtime polymorphism because the method call is resolved at runtime based on the object type.
String

1. What is a String in Java?

A String in Java is an object that represents a sequence of characters. It is used to store text, like words or
sentences, and is defined in the java.lang package. Strings are widely used in Java for handling text-based data.

For example:

String name = "Gaurav";


Here, "Gaurav" is a string literal, and name is a reference to the string object.

2. Why are Strings immutable in Java?

Strings in Java are immutable, which means once a string is created, it cannot be changed. Any operation that
seems to modify a string actually creates a new one.

This immutability is designed for security, thread safety, and performance — especially because strings are
frequently used as keys in collections and for storing sensitive information like usernames, file paths, etc.

Example:

String s = "Hello";
s.concat(" World");
System.out.println(s); // Output: Hello (not "Hello World")
3. How do you create a String object in Java?

You can create strings in two main ways:

1. Using a string literal:

2. String s1 = "Hello";

This goes into the String pool for memory efficiency.

3. Using the new keyword:

4. String s2 = new String("Hello");

This creates a new string in the heap memory.

4. What is the difference between String str = "abc" and String str = new String("abc")?

When you use String str = "abc", the string is placed in the String Pool, and if the same literal exists, Java
reuses it.
But if you use new String("abc"), Java creates a new object in heap memory, even if the same string exists in
the pool.
This affects memory usage and object comparison.
Example:

String a = "abc";
String b = new String("abc");
System.out.println(a == b); // false (different memory)
System.out.println(a.equals(b)); // true (same content)
5. How does == differ from .equals() in string comparison?

The == operator checks if two references point to the same object in memory, while .equals() checks if the
actual content of the strings is the same.
So, use == for reference comparison, and .equals() for content comparison.
Example:
String x = "Java";
String y = new String("Java");
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
6. What is the use of the intern() method in strings?

The intern() method returns a canonical representation of the string. It tells Java to add the string to the String
Pool if it’s not already there.
This is useful when you want to ensure that all equal strings share the same memory reference.
Example:
String a = new String("Core");
String b = a.intern();
System.out.println(b == "Core"); // true
7. How is memory managed for strings in Java?

Java uses two types of memory for strings:

• String Pool: for string literals — shared and reused.

• Heap memory: for strings created with new.

This model allows efficient memory use while also providing flexibility.

8. What is the String Pool?

The String Pool is a special memory area in the Java heap where string literals are stored. If two strings have
the same literal value, Java uses the same object from the pool instead of creating a new one.

Example:

String a = "data";
String b = "data";
System.out.println(a == b); // true
Both a and b refer to the same object in the pool.

9. What does the substring() method do?

The substring() method is used to extract a part of a string based on a starting and optional ending index. It
returns a new string containing characters from the original string.
Example:
String str = "HelloWorld";
String sub = str.substring(0, 5); // returns "Hello"

It’s commonly used when you need only a part of a string, like extracting date, name, or code from a larger
string.
10. What is the difference between substring(int beginIndex) and substring(int beginIndex, int endIndex)?

• substring(beginIndex) returns characters from the given index to the end of the string.

• substring(beginIndex, endIndex) returns characters from beginIndex to endIndex - 1 (end index is


exclusive).

Example:

String str = "Programming";


str.substring(3); // Output: "gramming"
str.substring(0, 6); // Output: "Progra"

11 . How does the replace() method work?

The replace() method replaces all occurrences of a character or substring with another.

Example:

String str = "Java is cool";


str.replace("cool", "awesome"); // Output: "Java is awesome"
It’s helpful for sanitizing data or formatting output.

12. What is the use of indexOf() and lastIndexOf()?

• indexOf() returns the first occurrence of a character or substring.

• lastIndexOf() returns the last occurrence.

Example:

String str = "banana";


str.indexOf("a"); // Output: 1
str.lastIndexOf("a"); // Output: 5
They’re useful when searching positions within strings.

13. How do toLowerCase() and toUpperCase() differ?

• toLowerCase() converts all characters in the string to lowercase.

• toUpperCase() converts all characters to uppercase.

Example:

String name = "Gaurav";


name.toLowerCase(); // Output: "gaurav"
name.toUpperCase(); // Output: "GAURAV"

These are often used for case-insensitive comparisons or formatting.


14. What does trim() do?

The trim() method removes leading and trailing white spaces from a string, but not spaces in between.

Example:

String input = " Hello World ";


input.trim(); // Output: "Hello World"

Very useful when processing user input or validating forms.

15. How to check if a string starts or ends with a particular substring?

You can use:

• startsWith(String prefix)

• endsWith(String suffix)

Example:

String str = "HelloWorld";


str.startsWith("Hello"); // true
str.endsWith("World"); // true
These methods are useful for validating prefixes like "https://" or checking file extensions.

16. What is the difference between contains() and matches()?

• contains() checks if a substring exists in the string.

• matches() checks if the entire string matches a regex pattern.

Example:

String s = "Java123";
s.contains("123"); // true
s.matches("\\w+"); // true (regex for word characters)
Use contains() for simple checks, and matches() for pattern-based validation (like email, mobile number).

17. How to split a string using split() method?

The split() method breaks a string into an array based on a given delimiter.

Example:

String str = "apple,banana,mango";


String[] fruits = str.split(",");

This is useful for CSV data or user input separated by commas, spaces, etc.

18. How to convert a string to a char array?

You can use the toCharArray() method to convert a string into an array of characters.
Example:

String str = "Java";


char[] arr = str.toCharArray(); // ['J', 'a', 'v', 'a']
This is often needed when you want to loop through characters individually (e.g., for palindrome check).

Absolutely! Here are interview-level answers to your StringBuilder and StringBuffer questions — explained in
a confident, structured, and example-backed way so you can crack your Java interview with ease:

19. What is the difference between StringBuilder and StringBuffer?

Both StringBuilder and StringBuffer are mutable classes used for creating modifiable string objects.
However, the key difference lies in thread safety.

• StringBuffer is thread-safe (synchronized) — suitable for multi-threaded environments.

• StringBuilder is not synchronized, hence faster and better for single-threaded applications.

Example:

StringBuilder sb = new StringBuilder("Hello");


sb.append(" Java");
System.out.println(sb); // Output: Hello Java

20. Why is StringBuilder preferred over StringBuffer in single-threaded applications?

In single-threaded applications, there is no need for synchronization.


Since StringBuilder is not synchronized, it performs faster than StringBuffer due to the lack of overhead from
thread-safety checks.

In short: Use StringBuilder for speed when you don't need thread safety.

21. Is StringBuffer thread-safe? How?

Yes, StringBuffer is thread-safe because all its methods are synchronized.


This means only one thread can access a method at a time, which prevents data inconsistency during
concurrent modifications.

Example:

StringBuffer sb = new StringBuffer("Hi");


sb.append(" Gaurav");
System.out.println(sb); // Output: Hi Gaurav

22. Can StringBuilder and StringBuffer be used for string concatenation? How?

Yes, both are commonly used for string concatenation, especially when dealing with loops or large strings, as
they avoid creating multiple immutable String objects.

Example using StringBuilder:

StringBuilder sb = new StringBuilder();


sb.append("Hello").append(" World").append("!");
System.out.println(sb); // Output: Hello World!
This is more efficient than using + operator in a loop.
23. How does append() method work in StringBuilder?

The append() method adds a string (or any data type) to the end of the existing content.

Example:

StringBuilder sb = new StringBuilder("Java");


sb.append(" is fun");
System.out.println(sb); // Output: Java is fun

It supports method chaining, so you can append multiple values in one line.

24. How does insert() work in StringBuilder or StringBuffer?

The insert() method inserts text at a specified position (index) within the string.

Example:

StringBuilder sb = new StringBuilder("Hello");


sb.insert(5, " Gaurav");
System.out.println(sb); // Output: Hello Gaurav

It's useful for adding data in the middle or beginning of a string.

25. What is the use of delete() and deleteCharAt()?

• delete(start, end) removes a range of characters.

• deleteCharAt(index) removes a character at a specific index.

Example:

StringBuilder sb = new StringBuilder("Hello Gaurav");


sb.delete(5, 12); // Output: Hello
sb.deleteCharAt(1); // Output: Hllo

These methods help clean or manipulate strings dynamically.

26. How do you reverse a string using StringBuilder?

You can use the built-in reverse() method in StringBuilder or StringBuffer.

Example:

StringBuilder sb = new StringBuilder("Java");


sb.reverse();
System.out.println(sb); // Output: avaJ
This is the simplest and most efficient way to reverse strings in Java.

27. What does capacity() and ensureCapacity() mean in StringBuilder?

• capacity() returns the current storage capacity of the builder, which may be more than the actual
string length.

• ensureCapacity(minCapacity) increases capacity to the given value if needed.


Example:

StringBuilder sb = new StringBuilder();


System.out.println(sb.capacity()); // Default: 16
sb.ensureCapacity(50); // Ensures capacity is at least 50
28. Check if a string is a palindrome

A palindrome reads the same forward and backward (e.g., "madam", "level").

import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String reversed = new StringBuilder(str).reverse().toString();
if (str.equalsIgnoreCase(reversed)) {
System.out.println("It's a palindrome.");
} else {
System.out.println("Not a palindrome.");
}
}
}
Explanation: We use StringBuilder to reverse the string and compare it (ignoring case).

29. Count vowels and consonants in a string

import java.util.Scanner;
public class VowelConsonantCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int vowels = 0, consonants = 0;
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1)
vowels++;
else
consonants++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}

Explanation: We loop through each character and count based on whether it is a vowel or consonant (ignoring
spaces, digits, etc.).
30. Find the first non-repeating character in a string

import java.util.*;
c class FirstNonRepeatingChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println("First non-repeating character: " +
entry.getKey());
return;
}
}
System.out.println("No non-repeating character found.");
}
}
Explanation: We use a LinkedHashMap to preserve order and track frequency. The first entry with value 1 is
our answer.

Arrays (Basics + Coding)

1. What is an array in Java?


An array in Java is a fixed-size, indexed collection of elements of the same data type. It stores multiple values
in a single variable, instead of declaring separate variables for each value.

2. How is a 1D array declared and initialized in Java?


You can declare and initialize a 1D array as follows:

int[] arr = new int[5]; // Declaration and memory allocation


int[] arr2 = {10, 20, 30}; // Declaration with initialization

3. What is the default value of array elements in Java?


Default values depend on the data type:

• int, float, long → 0

• boolean → false

• Object references → null

4. How to find the length of an array?


You can use the .length property:

int[] arr = {1, 2, 3};


System.out.println(arr.length); // Output: 3
5. Can you change the size of an array once it is created?
No. Arrays in Java have a fixed size once created. To resize, you need to create a new array and copy the
elements.

6. How to copy one array into another in Java?


Using System.arraycopy() or Arrays.copyOf():

int[] original = {1, 2, 3};


int[] copy = Arrays.copyOf(original, original.length);

7. Write a program to find the maximum and minimum in an array.

int[] arr = {4, 2, 9, 1, 6};


int max = arr[0], min = arr[0];
for (int num : arr) {
if (num > max) max = num;
if (num < min) min = num;
}
System.out.println("Max: " + max + ", Min: " + min);

8. Write a program to reverse an array.

int[] arr = {1, 2, 3, 4, 5};


for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
\

9. Write a program to remove duplicates from an array.

int[] arr = {1, 2, 2, 3, 4, 4, 5};


Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) set.add(num);
System.out.println(set); // [1, 2, 3, 4, 5]

10. Write a program to find the second largest element in an array.

int[] arr = {4, 1, 9, 7, 9, 3};


int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
System.out.println("Second largest: " + second);
11. How is a 2D array declared and initialized?
A 2D array is like an array of arrays. Here's how to declare and initialize it:

int[][] matrix = new int[3][3]; // 3x3 matrix


int[][] values = {{1, 2}, {3, 4}}; // Initialization with values

12. What is the difference between a 2D array and an array of arrays?


In Java, a 2D array is technically an array of arrays.
For example, int[][] arr = new int[2][]; creates an array with 2 rows, where each row can have a different
number of columns (jagged array).

13. Write a program to print a matrix.

int[][] mat = {{1, 2}, {3, 4}};


for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}

14. Write a program to add two matrices.

int[][] a = {{1, 2}, {3, 4}};


int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j];

15. Write a program to transpose a matrix.

int[][] mat = {{1, 2}, {3, 4}};


int[][] trans = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
trans[j][i] = mat[i][j];

16. Write a program to multiply two matrices.

int[][] a = {{1, 2}, {3, 4}};


int[][] b = {{5, 6}, {7, 8}};
int[][] prod = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
prod[i][j] += a[i][k] * b[k][j];
17. How to find the sum of each row and column in a 2D array?

int[][] mat = {{1, 2}, {3, 4}};


for (int i = 0; i < 2; i++) {
int rowSum = 0;
for (int j = 0; j < 2; j++) rowSum += mat[i][j];
System.out.println("Row " + i + " sum: " + rowSum);
}
for (int j = 0; j < 2; j++) {
int colSum = 0;
for (int i = 0; i < 2; i++) colSum += mat[i][j];
System.out.println("Column " + j + " sum: " + colSum);
}

18. How to search an element in a 2D array?

int[][] mat = {{1, 2}, {3, 4}};


int key = 3;
boolean found = false;
for (int[] row : mat) {
for (int val : row) {
if (val == key) {
found = true;
break;
}
}
}
System.out.println(found ? "Found" : "Not Found");

19. What is an array of objects in Java?


An array of objects in Java is a collection where each element is a reference to an object. It allows storing
multiple objects of the same class.
Example:

Student[] students = new Student[3];

20. How do you initialize an array of objects?


You first declare the array, then initialize each element with the new keyword.

Student[] students = new Student[2];


students[0] = new Student("Gaurav", 85);
students[1] = new Student("Aditya", 90);
21. Write a program to store and display an array of Student objects.

class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
void display() {
System.out.println(name + " - " + marks);
}
}
public class Test {
public static void main(String[] args) {
Student[] s = {
new Student("Gaurav", 85),
new Student("Aniket", 78)
};
for (Student stu : s) {
stu.display();
}
}
}

22. How to perform sorting on an array of objects using Comparable?


Implement the Comparable interface in the class and override compareTo().

class Student implements Comparable<Student> {


String name;
int marks;
public int compareTo(Student s) {
return this.marks - s.marks; // ascending
}
}
Arrays.sort(students);

23. How to perform sorting on an array of objects using Comparator?


Use a separate class that implements Comparator, or use a lambda.

Arrays.sort(students, (s1, s2) -> s1.name.compareTo(s2.name)); // sort by name


24. What is the Arrays class in Java?
Arrays is a utility class in the java.util package. It provides static methods for array manipulation, such as
sorting, searching, comparing, and filling arrays efficiently.
25. How to sort an array using Arrays.sort()?
You can use Arrays.sort(array) to sort elements in ascending order. It works for both primitive and object
arrays.
Example:

int[] arr = {5, 2, 8, 1};


Arrays.sort(arr); // arr becomes [1, 2, 5, 8]

26. What is the difference between Arrays.sort() and manual sorting?


Arrays.sort() is optimized and faster, using Dual-Pivot Quicksort (for primitives) or TimSort (for objects).
Manual sorting like bubble sort is slower and less efficient in real-time applications.

27. How to fill an array using Arrays.fill()?


Use Arrays.fill(array, value) to set all elements to a specific value.
Example:

int[] arr = new int[5];


Arrays.fill(arr, 100); // All elements become 100

28. How to compare two arrays using Arrays.equals()?


This method checks if both arrays have the same length and elements in the same order.
Example:

int[] a = {1, 2, 3};


int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); // true

29. How to perform binary search using Arrays.binarySearch()?


This method searches for a value in a sorted array and returns the index.

int[] arr = {10, 20, 30, 40};


int index = Arrays.binarySearch(arr, 30); // index = 2

30. How to convert an array to a list using Arrays.asList()?


This method returns a fixed-size list backed by the specified array.

String[] fruits = {"apple", "mango", "banana"};


List<String> list = Arrays.asList(fruits);
Wrapper Classes

1. What are wrapper classes in Java?


Wrapper classes are object representations of Java primitive data types. For example, int has a wrapper class
Integer, and double has Double.

2. Why do we need wrapper classes if we already have primitive types?


Wrapper classes allow primitives to be used where objects are required, like in collections (ArrayList<Integer>),
and they offer utility methods like parsing and conversions.

3. List the primitive types and their corresponding wrapper classes.

Primitive Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

4. How do you convert a primitive to a wrapper object?


By using constructors (before Java 9, now deprecated) or valueOf() method:

int num = 5;
Integer obj = Integer.valueOf(num);

5. How do you convert a wrapper object to a primitive type?


Using methods like intValue(), doubleValue(), etc.:

Integer obj = 10;


int num = obj.intValue();

6. What is the difference between Integer.parseInt() and Integer.valueOf()?

• parseInt() returns a primitive int.

• valueOf() returns an Integer object.


Example:

int a = Integer.parseInt("123");
Integer b = Integer.valueOf("123");
7. What is the purpose of the xxxValue() methods in wrapper classes?
These methods convert a wrapper object back to its primitive form. For example:

Double d = 10.5;
double val = d.doubleValue(); // Unboxing manually

8. How to convert a String to an int or double using wrapper classes?

int a = Integer.parseInt("123");
double b = Double.parseDouble("45.6");

9. What is the default value of wrapper class objects?


For wrapper class references, the default value is null.

10. What happens if you try to parse an invalid string using Integer.parseInt()?
It throws a NumberFormatException.

Integer.parseInt("abc"); // throws NumberFormatException

Autoboxing & Unboxing

11. What is autoboxing in Java?


Autoboxing is the automatic conversion of a primitive to its corresponding wrapper class.
Example:

int a = 10;
Integer obj = a; // autoboxing

12. What is unboxing in Java?


Unboxing is the reverse of autoboxing—automatic conversion of a wrapper object to its primitive type.

Integer obj = 100;


int a = obj; // unboxing

13. Explain with an example how autoboxing works.

List<Integer> list = new ArrayList<>();


list.add(5); // int is autoboxed to Integer

14. Explain with an example how unboxing works.

Integer num = 20;

int result = num + 10; // unboxing happens

15. How is autoboxing handled internally by the Java compiler?


The compiler inserts calls to valueOf() for autoboxing and xxxValue() for unboxing during compilation.

16. Can autoboxing lead to performance issues? How?


Yes. Excessive boxing/unboxing creates unnecessary objects and may slow down performance, especially in
loops or large data processing.
17. What is the difference between autoboxing and manual boxing?

• Autoboxing: Handled automatically by the compiler.

• Manual boxing: You explicitly use methods like Integer.valueOf().

18. Is null allowed in autoboxing/unboxing? What happens if you unbox a null?


Yes, but unboxing a null will throw a NullPointerException.

Integer obj = null;

int a = obj; // throws NullPointerException

19. Write a code snippet that shows autoboxing inside a collection like ArrayList<Integer>.

ArrayList<Integer> list = new ArrayList<>();


list.add(10); // autoboxing
int num = list.get(0); // unboxing

20. What are the potential pitfalls when using wrapper classes in comparisons (== vs .equals())?

• == checks reference equality.

• .equals() checks value equality.


Example:

Integer a = 128;
Integer b = 128;
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

Java Keyword

1. What is the use of the this keyword in Java?


The this keyword refers to the current class instance. It is mainly used to differentiate between instance
variables and method parameters with the same name.

2. How do you use this to refer to the current object?


You can use this to refer to instance variables of the current object when there is a naming conflict.
Example:

this.name = name;

3. How can this() be used to call a constructor?


this() is used for constructor chaining within the same class. It must be the first statement in the constructor.
Example:

this(); // Calls another constructor of the same class

4. What happens if you use this() and super() in the same constructor?
It leads to a compilation error because both this() and super() must be the first statement in a constructor, and
only one can occupy that position.

5. Can this be used inside static methods? Why or why not?


No. Static methods belong to the class, not to any specific object. Since this refers to the current object, it
cannot be used in static methods.
6. What is the purpose of the super keyword in Java?
The super keyword is used to refer to the immediate parent class object. It helps access parent class methods,
constructors, or variables.

7. How do you use super() to call the superclass constructor?


super() is used to explicitly call the constructor of the superclass. It must be the first line in the subclass
constructor.
Example:

super(); // Calls the parent class constructor

8. Can super be used to access data members of a superclass?


Yes. It can access data members of the superclass, especially when they are hidden by subclass variables.

9. What happens if a subclass overrides a method and still wants to call the superclass version?
You can use super.methodName() to call the overridden method from the parent class.

10. What is the difference between this and super?

• this: Refers to the current class instance.

• super: Refers to the parent class instance.

11. What is a static variable? How is it shared across objects?


A static variable belongs to the class rather than instances. It is shared among all objects of that class.
Example:

static int count;

12. What is a static method? Can it access non-static members?


A static method belongs to the class and not any object. It cannot access non-static members directly because
they belong to instances.

13. Can a static method be overridden? Why or why not?


No. Static methods cannot be overridden; they can only be hidden using another static method with the same
signature.

14. What is a static block and when is it executed?


A static block is used for static initializations. It runs once when the class is loaded into memory.

15. Write a program to show how static members behave across multiple objects.

class Test {
static int count = 0;
Test() { count++; }
}
Test a = new Test();
Test b = new Test();
System.out.println(Test.count); // Output: 2
16. What does final mean when applied to a variable?
A final variable becomes a constant. Once assigned, its value cannot be changed.

17. What does final mean when applied to a method?


A final method cannot be overridden by subclasses.

18. What does final mean when applied to a class?


A final class cannot be extended or inherited.

19. Can you change the value of a final variable once assigned?
No. Attempting to change a final variable results in a compilation error.

20. What is the difference between finally, final, and finalize()?

• final: Keyword to declare constants, final methods, or classes.

• finally: A block in exception handling that executes always.

• finalize(): A method invoked by the garbage collector before object destruction (deprecated in Java 9+).

21. What is the use of the abstract keyword?


The abstract keyword is used to declare a class or method that is incomplete and must be implemented in a
subclass.

22. What is the difference between an abstract class and an interface?

• Abstract class can have constructors, fields, and implemented methods.

• Interface (before Java 8) only had abstract methods. Interfaces support multiple inheritance.

23. What is the native keyword used for?


The native keyword is used to declare a method that is implemented in another language like C or C++.

24. What does the synchronized keyword do?


It ensures that only one thread can access a method or block of code at a time, helping with thread safety.

25. What is the role of the transient keyword in serialization?


A transient variable is not included during serialization, meaning it won’t be saved in the file or stream.

26. What happens if you declare a constructor static?


It causes a compilation error. Constructors cannot be static because they are called to create instances.

27. Can we override a method declared as final?


No. A final method cannot be overridden.

28. Can a class be both abstract and final? Why or why not?
No. An abstract class needs to be extended, but a final class cannot be extended — hence, they contradict.

29. Can static blocks throw exceptions?


Yes. Static blocks can throw unchecked exceptions. Checked exceptions must be handled explicitly.

30. What is the effect of declaring a class final but not its methods?
The class cannot be inherited, but its methods can be invoked normally.
Exception Handling

1. What is an exception in Java?


An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions. It is an object which Java uses to describe an error or an unexpected event.

2. What is the difference between an error and an exception?

• Error refers to serious problems that a program should not try to catch (e.g., OutOfMemoryError).

• Exception refers to conditions that a program might want to catch and handle (e.g., IOException).

3. What are the two types of exceptions in Java?


Java exceptions are categorized into two types:

• Checked Exceptions – These are checked at compile time (e.g., FileNotFoundException).

• Unchecked Exceptions – These occur at runtime (e.g., ArithmeticException).

4. What is the difference between checked and unchecked exceptions?

• Checked exceptions must be either caught or declared using the throws keyword.

• Unchecked exceptions are not required to be caught or declared; they occur due to programming
bugs.

5. What is the superclass of all exceptions in Java?


Throwable is the superclass of all exceptions and errors in Java. It has two main subclasses: Exception and
Error.

6. What is the purpose of the try block?


The try block is used to wrap the code that might throw an exception. It helps handle exceptions without
crashing the program.

7. Can we have multiple catch blocks with a single try block?


Yes, we can have multiple catch blocks to handle different types of exceptions separately.

8. What happens if no exception occurs inside the try block?


If no exception occurs, the catch block is skipped, and the program continues executing the next statement.

9. What is the role of the finally block?


The finally block contains code that is always executed, regardless of whether an exception occurs or not. It is
often used for cleanup tasks.

10. Will the finally block execute even if the program terminates using System.exit()?
No, if System.exit() is called before the finally block, it will not execute.

11. What is the difference between throw and throws?

• throw is used to explicitly throw an exception.

• throws is used in a method signature to declare that the method might throw exceptions.

12. Can you throw more than one exception in a method?


You can only throw one exception instance at a time using throw, but multiple exceptions can be declared
using throws.
13. Can throws be used with unchecked exceptions?
Yes, but it's optional. Unchecked exceptions don't need to be declared using throws.

14. Why do we use throws in method declaration?


It is used to indicate the calling method that an exception might be thrown and must be handled.

15. Can we use throw without a try-catch block?


Yes, but the method must declare the exception using the throws clause if it’s a checked exception.

16. How do you create a custom exception in Java?


By extending the Exception or RuntimeException class and defining your own class.
Example:

class MyException extends Exception {


public MyException(String msg) {
super(msg);
}
}

17. Should a custom exception extend Exception or RuntimeException?


It depends:

• Extend Exception for a checked exception.

• Extend RuntimeException for an unchecked exception.

18. How can you include a custom message in your exception?


Pass the message to the superclass constructor using super("message").

19. When would you use a custom exception?


When you need domain-specific exception handling like InvalidAgeException or InsufficientBalanceException.

20. Can a custom exception class override toString() or getMessage()?


Yes, for custom error message formatting or logging.

21. What is the difference between Exception and Throwable?

• Throwable is the superclass of both Exception and Error.

• Exception is meant for conditions that programs should catch.

22. What is the difference between RuntimeException and Error?

• RuntimeException is caused by programming mistakes.

• Error represents serious system failures like memory leaks or JVM crashes.

23. Can we catch multiple exceptions in a single catch block (Java 7+ feature)?
Yes, using multi-catch like:

catch (IOException | SQLException e) { ... }

24. Can we nest try-catch blocks?


Yes. One try-catch block can be placed inside another for fine-grained error handling.
25. What is a multi-catch block? How is it useful?
It allows catching multiple exceptions in one catch block, which reduces code redundancy.

26. What will happen if an exception occurs in the catch block?


If another exception occurs in the catch block, it will propagate to the outer scope or terminate the program if
unhandled.

27. Write a program to demonstrate multiple catch blocks.

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (Exception e) {
System.out.println("General error");
}

28. Write a program where finally is used to close a file/connection.

FileReader fr = null;
try {
fr = new FileReader("data.txt");
// Read file
} catch (IOException e) {
System.out.println("Error reading file");
} finally {
if (fr != null) fr.close();
}

29. Write a program to throw a custom InvalidAgeException if age < 18.

class InvalidAgeException extends Exception {


InvalidAgeException(String msg) { super(msg); }
}
public class Test {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) throw new InvalidAgeException("Age must be 18+");
else System.out.println("Eligible");
}
}
30. What happens if an exception is not caught in the program?
If an exception is not caught, it propagates up the call stack. If still unhandled, the JVM terminates the program
and prints a stack trace.
Nested & Inner Classes

1. What are nested classes in Java?


Nested classes are classes defined within another class. They help logically group classes and improve
encapsulation and readability.

2. What is the difference between static and non-static nested classes?

• Static nested class: Does not have access to non-static members of the outer class directly.

• Non-static nested class (Inner class): Has access to all members of the outer class, including private
ones.

3. What is an inner class?


An inner class is a non-static nested class defined within another class. It is associated with an instance of the
enclosing class and can access its members.

4. What are the types of inner classes in Java?


There are four types:

• Member inner class

• Local inner class

• Anonymous inner class

• Static nested class

5. What is a member inner class?


A member inner class is a class defined at the member level of another class (not inside a method). It can
access all members of the outer class.

6. What is a local inner class?


A local inner class is defined inside a method or a block and is accessible only within that method or block.

7. What is an anonymous inner class?


An anonymous inner class is a class without a name, declared and instantiated at the same time. It is typically
used to implement interfaces or extend classes with short-lived logic.

8. What is a static nested class?


A static nested class is a nested class declared with the static keyword. It can access only static members of the
outer class.

9. How can you access an inner class from outside the outer class?
By using the outer class object:

Outer.Inner inner = new Outer().new Inner();

10. Can a static nested class access non-static members of the outer class?
No. A static nested class can only access static members of the outer class.

11. Can an inner class have a constructor?


Yes. Inner classes can have constructors just like regular classes.
12. When should you use an inner class over a regular class?
Use inner classes when the class logically belongs to another class and is not useful independently.

13. Write a program demonstrating an anonymous inner class implementing an interface.

interface Greeting {
void sayHello();
}
public class Test {
public static void main(String[] args) {
Greeting g = new Greeting() {
public void sayHello() {
System.out.println("Hello from anonymous inner class!");
}
};
g.sayHello();
}
}

14. Can inner classes extend a class or implement interfaces?


Yes. Inner classes can extend other classes or implement interfaces like regular classes.

15. How is enclosing class's this referenced inside an inner class?


Use OuterClassName.this to refer to the enclosing class instance.
Example:

Outer.this.someMethod();

Here are the answers in your preferred format:


Access Modifiers in Java

1. What are the different access modifiers available in Java?


Java provides four access modifiers:

• private

• default (no modifier)

• protected

• public

2. Explain the difference between private, default, protected, and public.

• private – Accessible only within the same class.

• default – Accessible within the same package (no modifier).

• protected – Accessible within the same package and by subclasses in other packages.

• public – Accessible from anywhere.

3. What is the default access modifier in Java?


If no modifier is specified, default access is applied, meaning it’s accessible only within the same package.

4. Can a top-level class be declared private or protected?


No. Top-level classes can only be declared with public or default access.
Private or protected are not allowed for top-level classes.

5. Can we override a private method in Java?


No. Private methods are not visible in subclasses, so they cannot be overridden.

6. What is the scope of protected members?


Protected members are accessible within the same package and by subclasses in other packages.

7. Can a subclass in a different package access protected members of a superclass?


Yes, but only through inheritance, not through an object of the superclass.

8. Can constructors have access modifiers?


Yes. Constructors can be private, default, protected, or public, depending on the intended visibility of the
class instantiation.

9. What access modifiers can be used for class members (variables/methods)?


You can use private, default, protected, or public for class members.

10. Can you restrict access to a class so it’s only visible within the same package?
Yes. Use default access (no modifier) to restrict class visibility to the same package.

11. Can you access a private variable of a class from another class?
No. Private variables are not accessible from other classes. Use getters/setters to access them if needed.

12. What happens when you try to access a private method via inheritance?
You’ll get a compilation error because private methods are not inherited.
13. Write an example to show the difference between default and protected access.

// File: package1/Base.java
package package1;
public class Base {
void defaultMethod() {
System.out.println("Default Access");
}
protected void protectedMethod() {
System.out.println("Protected Access");
}
}
// File: package2/Derived.java
package package2;
import package1.Base;
public class Derived extends Base {
public void accessMethods() {
// defaultMethod(); // Error: Not accessible outside package
protectedMethod(); // OK: Accessible via inheritance
}
}

14. What modifier would you use to make a class member accessible to all other classes?
Use the public modifier.

15. How does access control impact encapsulation?


Access control supports encapsulation by restricting access to internal object data. It hides implementation
details and exposes only necessary parts, maintaining object integrity.

Object Class Methods

1. What is the Object class in Java?


The Object class is the root class of all Java classes. Every class in Java directly or indirectly inherits from
Object.

2. Why is the Object class considered the root of all Java classes?
It provides basic methods like equals(), toString(), hashCode(), etc., that every Java object can use or override.

3. What is the use of the equals() method?


The equals() method checks whether two objects are logically equal, typically by comparing their data
members.

4. What is the difference between == and equals()?

• == checks for reference equality (same memory location).

• equals() checks for content equality (same data), if overridden.


5. How do you override the equals() method properly?
Override equals() by checking:

• If the object is null

• If both objects are of the same class

• If key fields are equal


Example:

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee e = (Employee) obj;
return id == e.id && name.equals(e.name);
}

6. Why is it important to override hashCode() when overriding equals()?


Because equal objects must have the same hash code to maintain consistency in hash-based collections like
HashSet, HashMap.

7. What happens if two equal objects have different hash codes?


It breaks the contract and can lead to incorrect behavior in hash-based collections (e.g., duplicate entries in
HashSet).

8. What is the contract between equals() and hashCode()?


If two objects are equal (equals() returns true), then their hashCode() must also return the same value.

9. How does hashCode() affect performance in collections like HashMap or HashSet?


Efficient hashCode() implementation ensures even distribution and faster lookup, insert, and delete
operations.

10. What is the default implementation of toString() in the Object class?


Returns a string in the format:
ClassName@HexHashCode
e.g., Employee@1a2b3c

11. How and why would you override the toString() method?
Override toString() to return a meaningful string representation of the object (used in logging, debugging).
Example:

@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "'}";
}
12. What is the output of System.out.println(obj); if toString() is not overridden?
It prints the default output from Object class:
ClassName@HashCode

13. Can two unequal objects have the same hash code?
Yes. It’s called a hash collision, and it's allowed by the hashCode() contract.
14. Write a custom Employee class and override equals(), toString(), and hashCode().

class Employee {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee e = (Employee) obj;
return id == e.id && name.equals(e.name);
}
@Override
public int hashCode() {
return id * 31 + name.hashCode();
}
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "'}";
}
}
15. What are some best practices when overriding equals() and hashCode()?

• Use the same fields for both methods.

• Ensure symmetry, transitivity, and consistency.

• Use @Override annotation.

• Prefer Objects.equals() and Objects.hash() for null-safe comparisons.

Java Packages

1. What is a package in Java?


A package in Java is a namespace that organizes related classes and interfaces. It helps avoid name conflicts
and makes code modular and easier to maintain.

2. What is the purpose of using packages?


Packages:

• Group related classes/interfaces

• Avoid class name conflicts

• Provide access protection

• Help in maintaining and organizing large codebases


3. What is the difference between built-in and user-defined packages?

• Built-in packages: Provided by Java (e.g., java.util, java.io)

• User-defined packages: Created by the developer to group custom classes

4. How do you create and use a user-defined package?

1. Declare the package at the top of the file:


package mypack;

2. Save the file in a folder matching the package name.

3. Import and use it:


import mypack.MyClass;

5. What is the syntax to import a specific class from a package?

import packageName.ClassName;

6. What is the difference between import package.* and import package.ClassName?

• package.*: Imports all classes/interfaces from the package.

• package.ClassName: Imports only the specified class.

7. Can a class belong to multiple packages?


No. A Java class can belong to only one package defined using the package keyword at the top of the source
file.

8. What is the default package in Java?


If no package is declared, the class belongs to the default package (unnamed package), which has no specific
name.

9. What is the purpose of the java.lang package?


It provides fundamental classes like String, Math, System, Object, etc.
It’s automatically imported in every Java program.

10. Name some important Java packages and their uses.

• java.lang – Core classes

• java.util – Collections, Date, Random

• java.io – Input/output classes

• java.net – Networking

• java.sql – JDBC for database connectivity

• java.time – Date and time API

11. How are packages related to access modifiers?

• default access: Visible within the same package


• public: Accessible from any package
• protected: Accessible in subclasses across packages
• private: Not accessible outside the class
12. Can two classes in different packages have the same name?
Yes. As long as they are in different packages, class names can be the same without conflict.

13. How do you access a class from another package?


Use the import statement or the fully qualified class name:

import packagename.ClassName;
OR
packagename.ClassName obj = new packagename.ClassName();
14. Can you create sub-packages in Java? How?
Yes. Use a dot . to separate sub-packages:

package mycompany.sales;

Folder structure: mycompany/sales

15. How does the directory structure of packages reflect the package name?
The package name maps to a folder hierarchy:
package com.example.app;
// corresponds to directory: com/example/app/

Java Collections Framework

1. What is the Java Collections Framework?

The Java Collections Framework is a set of classes and interfaces that help manage groups of objects.
It provides data structures like List, Set, and Map, along with utility classes for sorting and searching.

2. What is the difference between Collection and Collections?

Collection is an interface that represents a group of elements like List and Set.
Collections is a utility class that provides static methods like sort(), reverse(), etc., to operate on collections.

3. Why is Java Collections Framework important?

It provides ready-to-use, well-tested data structures that reduce development time and improve performance.
It also promotes consistency by using standard interfaces and methods.

4. What is the root interface of the collection hierarchy?

Iterable is the root interface of the collection hierarchy.


It allows objects to be used in the enhanced for-loop by providing the iterator() method.

5. How is Iterable different from Collection?

Iterable is a super interface that defines the ability to be iterated.


Collection extends Iterable and adds methods like add(), remove(), and size().

6. What are the major interfaces in the Java Collections Framework?

The main interfaces are:

• Collection (extended by List, Set, and Queue)

• Map (separate hierarchy for key-value pairs)


7. Explain the difference between List, Set, and Map.

• List stores elements in order and allows duplicates.

• Set stores unique elements, no duplicates allowed.

• Map stores key-value pairs; keys must be unique, but values can be duplicated.

8. What are the main differences between ArrayList and LinkedList?

• ArrayList is backed by an array and provides fast access using index but slower insertions/deletions.

• LinkedList uses a doubly-linked list, so it's better for frequent insertions and deletions but slower for
access.

9. What are the main differences between HashSet and TreeSet?

• HashSet is unordered, allows one null, and is backed by a hash table.

• TreeSet is sorted, doesn’t allow null, and is backed by a red-black tree.

10. What are the main differences between HashMap and TreeMap?

• HashMap is unordered, allows one null key, and is generally faster.

• TreeMap maintains keys in sorted order and doesn’t allow null keys.

Great! Here's the interview-style answer format for questions 11–30 on Java Collections:

11. What is the difference between ArrayList and Vector?


Both are dynamic arrays, but ArrayList is not synchronized while Vector is synchronized.
Hence, Vector is thread-safe but slower than ArrayList in single-threaded environments.

12. How does ArrayList work internally?


ArrayList uses a dynamic array to store elements.
When it exceeds capacity, it creates a new array with 1.5 times the size and copies the old elements to the
new one.

13. How is LinkedList implemented internally?


LinkedList uses a doubly linked list internally.
Each node contains references to the previous and next elements, making insertion/deletion efficient at both
ends

14. Which is faster for insert/delete: ArrayList or LinkedList? Why?


LinkedList is faster for insertion and deletion, especially in the middle or at the ends.
This is because it doesn’t require shifting elements like ArrayList does.

15. What are the default capacities of ArrayList and LinkedList?

• ArrayList starts with a default capacity of 10.

• LinkedList does not have a predefined capacity; it grows dynamically as nodes are added.

16. Why doesn’t Set allow duplicate elements?


Set is designed to model mathematical sets, which contain unique elements.
It uses equals() and hashCode() to ensure uniqueness.
17. What is the underlying data structure of HashSet?
HashSet is backed by a HashMap.
Each element is stored as a key in the map with a constant dummy value.

18. How does TreeSet maintain ordering?


TreeSet uses a Red-Black Tree internally.
It maintains elements in ascending order by default or using a custom Comparator.

19. What is the time complexity for add, remove, and search in HashSet and TreeSet?

• HashSet: O(1) for add/remove/search (average case)

• TreeSet: O(log n) for add/remove/search due to tree operations

20. How does LinkedHashSet differ from HashSet?


LinkedHashSet maintains the insertion order using a linked list internally, while HashSet does not.

21. What are the key differences between HashMap and TreeMap?

• HashMap: Unordered, allows one null key, faster

• TreeMap: Sorted by keys, does not allow null keys, slightly slower

22. What is the underlying data structure of HashMap?


HashMap uses an array of buckets, each containing a linked list (or tree after Java 8) for handling collisions.

23. How does TreeMap maintain natural ordering?


TreeMap uses a Red-Black Tree that automatically sorts keys in their natural order or via a custom comparator.

24. What happens if you add a key with null to a TreeMap?


TreeMap throws a NullPointerException when a null key is added because it needs to compare keys.

25. How does LinkedHashMap maintain insertion order?


It uses a doubly linked list to link all entries, preserving the order in which keys were inserted.

26. What is the Queue interface in Java?


Queue is a collection used for FIFO (First In First Out) operations.
It provides methods like offer(), poll(), and peek() for element handling.

27. What is the difference between Queue and Deque?

• Queue: Supports insertion at the end and removal from the front

• Deque: Supports insertion and removal from both ends (Double-Ended Queue)

28. What is the difference between ArrayDeque and LinkedList?

• ArrayDeque: Uses a resizable array, faster and more efficient

• LinkedList: Uses a doubly linked list, can be slower and consumes more memory

29. What are some real-life use cases of Queues in Java?

• Task scheduling
• Print job management
• Thread pool management
• BFS traversal in graphs/trees
30. What is the difference between PriorityQueue and normal Queue?
PriorityQueue arranges elements based on priority using a heap, not insertion order.
Normal queues follow simple FIFO ordering without priority handling.

31. What is the difference between Iterator and ListIterator?

• Iterator can traverse only forward and works with all collections.

• ListIterator can traverse both forward and backward but only works with List types like ArrayList and
LinkedList.

• ListIterator also supports add(), set(), and previous() methods.

32. What is the purpose of remove() in Iterator?


The remove() method removes the last element returned by the iterator from the underlying collection.
It allows safe removal of elements during iteration without throwing ConcurrentModificationException.

33. Can we modify a collection while iterating over it?


We should not modify a collection directly while iterating using for-each or Iterator.
However, using Iterator.remove() is safe.
Modifying structurally (like adding/removing) from outside the iterator causes
ConcurrentModificationException.

34. What is a ConcurrentModificationException?


It is a runtime exception thrown when a collection is modified while iterating, except through the iterator’s
own methods.
This ensures fail-fast behavior to prevent unpredictable results.

35. What are the limitations of Iterator?

• Only forward traversal (unless using ListIterator)

• Cannot get index of elements

• Cannot add new elements

• Works only for one collection instance at a time

Comparator & Comparable (36–42)

36. What is the difference between Comparator and Comparable?

• Comparable is used to define natural ordering of objects (inside the class using compareTo()).
• Comparator is used to define custom ordering (outside the class using compare()).
37. How do you sort a list of custom objects using Comparable?
Implement the Comparable interface in the class and override the compareTo() method.
Then use Collections.sort(list);.

class Student implements Comparable<Student> {


int marks;
public int compareTo(Student s) {
return this.marks - s.marks;
}
}
38. How do you sort a list of custom objects using Comparator?
Create a separate class or anonymous class implementing Comparator, override compare(), and pass it to
Collections.sort().

Collections.sort(list, new Comparator<Student>() {


public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
});

39. Can we sort objects without modifying their class?


Yes, by using a Comparator.
You can define a custom comparator externally and use it with Collections.sort() or List.sort().

40. What is the result if compareTo() returns a negative value?


It means the current object is less than the compared object and should appear before it in the sorted order.

41. How does Collections.sort() use Comparable?


It checks if the objects implement the Comparable interface and uses the compareTo() method for sorting.
If not, it throws a ClassCastException.

42. How can you sort a Map by its values?


Convert the entry set to a list and sort it using a custom comparator based on values.

List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());

Collections.sort(list, (e1, e2) -> e1.getValue().compareTo(e2.getValue()));

43. Write a program to iterate over a HashMap and print keys and values.

import java.util.*;

public class HashMapIteration {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 3);
map.put("Banana", 5);
map.put("Orange", 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
}
}
44. Write a program to remove duplicates from a list using Set.

import java.util.*;

public class RemoveDuplicates {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Alice", "Tom",
"Bob");

Set<String> uniqueNames = new HashSet<>(names);

System.out.println("After removing duplicates: " + uniqueNames);


}
}
45. Write a program to sort an ArrayList of strings in reverse order.

import java.util.*;

public class ReverseSortList {


public static void main(String[] args) {
List<String> cities = new ArrayList<>(Arrays.asList("Pune", "Mumbai",
"Delhi", "Chennai"));

Collections.sort(cities, Collections.reverseOrder());

System.out.println("Sorted in reverse order: " + cities);


}
}

46. How to convert HashMap to TreeMap?

import java.util.*;
public class HashMapToTreeMap {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Zebra", 1);
hashMap.put("Apple", 2);
hashMap.put("Monkey", 3);

TreeMap<String, Integer> treeMap = new TreeMap<>(hashMap);

System.out.println("TreeMap (sorted): " + treeMap);


}
}
47. How to synchronize a collection?

import java.util.*;

public class SynchronizedCollection {


public static void main(String[] args) {
List<String> list = Collections.synchronizedList(new ArrayList<>());

list.add("One");
list.add("Two");

synchronized (list) {
for (String item : list) {
System.out.println(item);
}
}
}
}
48. How is fail-fast different from fail-safe iterators?

• Fail-fast iterators (e.g., in ArrayList, HashMap) throw ConcurrentModificationException if the


collection is modified during iteration.

• Fail-safe iterators (e.g., in CopyOnWriteArrayList, ConcurrentHashMap) allow modification during


iteration by working on a clone of the collection.

49. What collection would you use to implement a LRU cache?

You can use LinkedHashMap with access-order enabled to implement an LRU cache.

class LRUCache<K, V> extends LinkedHashMap<K, V> {


private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true); // true for access-order
this.capacity = capacity;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}

50. What are some best practices when working with Java collections?

• Choose the right collection type based on requirements (List, Set, Map).
• Always initialize with proper capacity to avoid resizing overhead.
• Prefer interfaces (List, Set) over implementation classes (ArrayList, HashSet) for flexibility.
• Use Collections.unmodifiableXXX() to create read-only collections when needed.
• Use Concurrent collections for multi-threaded environments.
• Avoid using raw types; always use generics.
• For large datasets, prefer Streams and parallel processing where appropriate.
Thread Basics & Lifecycle (1–10)

1. What is multithreading in Java?


Multithreading is the concurrent execution of two or more threads for maximum CPU utilization and better
performance.

2. What is the difference between a process and a thread?


A process is an independent execution unit with its own memory space, while a thread is a lightweight unit of
a process that shares memory.

3. How do you create a thread in Java?

• By extending the Thread class and overriding run().

• By implementing the Runnable interface and passing it to a Thread object.

4. What is the difference between extending Thread class and implementing Runnable?

• Runnable is preferred for flexibility (since Java doesn't support multiple inheritance).

• Use Thread when you need to override more than just run().

5. What are the different states of a thread?


NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.

6. What does the start() method do?


It starts a new thread and calls the run() method asynchronously.

7. What happens if we call run() instead of start()?


run() executes in the current thread, not in a new thread.

8. What is the use of the sleep() method in a thread?


It pauses the current thread for a specified time (in milliseconds), allowing other threads to execute.

9. What is the purpose of the yield() method?


It hints to the scheduler that the current thread is willing to yield CPU to other equal-priority threads.

10. What is the difference between isAlive() and join()?

• isAlive() checks if a thread is still running.

• join() waits for a thread to finish its execution.

11. When would you use the Runnable interface over extending Thread?
When you want to extend another class or separate logic from thread management.

12. Can we start a thread twice?


No, it throws IllegalThreadStateException if start() is called again.

13. How can we set thread priority? What is its effect?


Using setPriority(int). Priorities range from 1 (min) to 10 (max), but thread scheduling is JVM-dependent.

14. What is a daemon thread?


A background thread that runs until all user threads finish. E.g., Garbage Collector thread.
15. How can we create and run multiple threads?
By creating multiple Thread or Runnable objects and calling start() on each.

Synchronization (16–22)

16. Why do we need synchronization in Java?


To prevent race conditions and ensure thread safety when multiple threads access shared resources.

17. What is a race condition? How do you prevent it?


It occurs when threads access and modify shared data simultaneously. Use synchronized to avoid it.

18. What is the difference between synchronized method and synchronized block?

• A synchronized method locks the entire object.

• A synchronized block locks only the specified code, improving performance.

19. Can a constructor be synchronized?


No, constructors can't be synchronized because object locking happens after the object is created.

20. What is a synchronized block? When should you use it?


A block of code wrapped with synchronized(obj) to control access to critical sections. Use it for finer control.

21. What is the significance of the object lock in synchronization?


Only one thread can hold an object lock. It ensures mutual exclusion for synchronized code.

22. What are some alternatives to synchronized for thread safety?

• java.util.concurrent (e.g., ReentrantLock, AtomicInteger)

• Using thread-safe classes like ConcurrentHashMap.

23. What is inter-thread communication?


It allows threads to communicate and coordinate their actions using methods like wait(), notify().

24. What are the roles of wait(), notify(), and notifyAll()?

• wait() releases the lock and pauses the thread.

• notify() wakes up one waiting thread.

• notifyAll() wakes up all waiting threads.

25. Can wait() and notify() be called outside a synchronized block?


No, they must be called from synchronized context or it throws IllegalMonitorStateException.

26. What happens if a thread calls wait() without owning the monitor?
It throws IllegalMonitorStateException.

27. What is the difference between notify() and notifyAll()?

• notify() wakes one random thread.

• notifyAll() wakes up all waiting threads.


28. What is a deadlock? How can you prevent it?
Deadlock is when two or more threads wait forever for each other's resources. Prevent by:

• Lock ordering

• Timeout

• Using tryLock() from ReentrantLock.

29. What is the difference between volatile and synchronized?

• volatile ensures visibility, not atomicity.

• synchronized ensures both visibility and atomicity via locking.

30. What are thread-safe classes in Java?


Classes like Vector, Hashtable, StringBuffer, and Collections.synchronizedList() are thread-safe.

Sure! Here are 5 more advanced multithreading interview questions and answers, continuing from where we
left off — focusing on concurrency utilities, thread pools, and best practices.

31. What is the Executor framework in Java?


The Executor framework provides a high-level API for managing a pool of threads and executing tasks
asynchronously using interfaces like Executor, ExecutorService, and ScheduledExecutorService.

32. What is the difference between submit() and execute() in ExecutorService?

• execute() is used for Runnable tasks and doesn't return any result.

• submit() can accept both Runnable and Callable and returns a Future object.

33. What is a Callable and how is it different from Runnable?


Callable is similar to Runnable but can return a result and throw checked exceptions. Used with submit() to get
a Future.

34. What is a Future in Java concurrency?


A Future represents the result of an asynchronous computation. You can use get() to retrieve the result or
check if the task is complete

35. What are the benefits of using thread pools?

• Better resource management

• Avoids overhead of thread creation/destruction

• Improves application responsiveness

• Reuses threads, reducing latency and memory usage


Java I/O Streams

1. What are I/O streams in Java?


I/O streams in Java are used to read data from input sources (like files, keyboards, or networks) and write data
to output destinations (like files or consoles). Java provides two kinds of streams — byte streams and
character streams — so we can handle both binary data and character-based data effectively. They’re part of
the java.io package.

2. What is the difference between byte streams and character streams?


Byte streams, like InputStream and OutputStream, deal with raw binary data — ideal for images, audio, or
video files.
Character streams, like Reader and Writer, are used to handle text data. They use character encoding like UTF-
8, which makes them more suitable for reading and writing text files.

3. What is the difference between InputStream and Reader?


InputStream is designed for reading raw bytes — one byte at a time — whereas Reader reads Unicode
characters. So if I'm working with binary files, InputStream is better, but for text files with encoding, Reader is
preferred.

4. What is the difference between OutputStream and Writer?


OutputStream writes bytes to a destination, while Writer is for characters. Writer automatically handles
encoding, so if I’m writing to a text file, using Writer makes the code cleaner and encoding-safe.

5. What is the hierarchy of I/O classes in Java?


At the top level, we have abstract base classes:

• InputStream and OutputStream for byte streams

• Reader and Writer for character streams


These are extended by concrete classes like FileInputStream, BufferedReader, FileWriter, etc. The
design is very modular, making it easy to combine different stream types.

6. What are the main abstract classes for byte and character streams?
For bytes: InputStream and OutputStream
For characters: Reader and Writer
All file and buffer-based classes extend from these, ensuring consistency in I/O handling.

7. Why does Java have both byte and character streams?


Byte streams are necessary for binary data — like images or audio files — while character streams are better
for reading/writing human-readable text. Having both gives flexibility depending on the data type and
encoding needs.

8. How does Java handle character encoding in streams?


Java uses classes like InputStreamReader and OutputStreamWriter to bridge byte and character streams.
These allow us to specify encodings like UTF-8, making sure that characters are interpreted correctly when
reading or writing.

9. What is the use of the File class in Java?


The File class represents a file or directory path in the filesystem. It doesn’t perform read/write but is used to
get file info — like size, path, permissions, and whether it exists. It can also create or delete files.
10. How can you check if a file exists using Java?
We use the exists() method of the File class. For example:

File file = new File("data.txt");


if (file.exists()) {
System.out.println("File exists");
}

11. How do you read a file using FileReader?


FileReader is used for reading character data. Here's a basic example:

FileReader fr = new FileReader("data.txt");


int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
It reads one character at a time. For better performance, we usually wrap it with BufferedReader.

12. How do you write data to a file using FileWriter?


FileWriter writes character data to a file. Example:

FileWriter fw = new FileWriter("output.txt");


fw.write("Hello, Java I/O!");
fw.close();
It overwrites existing content unless we pass true for appending.

13. What is the difference between FileReader and BufferedReader?


FileReader reads one character at a time, which can be slow for large files.
BufferedReader adds buffering and methods like readLine() for faster and more convenient reading.
We usually wrap a FileReader inside a BufferedReader to improve performance.

14. How do you create a new file using Java?


You can use File.createNewFile():

File file = new File("newfile.txt");


if (file.createNewFile()) {
System.out.println("File created");
}

15. What happens if the file does not exist while reading?
If we try to read a non-existent file using FileReader or BufferedReader, a FileNotFoundException is thrown.

16. How can you append data to a file using FileWriter?


By passing true to the constructor:

FileWriter fw = new FileWriter("file.txt", true);


fw.write("Appended text");
fw.close();
This avoids overwriting existing content.
17. What is the difference between absolute and relative file paths?

• Absolute path includes the full location from the root (e.g., C:/Users/.../file.txt)

• Relative path is based on the current working directory (e.g., ./data/file.txt)


Relative paths are more flexible for cross-platform apps.

18. What exceptions should be handled during file I/O?


Primarily:
• IOException (parent of most I/O issues)
• FileNotFoundException (when file is missing)
It's good practice to handle or declare these using try-catch or throws.
19. What is BufferedReader? Why is it more efficient than FileReader alone?
BufferedReader reads characters from a stream and buffers them for efficiency. It reduces disk I/O by reading
chunks instead of one character at a time. It also offers readLine() which makes reading lines easy

20. How do you read a line from a file using BufferedReader?

BufferedReader br = new BufferedReader(new FileReader("data.txt"));


String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
It reads line by line until the end of file.

21. What is Scanner class used for in file reading?


Scanner is used to read input from various sources like keyboard, files, or strings. It supports parsing of
primitives (int, double) and strings easily using methods like nextInt(), nextLine(), etc.
22. How do you read different data types using Scanner?

Scanner sc = new Scanner(new File("input.txt"));


int age = sc.nextInt();
String name = sc.next();
It tokenizes input based on whitespace by default and parses accordingly.

23. What is the difference between Scanner and BufferedReader?

• BufferedReader is faster and suited for reading large files


• Scanner is easier for parsing input like numbers and words
For performance, BufferedReader is better; for parsing, Scanner is more convenient.
24. Which is preferred for performance: Scanner or BufferedReader?
BufferedReader is generally preferred for performance because it reads in larger chunks and uses less parsing
logic. Scanner trades speed for parsing flexibility.

25. How do you close file resources properly in Java?


We should use the try-with-resources feature (Java 7+) which automatically closes the stream:

try (FileReader fr = new FileReader("file.txt")) {


// use fr
}
This avoids manual close() calls and prevents resource leaks.
26. What is the try-with-resources statement?
It’s a try block that auto-closes resources implementing AutoCloseable. It simplifies code and avoids forgetting
to close streams, which can cause memory issues.

27. How can you copy contents from one file to another in Java?
Using streams:

try (FileInputStream in = new FileInputStream("source.txt");


FileOutputStream out = new FileOutputStream("dest.txt")) {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
Or using Files.copy() from NIO.

28. How can you read a binary file in Java?


Use FileInputStream to read raw byte data:

FileInputStream fis = new FileInputStream("image.jpg");


int byteData;
while ((byteData = fis.read()) != -1) {
// process byte
}
fis.close();
29. What is the difference between ObjectInputStream and FileInputStream?

Answer:

• FileInputStream reads raw bytes

• ObjectInputStream reads serialized Java objects from a stream


Use ObjectInputStream when restoring full object state from a file.

30. How can you serialize and deserialize an object to/from a file?
Serialization:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("obj.dat"));


out.writeObject(myObject);
out.close();
Deserialization:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("obj.dat"));
MyClass obj = (MyClass) in.readObject();
in.close();
The class must implement Serializable.

Here are detailed and interviewer-friendly answers for Serialization & Deserialization (1–10). Each answer is
crafted to show both understanding and confidence, making it easier for the interviewer to appreciate your
clarity.
Serialization & Deserialization

1. What is serialization in Java?


Serialization is the process of converting a Java object into a byte stream, so it can be easily saved to a file,
transferred over a network, or stored in memory. This makes it possible to persist object states and later
restore them using deserialization.

2. What is the purpose of serialization?


The main purpose is to persist an object's state or transfer it across different systems or networks. It allows
objects to be stored or shared in a form that can be re-created later, which is especially useful in file storage,
caching, or sending objects over sockets in distributed systems.

3. What is deserialization?
Deserialization is the reverse process of serialization. It converts the byte stream back into a Java object. This
helps in reconstructing the previously saved object state from a file, database, or network.

4. Which interface must a class implement to be serializable?


A class must implement the java.io.Serializable interface to be serializable. This is a marker interface —
meaning it has no methods — and it just indicates to the JVM that this class can be serialized.

5. What is the role of the serialVersionUID?


serialVersionUID is a unique identifier for a Serializable class. It is used during deserialization to verify that the
sender and receiver of the serialized object have loaded classes that are compatible. If the versions mismatch,
it throws an InvalidClassException.

6. What happens if serialVersionUID is not declared?


If not declared, Java will generate one automatically based on class details. However, this can lead to
unexpected InvalidClassException errors if the class structure changes slightly. That’s why it’s good practice to
declare it explicitly to ensure consistent compatibility across different JVMs or application versions.

7. Can we serialize static data members?


No, static members are not serialized because they belong to the class, not the object. Serialization works on
instance data — if you want static values to be preserved, you’ll need to handle them separately.

8. How do you prevent a field from being serialized?


By using the transient keyword. For example:

transient String password;

This tells the JVM to skip this field during serialization. It’s commonly used for sensitive data like passwords or
session tokens.

9. What is the difference between transient and static in serialization?

• transient fields are not serialized intentionally, even though they are part of the object.

• static fields are not serialized by nature, as they belong to the class, not the object instance.
So, both are skipped, but for different reasons.

10. Can a superclass be serialized if it doesn’t implement Serializable?


If the superclass is not serializable, only the subclass's serializable fields are saved. The non-serializable
superclass must have a no-arg constructor, because during deserialization, the JVM will call that constructor to
initialize the superclass part. So, yes — the subclass can still be serialized, but the superclass state won't be.
Generics

1. What are generics in Java?


Generics allow you to write type-safe and reusable code. Introduced in Java 5, they let classes, interfaces, and
methods operate on objects of various types, while maintaining compile-time type checking.
For example:

List<String> list = new ArrayList<>();

Here, generics ensure that only String elements can be added to the list.

2. What is the advantage of using generics?


Generics offer several advantages:

• Type Safety: Prevents runtime ClassCastException by catching errors at compile time.

• Code Reusability: Write methods or classes once and use them for any type.

• Cleaner Code: No need for explicit type casting.

Example:

List<Integer> list = new ArrayList<>();

list.add(10); // no casting needed later

3. How do generics provide type safety?


Generics enforce compile-time checks. When you specify a type (e.g., List<String>), the compiler ensures that
only objects of that type can be inserted, reducing the chances of runtime type errors.

List<String> names = new ArrayList<>();

names.add("Alice");

// names.add(123); // Compile-time error

4. What is type erasure in generics?


Type erasure is how Java implements generics internally. At runtime, the generic type information is erased,
and replaced with raw types.
So List<String> becomes just List at runtime. This is why reflection doesn’t retain generic type info.

5. Can we use primitive types like int, char with generics?


No, Java generics don’t support primitive types like int or char directly. You must use their wrapper classes
like Integer, Character, etc.
Example:

List<Integer> list = new ArrayList<>();

6. What is a bounded type parameter?


A bounded type parameter restricts the types that can be used as arguments. For example:

public <T extends Number> void show(T num) { ... }

Here, T can only be a subclass of Number like Integer, Float, etc.


7. What is the difference between <T> and <?> in generics?

• <T> defines a generic type — a placeholder for a specific type you’ll provide.

• <?> is a wildcard — it means an unknown type, mainly used for reading.

Example:

public <T> void print(T value) { ... } // defines generic type

public void printList(List<?> list) { ... } // accepts any type of list

8. Explain <? extends T> vs <? super T>

• <? extends T>: You can read subtypes of T. (Used for reading)

• <? super T>: You can write T and its subtypes. (Used for writing)

Example:

List<? extends Number> nums = new ArrayList<Integer>(); // read-only

List<? super Integer> ints = new ArrayList<Number>(); // can add Integer

Remember:

• Use extends when you only read from the collection.

• Use super when you only write to the collection.

9. Can we create a generic array in Java?


No, Java doesn’t allow direct creation of generic arrays due to type erasure.
For example, T[] arr = new T[10]; causes a compile-time error.
A workaround is:

@SuppressWarnings("unchecked")

T[] arr = (T[]) new Object[10];

But it requires caution and usually a warning suppression.

10. What are generic methods? How do you define one?


A generic method is a method that declares its own type parameter(s). These can be different from the class-
level generics.
Syntax:

public <T> void printArray(T[] array) {

for (T element : array)

System.out.println(element);

You can call it with any type of array — Integer[], String[], etc. — and it will work.
JDBC (Java Database Connectivity)

1. What is JDBC in Java?


JDBC (Java Database Connectivity) is an API provided by Java to connect and interact with relational
databases. It allows Java programs to send SQL queries and receive results, perform CRUD operations, and
manage transactions directly with a database.

2. What are the different types of JDBC drivers?


There are 4 types of JDBC drivers:

• Type 1 – JDBC-ODBC Bridge Driver: Translates JDBC calls into ODBC calls.
• Type 2 – Native-API Driver: Converts JDBC calls into native DB API calls.
• Type 3 – Network Protocol Driver: Sends JDBC calls to a middleware server.
• Type 4 – Thin Driver (Pure Java Driver): Converts JDBC calls directly into database-specific protocol.
Most commonly used.
3. Which JDBC driver type is platform-independent and pure Java?
Type 4 (Thin driver) is pure Java, platform-independent, and directly communicates with the database using
the database’s native protocol. It's the most widely used in production.

4. What is the role of the DriverManager class?


DriverManager acts as a factory for database connections. It manages the set of registered JDBC drivers and
establishes a connection by matching a URL to the appropriate driver.

Connection con = DriverManager.getConnection(url, user, pass);

5. How do you register a JDBC driver?


Typically, we use Class.forName() to register the driver:

Class.forName("com.mysql.cj.jdbc.Driver");

In JDBC 4.0 and above, drivers are auto-registered if present in the classpath.

6. What is the difference between Class.forName() and DriverManager.registerDriver()?

• Class.forName() loads and registers the driver class implicitly (via static block).

• DriverManager.registerDriver() registers the driver explicitly using an object.

DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

7. What is a JDBC URL? Give an example.


A JDBC URL is a string used to connect to the database. It includes protocol, sub-protocol, host, port, and DB
name.
Example for MySQL:
jdbc:mysql://localhost:3306/studentdb
8. What is the difference between ODBC and JDBC?

• ODBC is language-independent, requires native drivers.

• JDBC is Java-specific, doesn’t need native libraries.


Also, JDBC is preferred in Java applications for better portability and security.
9. Which JDBC driver is commonly used with MySQL?
MySQL Connector/J, which is a Type 4 JDBC driver:

com.mysql.cj.jdbc.Driver

10. How do you load a JDBC driver for Oracle?


Use:

Class.forName("oracle.jdbc.driver.OracleDriver");

For JDBC 4.0 and above, this is optional if the driver JAR is included in the classpath.

11. What is the role of the Connection interface in JDBC?


The Connection interface represents a session with a database.
It is used to:

• Establish communication with the database.

• Create Statement, PreparedStatement, and CallableStatement objects.

• Manage transactions (commit, rollback).

Example:

Connection con = DriverManager.getConnection(url, user, pass);

12. How do you establish a connection to a database in JDBC?


To connect to a DB:
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String pass = "1234";
Connection con = DriverManager.getConnection(url, user, pass);
Make sure the JDBC driver is loaded and the database is running.
13. What is the difference between Statement and PreparedStatement?

Feature Statement PreparedStatement

SQL Query Hardcoded Parameterized

Performance Slower Faster (precompiled)

Security Prone to SQL injection Prevents SQL injection

14. What are the benefits of using PreparedStatement over Statement?

• Prevents SQL injection attacks

• Better performance for repeated queries (precompiled SQL)

• Easier to set dynamic values using ? placeholders

Example:

PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");


ps.setInt(1, 101);
15. What is CallableStatement used for?
CallableStatement is used to call stored procedures in the database.

Example:

CallableStatement cs = con.prepareCall("{call getSalary(?)}");


cs.setInt(1, 101);
16. How do you handle SQL exceptions in JDBC?
Use a try-catch block for SQLException and log the details:

try {
// JDBC code
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}

17. How do you close JDBC resources properly?


Always close in reverse order of opening:

rs.close();
stmt.close();
con.close();
Or use try-with-resources:

try (Connection con = DriverManager.getConnection(...)) {


// work with connection
}

18. What is connection pooling?


Connection pooling is a technique where a pool of pre-established DB connections is maintained and reused.
It improves performance by:
• Avoiding the overhead of opening/closing connections repeatedly.
Tools like HikariCP, Apache DBCP, or Tomcat JDBC Pool are commonly used.
19. What is auto-commit in JDBC?
By default, JDBC runs in auto-commit mode, which means each SQL statement is committed immediately after
execution.
You can disable it like this:
con.setAutoCommit(false);
20. How do you disable auto-commit and manage transactions manually?

con.setAutoCommit(false);
try {
// multiple SQL statements
con.commit(); // only if all successful
} catch (SQLException e) {
con.rollback(); // if error occurs
}
This gives full control over the transaction.
21. How do you perform an INSERT operation using JDBC?

You use PreparedStatement to insert data safely and efficiently.

Example:

String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ps.setString(2, "Gaurav");
ps.setInt(3, 22);
int rowsInserted = ps.executeUpdate();
“Using PreparedStatement avoids SQL injection and ensures the statement is compiled once and reused.”

22. How do you retrieve records from a table using ResultSet?

You use Statement or PreparedStatement with executeQuery().

Example:

String sql = "SELECT * FROM student";


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id + " " + name + " " + age);
}

23. How do you update a row in a database using JDBC?

Example:

String sql = "UPDATE student SET age = ? WHERE id = ?";


PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 23);
ps.setInt(2, 101);
int rowsUpdated = ps.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated.");
“Only the required field is updated, improving efficiency and clarity.”

24. How do you delete a row using JDBC?

Example:

String sql = "DELETE FROM student WHERE id = ?";


PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
int rowsDeleted = ps.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
25. How do you handle user input for SQL queries securely?

Answer:
Use PreparedStatement. Never concatenate user inputs directly into SQL queries as it can lead to SQL
Injection.

Bad:

Statement stmt = con.createStatement();

stmt.executeQuery("SELECT * FROM student WHERE name = '" + userInput + "'");

Good:

PreparedStatement ps = con.prepareStatement("SELECT * FROM student WHERE name = ?");

ps.setString(1, userInput);

26. How do you use batch updates in JDBC?

Batching allows multiple queries to be grouped and executed together—improving performance.

Example:

String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
ps.setInt(1, 100 + i);
ps.setString(2, "Name" + i);
ps.setInt(3, 20 + i);
ps.addBatch();
}
int[] results = ps.executeBatch();

27. How do you fetch the number of rows affected by an update?

Every executeUpdate() method returns an int which represents the number of rows affected.

Example:

int rows = ps.executeUpdate();


System.out.println(rows + " row(s) affected.");
Perfect! Here's a detailed and interviewer-friendly explanation for the remaining:

28. What are different types of ResultSet in JDBC?

ResultSet types define how you can move through the result and whether it's updatable:

Common types:

• TYPE_FORWARD_ONLY – Default; moves only forward.

• TYPE_SCROLL_INSENSITIVE – Scrollable, not sensitive to DB changes after query.

• TYPE_SCROLL_SENSITIVE – Scrollable and sensitive to DB changes.


Example:

Statement stmt = con.createStatement(


ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
"Use scroll types when you need to move back and forth in results."

29. What is the difference between TYPE_FORWARD_ONLY and TYPE_SCROLL_INSENSITIVE?

Feature TYPE_FORWARD_ONLY TYPE_SCROLL_INSENSITIVE

Navigation Only forward Forward, backward, random

Performance Faster Slightly slower

Sensitive to DB changes No No

Use-case Simple reads Complex navigation

"Use TYPE_FORWARD_ONLY for performance and TYPE_SCROLL_INSENSITIVE when result navigation is


required."

30. Can you update a database record using ResultSet?

Yes, if the ResultSet is created with CONCUR_UPDATABLE.

Required settings:

• TYPE_SCROLL_SENSITIVE

• CONCUR_UPDATABLE

Example:

Statement stmt = con.createStatement(


ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = stmt.executeQuery("SELECT * FROM student WHERE id = 101");
if (rs.next()) {
rs.updateInt("age", 25);
rs.updateRow();
}

"Updating via ResultSet is handy when you need to fetch and modify records together."
Java Networking

1. What is Java Networking?


Java Networking refers to the communication between two or more computing devices using Java APIs. It
allows data to be sent and received over protocols like TCP and UDP using classes from java.net.

"Java provides built-in libraries for handling network communication, making it easy to build distributed apps."

2. What is the difference between TCP and UDP protocols?

TCP UDP

Connection-oriented Connectionless

Reliable (guarantees delivery) Unreliable but faster

Used for file transfer, web Used for streaming, gaming

"TCP is reliable but slower; UDP is lightweight but no guarantee of delivery."

3. What is a socket in Java?


A socket is an endpoint for communication between two machines. Java provides the Socket class for clients
and ServerSocket for servers to establish a TCP connection.

4. What is the difference between Socket and ServerSocket classes?

• Socket: Used by the client to connect to the server.

• ServerSocket: Waits for client connections on the server side.

"Think of ServerSocket as a doorman and Socket as the client knocking on the door."

5. How do you create a simple client-server communication using sockets?

Server:

ServerSocket ss = new ServerSocket(5000);


Socket s = ss.accept();
Client:
Socket s = new Socket("localhost", 5000);
"Client connects using Socket, and the server listens using ServerSocket."

6. What is the use of InetAddress class in networking?


It represents an IP address and provides methods like getLocalHost() and getByName() to retrieve hostnames
and IPs.

7. How do you read data from a URL in Java?

URL url = new URL("https://example.com");

BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

8. What is URLConnection and how is it different from HttpURLConnection?

• URLConnection: General-purpose for any protocol.


• HttpURLConnection: Subclass specific to HTTP requests.
"Use HttpURLConnection when working with REST APIs or web requests."
9. How do you send an HTTP GET request using HttpURLConnection?

URL url = new URL("https://api.example.com");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");

10. What are the advantages of using HttpURLConnection over third-party HTTP libraries?

• Comes with JDK (no dependency)

• Lightweight and secure

• Ideal for simple REST operations

"For basic HTTP tasks, HttpURLConnection avoids the overhead of third-party libraries."

Lambda Expressions & Functional Interfaces

1. What is a lambda expression in Java?


It is a short block of code that takes in parameters and returns a value, used primarily to implement functional
interfaces.

(int a, int b) -> a + b

"It brings cleaner, functional-style programming to Java."

2. What are the main benefits of using lambda expressions?

• More concise and readable code

• Enables functional programming

• Useful for passing behavior as arguments

3. What is a functional interface?


An interface with exactly one abstract method. Can have default or static methods.

"It's the backbone of lambda expressions."

4. Give an example of a functional interface in Java API.

• Runnable → void run()

• Comparator<T> → int compare(T o1, T o2)

5. What is the difference between lambda expressions and anonymous classes?

Lambda Anonymous Class

More concise Verbose

No this shadowing Has this for class

Only functional interfaces Can have multiple methods


6. How do you pass a lambda expression to a method?

Example with functional interface:

interface MathOperation {
int operate(int a, int b);
}
public void calculate(MathOperation op) {
System.out.println(op.operate(10, 20));
}
Call:

calculate((a, b) -> a + b);

7. What is the @FunctionalInterface annotation used for?

To indicate the interface is meant to have only one abstract method. It helps catch errors at compile time.

8. Can a functional interface have default and static methods?

Yes, as long as there’s only one abstract method.

@FunctionalInterface
interface Test {
void show();
default void log() {}
static void info() {}
}

9. How do lambda expressions relate to Java Streams and collections?

Lambdas are often used with stream operations like filter(), map(), forEach() to process data functionally.

list.stream().filter(s -> s.startsWith("A")).forEach(System.out::println);

10. What is method reference in Java, and how is it related to lambdas?

It’s a shorthand for a lambda that calls a method.

strList.forEach(System.out::println);

"Method references are concise and improve readability when the lambda just calls a method."
Streams API

1. What is the Java Streams API?


The Java Streams API is used to process data from collections in a functional and declarative way.
It allows operations like filtering, mapping, sorting, and collecting data without writing complex loops.
It was introduced in Java 8 to work efficiently with collections using stream pipelines.

2. What are the advantages of using streams over loops?


Streams help write cleaner and shorter code compared to traditional loops.
They support method chaining and internal iteration.
Also, they can be easily converted into parallel streams for faster processing using multiple threads.

3. What is the difference between Stream and Collection?


A Collection is a data structure that stores data in memory.
A Stream is used to process that data and does not store elements itself.
Also, streams are read-only and can be used only once, whereas collections can be reused.

4. What is the difference between intermediate and terminal operations in streams?


Intermediate operations like filter(), map() return a new stream and are lazy, meaning they don’t
process data immediately.
Terminal operations like collect(), forEach() trigger the actual processing and end the stream pipeline.
Without a terminal operation, the intermediate steps don’t execute.

5. What is filter() in streams?


The filter() method is used to select elements from a stream based on a condition.
It takes a predicate (a boolean condition) and returns a new stream containing only the matching
elements.
For example, stream.filter(x -> x > 10) keeps elements greater than 10.

6. How does map() differ from flatMap()?


map() is used to transform each element of the stream and return a new stream of the results.
flatMap() is used when each element needs to be converted into a stream and all such streams are
then flattened into a single stream.
It’s helpful when working with nested data structures like a list of lists.

7. What is the use of collect() and Collectors?


collect() is a terminal operation that gathers the stream elements into a result like a List, Set, or Map.
It works with Collectors utility methods like Collectors.toList() or toSet().
It's mainly used for grouping, joining, or transforming stream output into desired formats.

8. How do you use sorted() with streams?


The sorted() method is used to sort the stream elements either in natural order or using a custom
comparator.
For example, stream.sorted() sorts in ascending order, and stream.sorted(Comparator.reverseOrder())
sorts in descending order.
It is an intermediate operation that returns a new sorted stream.

9. What is the difference between sequential and parallel streams?


A sequential stream processes elements one after another in a single thread.
A parallel stream splits the data and processes parts of it in multiple threads for better performance.
However, parallel streams should be used carefully with large data and stateless operations.
10. Can a stream be reused after a terminal operation?
No, once a terminal operation like collect() or forEach() is executed, the stream is considered closed.
If you try to use it again, it will throw an IllegalStateException.
If you want to reuse, you need to create the stream again from the source collection.

Annotations

11. What is an annotation in Java?


An annotation is a special kind of metadata used to provide extra information to the compiler or tools.
It does not directly affect the program logic but helps in configuration, code generation, or runtime
behavior.
Examples include @Override, @Deprecated, and custom annotations.

12. What are the built-in annotations in Java?


Java provides several built-in annotations like:

o @Override to check if a method overrides a superclass method.

o @Deprecated to indicate that a method or class is outdated.

o @SuppressWarnings to hide compiler warnings.


These annotations improve code quality and communication with the compiler.

13. What is the purpose of @Override, @Deprecated, and @SuppressWarnings?

o @Override ensures we are correctly overriding a method; otherwise, it gives an error.

o @Deprecated tells developers not to use the method as it may be removed in future.

o @SuppressWarnings hides unnecessary compiler warnings for cleaner code.

14. What is the @FunctionalInterface annotation used for?


It is used to declare that an interface is meant to be a functional interface.
A functional interface has only one abstract method and can be used in lambda expressions.
It helps the compiler check and ensures that no additional abstract methods are added.

15. How do you create a custom annotation?


You can create it using the @interface keyword.
For example:

@interface MyAnnotation {
String value();
}
You can use it to add custom metadata on methods, classes, or fields.

16. What is a retention policy in annotations?


Retention policy defines how long the annotation should be retained.
There are three types:

o SOURCE (removed during compilation),

o CLASS (kept in bytecode),

o RUNTIME (available during execution using reflection).


Java 8+ Features

18. What is Optional in Java 8? Why is it used?


Optional is a container object used to represent the presence or absence of a value.
It helps avoid NullPointerException by providing methods to check if a value exists.
It's a better way to deal with null values in return types.

19. How do you create and check values in Optional?


You can create it using Optional.of(value), Optional.ofNullable(value), or Optional.empty().
You can check values using isPresent() or perform actions using ifPresent().
These methods help handle optional values cleanly and safely.

20. What are the methods of Optional like orElse(), orElseGet(), ifPresent()?

o orElse() returns a default value if optional is empty.

o orElseGet() returns value from a supplier function if empty.

o ifPresent() executes a lambda if the value is present.


These help reduce null checks in the code.

21. What is the purpose of default methods in interfaces?


Default methods allow you to add new methods to interfaces without affecting existing
implementations.
This was introduced in Java 8 to support backward compatibility.
Classes implementing the interface can use or override these default methods.

22. How do static methods in interfaces work?


Static methods in interfaces belong to the interface itself, not the implementing class.
They are called using InterfaceName.method().
They are useful for providing utility methods related to the interface.

23. Why were default and static methods introduced in interfaces?


Before Java 8, interfaces couldn’t have any method body.
Default and static methods were introduced to allow code reuse and avoid breaking existing
implementations when new methods are added.
It made interfaces more flexible and powerful.

24. What is the new Date and Time API in Java 8?


Java 8 introduced a new package java.time to handle date and time in a better way.
It includes classes like LocalDate, LocalTime, LocalDateTime, ZonedDateTime, etc.
These classes are immutable, thread-safe, and easier to use than the old Date/Calendar classes.

25. How does LocalDate, LocalTime, and LocalDateTime differ?

o LocalDate represents a date (like 2025-04-07).


o LocalTime represents only time (like 10:30 AM).
o LocalDateTime combines both date and time.
None of them store timezone information.
26. How do you format and parse date-time using DateTimeFormatter?
You can use DateTimeFormatter to convert date-time to strings and vice versa.
Example: DateTimeFormatter.ofPattern("dd-MM-yyyy") formats a date in custom style.
Parsing is done using LocalDate.parse("07-04-2025", formatter).

27. What is the Period and Duration class used for?

o Period is used to measure time in days, months, and years between two dates.

o Duration is used to measure time in hours, minutes, seconds between two times.
Both help in calculating time differences in a readable way.

28. What is the difference between Instant and ZonedDateTime?

o Instant represents a timestamp in UTC time.

o ZonedDateTime includes date, time, and time zone information.


Use ZonedDateTime when you need to work with time zones.

29. How do you calculate date differences in Java 8?


You can use Period.between(startDate, endDate) to calculate the difference in days, months, or years.
For time, Duration.between(startTime, endTime) gives the result in seconds or minutes.
These classes make date and time calculations easier.

30. How is the new Date-Time API better than the old java.util.Date and Calendar?
The new API is immutable, thread-safe, and follows a clean design.
It avoids confusion with months (starting from 0), handles time zones better, and supports
formatting/parsing easily.
Overall, it is much easier and safer to use.

You might also like