1.
Func onal Interface
Defini on: An interface with exactly one abstract method.
Use: Enables lambda expressions and method references.
Example: Runnable (has only run() method).
2. Lambda Expression
Defini on: A short block of code (anonymous func on) that can be passed around.
Syntax: (parameters) -> expression
Example: (a, b) -> a + b
Purpose: Makes code concise and func onal-style.
3. Method Reference
Defini on: A shorthand for calling exis ng methods using ::.
Types:
o Sta c method → ClassName::methodName
o Instance method → object::methodName
o Constructor → ClassName::new
Example: [Link]::println
4. Yield Keyword
Introduced in Java 13/14.
Use: Returns a value from a switch expression.
Example:
int result = switch(day) {
case MONDAY -> 1;
case TUESDAY -> yield 2;
default -> 0;
};
5. Default & Sta c Methods in Interfaces
Default method: Has a body inside interface, can be overridden.
Sta c method: Belongs to interface itself, not to implemen ng classes.
Purpose: Adds new func onality without breaking old code.
6. Encoding & Decoding in Java
Encoding: Conver ng data into another format (e.g., text → bytes).
Decoding: Reversing the process.
Common use: Base64 for binary-to-text conversion.
7. Base64 Encoding
Defini on: Represents binary data using A–Z, a–z, 0–9, +, /.
Use: Safe transmission of data in text-based formats (XML, JSON).
Java API: java.u l.Base64 class.
8. Try-with-Resources
Defini on: A try block that automa cally closes resources.
Requirement: Resource must implement AutoCloseable.
Example:
try(FileInputStream fis = new FileInputStream("fi[Link]")) {
// use fis
9. Type & Repea ng Annota ons
Type annota ons: Can be applied anywhere a type is used (e.g., @NonNull String).
Repea ng annota ons: Same annota on applied mul ple mes on one element.
10. forEach Method
Defini on: Default method in Iterable and also in Stream.
Use: Iterates elements with a Consumer (lambda or method reference).
Example:
[Link]([Link]::println);
11. Java Module System (JPMS)
Introduced in Java 9.
Defini on: Groups packages/resources into modules with a descriptor ([Link]).
Purpose: Be er encapsula on and dependency management.
12. Local Variable Type Inference (var)
Introduced in Java 10.
Defini on: Compiler infers type of local variables.
Example:
var list = new ArrayList<String>(); // inferred as ArrayList<String>
Explain Lambda Expressions with the help of suitable program
A lambda expression is essen ally a short block of code (like an anonymous func on) that can be passed around.
It’s mainly used to implement func onal interfaces (interfaces with a single abstract method).
Syntax:
(parameters) -> expression
import java.u l.*;
public class LambdaExample {
public sta c void main(String[] args) {
// Example 1: Runnable using Lambda
Runnable task = () -> [Link]("Running a task using Lambda!");
new Thread(task).start();
// Example 2: Using Lambda with forEach
List<String> names = [Link]("Ishita", "Rahul", "Sneha", "Amit");
[Link]("Names in the list:");
[Link](name -> [Link](name));
Write a Java program using Stream API to process a collec on.
import java.u l.*;
import java.u [Link].*;
class Student {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
public String getName() {
return name;
public int getMarks() {
return marks;
public class StreamExample {
public sta c void main(String[] args) {
List<Student> students = [Link](
new Student("Ishita", 85),
new Student("Rahul", 45),
new Student("Sneha", 72), );
// Process with Stream API
List<String> passedStudents = [Link]()
.filter(s -> [Link]() >= 60) // keep only students with marks >= 60
.sorted([Link](Student::getMarks).reversed()) // sort by marks descending
.map(Student::getName) // transform to names only
.collect([Link]()); // collect into a list
[Link]("Students who passed: " + passedStudents);
Explain default and sta c methods in interfaces with examples.
Default Methods in Interfaces
Defini on: Introduced in Java 8, default methods allow you to add new methods to interfaces without
breaking exis ng implementa ons.
Key Point: They have a body and can be overridden by implemen ng classes.
Syntax:
default void methodName() {
// method body
Sta c Methods in Interfaces
Defini on: Also introduced in Java 8, sta c methods belong to the interface itself, not to the implemen ng
class.
Key Point: They cannot be overridden and must be called using the interface name.
Syntax:
sta c void methodName() {
// method body
Code:-
interface Calculator {
sta c int add(int a, int b) {
return a + b;
public class Sta cMethodDemo {
public sta c void main(String[] args) {
int sum = [Link](10, 20); // called using interface name
[Link]("Sum = " + sum);
}}
Write a Java program to perform Base64 encoding and decoding.
Describe the role of annota ons in Java and how type annota ons are used.
Annota ons in Java are metadata that provide extra informa on to the compiler or run me without changing
program logic. Type annota ons, introduced in Java 8, extend this capability by allowing annota ons to be applied
wherever a type is used, enabling stronger type checking and integra on with pluggable type systems.
Role of Annota ons in Java
Metadata provider: Annota ons a ach informa on to classes, methods, variables, parameters, and
packages.
Compiler support: They help detect errors, suppress warnings (@SuppressWarnings), or enforce rules.
Code genera on: Tools can process annota ons to generate code, XML, or configura on files.
Run me processing: Frameworks like Spring and Hibernate use annota ons for dependency injec on,
mapping, and configura on.
Alterna ve to XML/config files: Annota ons reduce external configura on by embedding metadata directly
in code.
Categories of Annota ons
1. Marker annota ons (e.g., @Override) – no values, just mark.
2. Single-value annota ons (e.g., @SuppressWarnings("unchecked")).
3. Full annota ons – mul ple key–value pairs.
4. Type annota ons – applied anywhere a type is used.
5. Repea ng annota ons – same annota on applied mul ple mes.
Type Annota ons
Before Java 8: Annota ons could only be applied to declara ons (classes, methods, fields).
Since Java 8: They can be applied to any use of a type — variables, generic types, casts, and even implements
clauses.
Purpose: Enables pluggable type systems for stronger compile- me checks (e.g., null safety, immutability).
import [Link] on.*;
@Target(ElementType.TYPE_USE)
@interface NonNull {}
public class TypeAnnota onDemo {
public sta c void main(String[] args) {
@NonNull String name = "Ishita"; // annota on applied to type
[Link](name);
Write a Java program using try-with-resources to handle resources.
Explain Diamond Syntax with Inner Anonymous Class using example.
Introduced in Java 7 for generics.
Allows you to omit the type on the right-hand side of object crea on.
What are func onal interfaces and how are they implemented using lambda expressions?
A func onal interface is an interface that has exactly one abstract method.
It can have:
Mul ple default or sta c methods (these don’t count against the “one abstract method” rule).
Marked with the @Func onalInterface annota on (op onal but recommended).
Examples in Java:
Runnable → void run()
Callable<T> → T call()
Comparator<T> → int compare(T o1, T o2)
Why Func onal Interfaces Ma er
They are the founda on of lambda expressions and method references in Java.
Lambda expressions provide a shorter, cleaner way to implement func onal interfaces without wri ng
anonymous inner classes.
Explain the concept of Sealed classes in Java with suitable example.
Sealed classes in Java (introduced in Java 15 as a preview and finalized in Java 17) allow developers to ghtly
control inheritance by specifying exactly which classes or interfaces are permi ed to extend or implement them.
This is useful for modeling fixed hierarchies, improving security, and making code more predictable.
Concept of Sealed Classes
Normal class: Can be extended by any subclass.
Final class: Cannot be extended at all.
Sealed class: Can only be extended by a specific set of classes defined by the programmer.
Syntax:-
public sealed class Shape permits Circle, Rectangle, Square {
// common members
Program:-
// Sealed class
public sealed class Shape permits Rectangle, Square {
public abstract double area();
public final class Rectangle extends Shape {
private double length, width;
public Rectangle(double length, double width) {
[Link] = length; [Link] = width;
@Override
public double area() { return length * width; }
public final class Square extends Shape {
private double side;
public Square(double side) { [Link] = side; }
@Override
public double area() { return side * side; }
Explain the func onal interfaces in Java. Describe lambda expressions with the help of func onal interfaces.
Compare and contrast switch-case statement with switch-expression in Java. Explain with suitable example.
Switch-Case Statement (Old Style)
Available since early Java versions.
Used for control flow based on matching values.
Requires break statements to avoid fall-through.
Returns no value directly; it’s just a statement.
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Invalid day"; break;
[Link](dayName);
Switch Expression (Java 12+)
Introduced to make switch more concise and expressive.
Can be used as an expression that returns a value.
No need for break — each case is isolated.
Supports arrow syntax (->) and yield keyword.
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};
[Link](dayName);
Write a Java program to create an ArrayList<String> and display elements using forEach.
import java.u [Link];
public class ArrayListForEachExample {
public sta c void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
// Add elements to the ArrayList
[Link]("Ishita");
[Link]("Rahul");
[Link]("Sneha");
[Link]("Names in the ArrayList:");
[Link](name -> [Link](name));
}}
Explain List interface and compare ArrayList and LinkedList with program.
List is part of the Java Collec ons Framework.
It represents an ordered collec on (sequence) of elements.
Key features:
Allows duplicate elements.
Maintains inser on order.
Provides indexed access (get(int index)).
Common implementa ons: ArrayList, LinkedList, Vector.
import java.u l.*;
public class ListComparison {
public sta c void main(String[] args) {
// Using ArrayList
List<String> arrayList = new ArrayList<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("ArrayList elements:");
[Link]([Link]::println);
// Using LinkedList
List<String> linkedList = new LinkedList<>();
[Link]("Amit");
[Link]("Priya");
[Link]("\nLinkedList elements:");
[Link]([Link]::println);
// Demonstra ng performance difference
[Link]("\nAccessing second element:");
[Link]("ArrayList: " + [Link](1)); // O(1)
[Link]("LinkedList: " + [Link](1)); // O(n)
}}
Explain Set interface and its implementa ons (HashSet, LinkedHashSet, TreeSet) with the help of program
The Set Interface
Part of the Java Collec ons Framework.
Represents a collec on that does not allow duplicate elements.
Maintains unique elements only.
Common implementa ons:
o HashSet
o LinkedHashSet
o TreeSet
import java.u l.*;
public class SetExample {
public sta c void main(String[] args) {
// HashSet Example
Set<String> hashSet = new HashSet<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("Sneha");
[Link]("Rahul"); // duplicate ignored
[Link]("HashSet (no order, no duplicates): " + hashSet);
// LinkedHashSet Example
Set<String> linkedHashSet = new LinkedHashSet<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("Sneha");
[Link]("Rahul"); // duplicate ignored
[Link]("LinkedHashSet (inser on order): " + linkedHashSet);
// TreeSet Example
Set<String> treeSet = new TreeSet<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("Sneha");
[Link]("Rahul"); // duplicate ignored
[Link]("TreeSet (sorted order): " + treeSet);
}}
Discuss Map interface and explain HashMap, TreeMap, Hashtable with the help of program
The Map Interface
Part of the Java Collec ons Framework.
Stores data in key–value pairs.
Keys are unique, values can be duplicate.
Common implementa ons:
o HashMap TreeMap Hashtable
import java.u l.*;
public class MapExample {
public sta c void main(String[] args) {
// HashMap Example
Map<Integer, String> hashMap = new HashMap<>();
[Link](1, "Ishita");
[Link](2, "Rahul");
[Link](3, "Sneha");
[Link](2, "Amit"); // overwrites value for key 2
[Link]("HashMap (no order): " + hashMap);
// TreeMap Example
Map<Integer, String> treeMap = new TreeMap<>();
[Link](3, "Sneha");
[Link](1, "Ishita");
[Link](2, "Rahul");
[Link]("TreeMap (sorted by keys): " + treeMap);
// Hashtable Example
Map<Integer, String> hashtable = new Hashtable<>();
[Link](1, "Ishita");
[Link](2, "Rahul");
[Link](3, "Sneha");
[Link]("Hashtable (legacy, synchronized): " + hashtable);
// Accessing values
[Link]("\nAccessing values:");
[Link]("HashMap key 1: " + [Link](1));
[Link]("TreeMap key 2: " + [Link](2));
[Link]("Hashtable key 3: " + [Link](3));
Write a Java program demonstra ng Stack opera ons.
import java.u l.*;
public class StackExample {
public sta c void main(String[] args) {
// Create a Stack of Strings
Stack<String> stack = new Stack<>();
// Push elements onto the stack
[Link]("Ishita");
[Link]("Rahul");
[Link]("Sneha");
[Link]("Amit");
[Link]("Ini al Stack: " + stack);
// Peek at the top element
[Link]("Top element (peek): " + [Link]());
// Pop an element (removes top)
String popped = [Link]();
[Link]("Popped element: " + popped);
[Link]("Stack a er pop: " + stack);
// Search for an element (returns 1-based posi on from top)
int posi on = [Link]("Rahul");
if (posi on != -1) {
[Link]("Element 'Rahul' found at posi on: " + posi on);
} else {
[Link]("Element 'Rahul' not found.");
// Check if stack is empty
[Link]("Is stack empty? " + [Link]());
Write program to sort list using Comparable interface.
The Comparable interface is used to define the natural ordering of objects.
A class implements Comparable<T> and overrides the compareTo(T o) method.
Sor ng is then done automa cally using Collec [Link]() or [Link]().
import java.u l.*;
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
// Implement compareTo for natural ordering (by marks)
@Override
public int compareTo(Student other) {
return [Link]([Link], [Link]);
@Override
public String toString() {
return name + " (" + marks + ")";
public class ComparableExample {
public sta c void main(String[] args) {
List<Student> students = new ArrayList<>();
[Link](new Student("Ishita", 85));
[Link](new Student("Rahul", 72));
[Link](new Student("Sneha", 90));
[Link](new Student("Amit", 60));
[Link]("Before Sor ng:");
[Link]([Link]::println);
// Sort using Comparable (natural order by marks)
Collec [Link](students);
[Link]("\nA er Sor ng (by marks ascending):");
[Link]([Link]::println);
}
Differen ate Comparable and Comparator with example.
Comparable
Interface: [Link]<T>
Method: compareTo(T o)
Defines the natural ordering of objects (e.g., sort students by marks).
Implemented inside the class itself.
import java.u l.*;
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
// Natural ordering: by marks
@Override
public int compareTo(Student other) {
return [Link]([Link], [Link]);
@Override
public String toString() {
return name + " (" + marks + ")";
public class ComparableDemo {
public sta c void main(String[] args) {
List<Student> students = [Link](
new Student("Ishita", 85),
new Student("Rahul", 72),
new Student("Sneha", 90)
);
Collec [Link](students); // uses compareTo
[Link]("Sorted by marks (Comparable): " + students);
}
}
Comparator
Interface: java.u [Link]<T>
Method: compare(T o1, T o2)
Defines custom ordering outside the class (e.g., sort students by name).
Useful when you want mul ple sor ng criteria without changing the class itself.
import java.u l.*;
class Student {
String name;
int marks;
Student(String name, int marks) {
[Link] = name;
[Link] = marks;
@Override
public String toString() {
return name + " (" + marks + ")";
public class ComparatorDemo {
public sta c void main(String[] args) {
List<Student> students = [Link](
new Student("Ishita", 85),
new Student("Rahul", 72),
new Student("Sneha", 90)
);
// Sort by name using Comparator
Collec [Link](students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return [Link]([Link]);
});
[Link]("Sorted by name (Comparator): " + students);
}
Explain sor ng in Java Collec ons using Collec [Link]().
Key Points about Collec [Link]()
Belongs to: java.u [Link] ons class.
Works only on Lists: e.g., ArrayList, LinkedList.
Two Variants:
1. Collec [Link](List<T> list) → sorts using natural ordering (Comparable).
2. Collec [Link](List<T> list, Comparator<? super T> c) → sorts using a custom comparator.
Stable Sort: Equal elements retain their rela ve order.
Algorithm: TimSort (hybrid of merge sort and inser on sort).
Performance: O(n log n).
Explain the working of TreeMap in Java in detail. Discuss its features, internal working mechanism, and how it
maintains elements in sorted order
Features of TreeMap
Implements: Map, NavigableMap, SortedMap, Cloneable, Serializable.
Ordering: Keys are sorted in natural ascending order or by a Comparator provided at crea on.
No null keys: Unlike HashMap, TreeMap does not allow null keys (but allows mul ple null values).
Performance: All major opera ons (containsKey, get, put, remove) run in O(log n) me.
Navigable methods: Provides methods like firstKey(), lastKey(), higherKey(), lowerKey(), subMap(), etc.
Thread safety: Not synchronized; must be wrapped with Collec [Link]() if needed.
Internal Working Mechanism
Underlying Data Structure: TreeMap is implemented using a Red-Black Tree, a self-balancing binary search
tree.
Inser on: When a new key–value pair is added, the key is placed in the tree according to its order. The Red-
Black Tree ensures balance by recoloring and rota ons.
Searching: Keys are located by traversing the tree, ensuring O(log n) lookup.
Dele on: Removing a key involves restructuring the tree to maintain balance.
Sor ng: Keys are always maintained in sorted order automa cally.
import java.u l.*;
public class TreeMapExample {
public sta c void main(String[] args) {
// Natural ordering (ascending)
TreeMap<Integer, String> treeMap = new TreeMap<>();
[Link](3, "Sneha");
[Link](1, "Ishita");
[Link](2, "Rahul");
[Link](4, "Amit");
[Link]("TreeMap (natural order): " + treeMap);
// Accessing elements
[Link]("First Key: " + treeMap.firstKey());
[Link]("Last Key: " + [Link]());
[Link]("Higher Key than 2: " + [Link](2));
// Custom ordering (descending)
TreeMap<Integer, String> descMap = new TreeMap<>([Link]());
[Link](treeMap);
[Link]("TreeMap (descending order): " + descMap);
}}
Explain the Proper es class in Java in detail. Discuss its purpose, features, and how it is used to store and retrieve
configura on data in the form of key–value pairs
The Proper es class in Java is a specialized subclass of Hashtable<Object,Object> designed to handle configura on
data in the form of key–value pairs, where both keys and values are String. It’s widely used for storing applica on
se ngs, configura on files, and interna onaliza on (resource bundles).
Purpose
Provides a simple way to store and retrieve configura on data.
O en used with .proper es files (plain text files with key=value format).
Supports loading from and saving to streams (files, input streams, output streams).
Features
String-based storage: Both keys and values are strings.
Persistence: Can load and store data using load() and store() methods.
Default values: Supports chaining with default proper es.
Integra on: Commonly used in frameworks (Spring, JDBC, etc.) for configura on.
Thread safety: Inherits synchroniza on from Hashtable.
Internal Working
Internally extends Hashtable<Object,Object>.
Restricts keys and values to String.
Provides convenience methods like getProperty(String key) and setProperty(String key, String value).
When reading from a .proper es file, it parses lines in key=value format.
When wri ng, it stores them back in the same format.
import java.u l.*;
import [Link].*;
public class Proper esExample {
public sta c void main(String[] args) {
Proper es props = new Proper es();
// Set proper es
[Link]("username", "Ishita");
[Link]("password", "12345");
// Retrieve proper es
[Link]("Username: " + [Link]("username"));
[Link]("Password: " + [Link]("password"));
}}
Compare and contrast the List, Set, and Map interfaces in Java. Discuss their features, characteris cs, methods of
storing elements, handling of duplicate values, ordering mechanisms, and common implementa ons.
In Java, List, Set, and Map are the three core interfaces of the Collec ons Framework, each serving different
purposes: List stores ordered elements with duplicates allowed, Set stores unique elements without duplicates, and
Map stores key–value pairs with unique keys.
How They Store Elements
List → Stores elements sequen ally, supports posi onal access.
Set → Stores unique elements, typically backed by hashing (HashSet) or trees (TreeSet).
Map → Stores elements as key–value pairs, ensuring keys are unique.
import java.u l.*;
public class Collec onComparison {
public sta c void main(String[] args) {
// List Example
List<String> list = new ArrayList<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("Ishita"); // duplicate allowed
[Link]("List: " + list);
// Set Example
Set<String> set = new HashSet<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]("Ishita"); // duplicate ignored
[Link]("Set: " + set);
// Map Example
Map<Integer, String> map = new HashMap<>();
[Link](1, "Ishita");
[Link](2, "Rahul");
[Link](2, "Sneha"); // overwrites value for key 2
[Link]("Map: " + map);
1 ArrayList<String> list = new ArrayList<>();
[Link]("Ishita");
[Link]("Rahul");
[Link]([Link]::println);
2. Define Java Collec on Framework.
It is a unified architecture in Java that provides interfaces, classes, and algorithms to store, manipulate, and process
groups of objects efficiently.
3. What is Iterator interface? Write its methods.
Iterator is used to traverse elements in a collec on sequen ally.
Methods:
o boolean hasNext() → checks if more elements exist.
o E next() → returns next element.
o void remove() → removes current element.
4. Differen ate ArrayList and LinkedList.
ArrayList: Backed by dynamic array, fast random access, slower insert/delete in middle.
LinkedList: Backed by doubly linked list, fast insert/delete, slower random access.
5. What is HashSet?
A collec on that stores unique elements with no guaranteed order, implemented using a hash table.
6. Define Map interface.
A structure that stores key–value pairs, where keys are unique and values can be duplicate.
7. What is TreeSet? Explain with a suitable code snippet.
A Set implementa on that stores unique elements in sorted order using a Red-Black Tree.
TreeSet<Integer> set = new TreeSet<>();
[Link](5); [Link](1); [Link](3);
[Link](set); // [1, 3, 5]
8. Difference between HashMap and Hashtable.
HashMap: Non-synchronized, allows one null key and mul ple null values, faster.
Hashtable: Synchronized, does not allow null key or null values, legacy class.
9. Define Comparable interface.
An interface ([Link]) that defines natural ordering of objects using compareTo(T o).
10. What is Comparator interface?
An interface (java.u [Link]) used to define custom ordering of objects using compare(T o1, T o2).
11. Define LinkedHashSet.
A Set implementa on that maintains inser on order while ensuring unique elements.
12. What is Proper es class in Java?
A subclass of Hashtable used to store string-based key–value pairs, commonly for configura on files (.proper es)
with methods like load() and store().