Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

What is Enum?

A special class that represents a fixed set of constants.
java
QUBITS OF DPK
1enum Day {
2    MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
3    FRIDAY, SATURDAY, SUNDAY
4}
5
6Day today = Day.MONDAY;
7System.out.println(today);   // MONDAY

Enum with if and switch

java
QUBITS OF DPK
1Day day = Day.FRIDAY;
2
3// if
4if (day == Day.SATURDAY || day == Day.SUNDAY) {
5    System.out.println("Weekend!");
6}
7
8// switch
9switch (day) {
10    case MONDAY:  System.out.println("Work!"); break;
11    case FRIDAY:  System.out.println("TGIF!"); break;
12    default:      System.out.println("Midweek");
13}

Enum as Class (with fields/methods)

java
QUBITS OF DPK
1enum Planet {
2    MERCURY(3.303e+23, 2.4397e6),
3    EARTH  (5.976e+24, 6.37814e6),
4    MARS   (6.421e+23, 3.3972e6);
5
6    private final double mass;
7    private final double radius;
8
9    Planet(double mass, double radius) {
10        this.mass   = mass;
11        this.radius = radius;
12    }
13
14    double surfaceGravity() {
15        return 6.67300E-11 * mass / (radius * radius);
16    }
17}
18
19System.out.println(Planet.EARTH.surfaceGravity());

Annotations

Metadata that provides information to the compiler or JVM about the code.
java
QUBITS OF DPK
1@Override        // tells compiler this overrides a parent method
2@Deprecated      // marks as outdated, warns users
3@SuppressWarnings("unchecked")   // suppress compiler warnings
4
5// Custom annotation
6@interface MyAnnotation {
7    String value();
8    int count() default 1;
9}
10
11@MyAnnotation(value = "test", count = 3)
12public class MyClass { }

Types of Interfaces & Functional Interface

javascript
QUBITS OF DPK
1Normal Interface     → multiple abstract methods
2Functional Interface → exactly ONE abstract method (SAM)
3Marker Interface     → no methods (Serializable, Cloneable)
java
QUBITS OF DPK
1@FunctionalInterface
2interface Calculator {
3    int calculate(int a, int b);   // only ONE abstract method
4}
5
6// Implement with anonymous class
7Calculator add = new Calculator() {
8    @Override
9    public int calculate(int a, int b) { return a + b; }
10};
11
12// Or with Lambda (clean!)
13Calculator add = (a, b) -> a + b;
14Calculator multiply = (a, b) -> a * b;
15
16System.out.println(add.calculate(5, 3));       // 8
17System.out.println(multiply.calculate(5, 3));  // 15

Lambda Expressions

A concise way to represent a functional interface implementation.
javascript
QUBITS OF DPK
1Syntax: (parameters) -> expression
2        (parameters) -> { statements; }
java
QUBITS OF DPK
1// Without lambda
2Runnable r1 = new Runnable() {
3    @Override
4    public void run() {
5        System.out.println("Running!");
6    }
7};
8
9// With lambda — clean!
10Runnable r2 = () -> System.out.println("Running!");
11
12// With return
13Calculator square = (n) -> n * n;
14int result = square.calculate(5, 0);  // not ideal example but shows syntax
15
16// Multi-line lambda
17Calculator complex = (a, b) -> {
18    int sum = a + b;
19    int product = a * b;
20    return sum + product;
21};

Common Built-in Functional Interfaces

java
QUBITS OF DPK
1Function<Integer, Integer> square = x -> x * x;
2Predicate<Integer> isEven = x -> x % 2 == 0;
3Consumer<String> printer = s -> System.out.println(s);
4Supplier<String> greeter = () -> "Hello, World!";

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Enum can't be instantiated with new
2Day d = new Day();   // ❌ compile error!
3
4// Trap 2 — @FunctionalInterface with more than 1 abstract method
5@FunctionalInterface
6interface Wrong {
7    void method1();
8    void method2();   // ❌ not a functional interface!
9}
10
11// Trap 3 — Lambda only works with functional interfaces
12// Not with regular multi-method interfaces
13
14// Trap 4 — Enum values() method
15for (Day d : Day.values()) {
16    System.out.println(d);   // iterates all enum constants
17}

Interview Answer (SDE-2)

"Enum is a type-safe way to represent fixed constants — more powerful than int constants since it's a full class with methods, fields, and constructors. Annotations are metadata markers that inform the compiler or runtime — built-ins include @Override, @Deprecated. A Functional Interface has exactly one abstract method — SAM (Single Abstract Method) type — and can be implemented with a lambda expression. Lambda is a concise anonymous function — it enables functional programming style in Java. Common functional interfaces: Function, Predicate, Consumer, Supplier."

Interview Questions & MAANG-Level Answers

Q1. What is enum and why use it over constants?
Enum is a special class representing a fixed set of named constants. Over int constants: (1) Type safetyDay day = Day.MONDAY prevents passing invalid int like 99. (2) ReadabilityDay.FRIDAY is self-documenting vs magic number 5. (3) Rich behavior — enums can have fields, methods, constructors. (4) switch support — works cleanly in switch. (5) Singleton guarantee — each enum constant is a singleton. Java's values() method iterates all constants.
Q2. Can enum have methods and constructors?
Yes. Enum is a full class — it can have fields, constructors (always private), and methods:
java
QUBITS OF DPK
1enum Planet {
2    EARTH(5.976e+24, 6.37e6),
3    MARS(6.42e+23, 3.39e6);
4    private final double mass, radius;
5    Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
6    double gravity() { return 6.67e-11 * mass / (radius * radius); }
7}
8System.out.println(Planet.EARTH.gravity());  // works!
Q3. What is a functional interface?
A functional interface has exactly ONE abstract method (SAM — Single Abstract Method). It can have multiple default/static methods. Annotated with @FunctionalInterface (optional but recommended — compiler enforces SAM). Can be implemented with a lambda expression. Built-in examples: Runnable (run()), Callable (call()), Comparator (compare()), and Java 8's Function, Predicate, Consumer, Supplier.
Q4. What is a lambda expression?
A lambda is a concise anonymous function — shorthand for implementing a functional interface. Syntax: (params) -> expression or (params) -> { statements; return value; }. It captures its enclosing scope's effectively final variables. Key benefits: removes boilerplate anonymous inner class code, enables functional programming style, works with Stream API:
java
QUBITS OF DPK
1// Before lambda
2list.sort(new Comparator<String>() { public int compare(String a, String b) { return a.compareTo(b); } });
3// With lambda
4list.sort((a, b) -> a.compareTo(b));
5// With method reference
6list.sort(String::compareTo);
Q5. What is the difference between @Override and @Deprecated?
@Override is a compile-time annotation that verifies the method actually overrides a parent method — compiler error if not. @Deprecated marks a method/class as outdated and discourages use — compiler generates a warning when deprecated code is called. Neither changes runtime behavior, both are informational. @SuppressWarnings("deprecation") suppresses the warning when you must use deprecated code.
Q6. What are the built-in functional interfaces in Java?
In java.util.function:
java
QUBITS OF DPK
1Function<T, R>     – takes T, returns R    – x -> x * 2
2Predicate<T>       – takes T, returns boolean – x -> x > 0
3Consumer<T>        – takes T, returns void  – x -> System.out.println(x)
4Supplier<T>        – takes nothing, returns T() -> new User()
5BiFunction<T,U,R>  – takes T and U, returns R
6UnaryOperator<T>Function<T,T> – x -> x + 1
7BinaryOperator<T>BiFunction<T,T,T>
Used heavily in Stream API and CompletableFuture.
Q7. Can a lambda expression throw checked exceptions?
Not directly if the functional interface's method doesn't declare it. Consumer<String> accepts (String) -> void — if your lambda throws IOException (checked), it won't compile. Workarounds: (1) Wrap in try-catch inside lambda. (2) Create a custom functional interface that declares the checked exception: @FunctionalInterface interface ThrowingConsumer<T> { void accept(T t) throws Exception; }. (3) Use utility methods that wrap checked exceptions as unchecked.