BCS403 · Object Oriented Programming with Java · Unit 3
Java New Features
Unit Scope & Exam Weightage: This unit covers Functional Interfaces, Lambda Expression, Method References, Stream API, Default Methods, Static Method, Base64 Encode and Decode, ForEach Method, Try-with-resources, Type Annotations, Repeating Annotations, Java Module System, Diamond Syntax with Inner Anonymous Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, Text Blocks, Records, and Sealed Classes. AKTU repeatedly asks 7-mark lambda/Stream programs and 2–7 mark theory on records, sealed classes, annotations and switch expressions.
Importance-Wise Roadmap (BCS403 Unit 3)
| Priority | Exact Syllabus Topic | PYQ Evidence | Marks Pattern | Tag |
|---|---|---|---|---|
| 1 | Functional Interfaces + Lambda Expression | 2023-24, 2024-25 (real); 2025-26 (predicted cluster) | 7m × 2 + 7m predicted + 2m | Highest yield |
| 2 | Stream API | 2023-24, 2024-25, 2025-26 (predicted clusters) | 7m × 3 predicted | Program core |
| 3 | Type Annotations | 2024-25 (real) | 7m | Code + theory |
| 4 | Switch Expressions + Yield | 2023-24 (real) | 7m | Comparison |
| 5 | Records + Sealed Classes | 2025-26 (real 7m), 2023-24 (real 2m) | 7m + 2m | Data modelling |
| 6 | ForEach Method, Diamond Syntax | 2023-24 / 2025-26 (real 2m each) | 2m × 2 | Quick marks |
| 7 | Method References, Default/Static Methods, Base64, Try-with-resources, Modules, var, Text Blocks, Repeating Annotations |
Not directly asked | Predicted 2–7m | Complete coverage |
Java-new-features examiner guidance: For every lambda or Stream answer, write the functional interface signature first, then the lambda body, then the output. For language features such as records and sealed classes, name the Java version and show a compilable class declaration — abstract descriptions alone earn low marks.
1. Functional Interfaces and Lambda Expressions
Functional interface: an interface containing exactly one abstract method. It may also contain default, static and private methods and overrides of Object methods. It is annotated with @FunctionalInterface, which makes the compiler reject a second abstract method.
PYQ (2024-25, 2 marks): "What is a functional interface? Give an example." Answer: one abstract method; example
Runnablehasvoid run(). A custom example isinterface Calc { int operate(int a, int b); }.
| Built-in functional interface | Abstract method | Typical use |
|---|---|---|
Runnable |
void run() |
Task with no input/result |
Predicate<T> |
boolean test(T t) |
Filter condition |
Function<T,R> |
R apply(T t) |
Transform value |
Consumer<T> |
void accept(T t) |
Print/save value |
Supplier<T> |
T get() |
Lazy value creation |
Comparator<T> |
int compare(T a,T b) |
Sorting order |
1.1 Lambda Syntax
Lambda = (parameters) -> expression or (parameters) -> { statements; }.
The compiler checks the lambda against the single abstract method of the target functional interface — this is called target typing. Parameter types and parentheses may be omitted when inferable.
PYQ (2024-25, 7 marks): "What are functional interfaces and how are they implemented using lambda expressions?"
Step 1: Define the contract. interface Op { int apply(int a, int b); } has exactly one abstract method, so it is functional.
Step 2: Implement with lambdas and invoke through the interface reference:
@FunctionalInterface
interface Op {
int apply(int a, int b);
}
public class LambdaBasics {
public static void main(String[] args) {
Op add = (a, b) -> a + b; // expression body
Op squareSum = (a, b) -> a * a + b * b; // another implementation
Op show = (a, b) -> { // block body
int result = a - b;
System.out.println("computed " + result);
return result;
};
System.out.println(add.apply(4, 3));
System.out.println(squareSum.apply(4, 3));
show.apply(9, 5);
}
}
Output:
7
25
computed 4
Step 3: Marks line — Op is functional because it has one abstract method; each lambda supplies its body; dynamic dispatch calls the implementation stored in the variable.
Predicted (bank
PRED, 2025-26, 7 marks): "What is a Functional Interface in Java? Write a program that uses Lambda Expressions to perform basic arithmetic operations (Add, Sub, Mul) via a custom Functional Interface."
@FunctionalInterface
interface Arithmetic {
double calculate(double x, double y);
}
public class ArithmeticLambdas {
public static void main(String[] args) {
Arithmetic add = (x, y) -> x + y;
Arithmetic sub = (x, y) -> x - y;
Arithmetic mul = (x, y) -> x * y;
System.out.println("Add = " + add.calculate(8, 3));
System.out.println("Sub = " + sub.calculate(8, 3));
System.out.println("Mul = " + mul.calculate(8, 3));
}
}
Output:
Add = 11.0
Sub = 5.0
Mul = 24.0
No Div is added because division by zero would need separate validation — a good examiner discussion point.
Predicted (bank
PRED, 2023-24, 7 marks): "Explain the functional interfaces in Java. Describe lambda expressions with the help of functional interfaces." Use the definition, the built-in-interface table, and theArithmeticLambdasprogram; add that lambdas remove anonymous-class boilerplate:new Runnable(){ public void run(){...} }becomes() -> {...}.
1.2 Method References
A method reference is a compact lambda that calls an existing method: Class::staticMethod, object::instanceMethod, Class::instanceMethod, or Class::new.
| Lambda | Equivalent method reference |
|---|---|
s -> System.out.println(s) |
System.out::println |
s -> s.length() |
String::length |
(a,b) -> Math.max(a,b) |
Math::max |
() -> new ArrayList<String>() |
ArrayList<String>::new |
List<String> names = Arrays.asList("Riya", "Aman", "Neha");
names.forEach(System.out::println); // reference to an object's method
names.sort(Comparator.comparing(String::length)); // reference to an instance method
2. Stream API
Stream API: a Java 8 facility for processing a sequence of elements in a declarative, functional style. A Stream is not a data structure; it takes input from a collection/array and produces a result through a pipeline of operations.
| Operation kind | Examples | Behaviour |
|---|---|---|
| Source | list.stream(), Arrays.stream(a), Stream.of(...) |
Creates the pipeline |
| Intermediate | filter, map, distinct, sorted, limit, skip, peek |
Returns another stream; lazy |
| Terminal | forEach, collect, count, sum, min, max, anyMatch, reduce |
Produces a value/side effect; closes the pipeline |
Key properties: intermediate operations are not executed until a terminal operation is invoked; streams are consumed once and cannot be reused; map transforms, filter selects, reduce/collect summarise; parallelStream() splits work across the ForkJoin pool when ordering is not required.
Predicted (bank
PRED, 2024-25, 7 marks): "What is the Stream API in Java? How does it help in functional-style operations?" Answer with the definition, the three-stage pipeline, the intermediate/terminal table, and onefilter(...).map(...).collect(...)example. Emphasise that the programmer states what is needed, not how to loop.
Predicted (bank
PRED, 2025-26, 7 marks): "What is Stream API? Use the Stream API to process a list of Employee objects: filter those with salary > 50000, and print their names in uppercase."
import java.util.*;
import java.util.stream.*;
class Employee {
String name;
double salary;
Employee(String n, double s) { name = n; salary = s; }
}
public class EmployeeStream {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Aditi", 62000),
new Employee("Rahul", 45000),
new Employee("Neha", 75000),
new Employee("Karan", 50000)
);
employees.stream()
.filter(e -> e.salary > 50000) // intermediate: predicate
.map(e -> e.name.toUpperCase()) // intermediate: transform
.forEach(System.out::println); // terminal: print
}
}
Output:
ADITI
NEHA
Karan is excluded because the condition is strictly > 50000, not >=.
Predicted (bank
PRED, 2023-24, 7 marks): "Explain Java stream API and its applications. Describe Intermediate and terminal operations with suitable example. Write a program to print sum of all even numbers form an ArrayList containing all integers from 1 to 10."
import java.util.*;
public class EvenSumStream {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
for (int i = 1; i <= 10; i++) nums.add(i);
int sum = nums.stream()
.filter(n -> n % 2 == 0) // 2,4,6,8,10
.mapToInt(Integer::intValue)
.sum(); // terminal reduction
System.out.println("Sum of even numbers = " + sum);
}
}
Output: Sum of even numbers = 30 (2 + 4 + 6 + 8 + 10).
PYQ (2023-24, 2 marks): "Write a Java program to create an ArrayList with five items and display all the elements using forEach method."
import java.util.*;
public class ForEachDemo {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(Arrays.asList(
"Lucknow", "Kanpur", "Varanasi", "Agra", "Prayagraj"));
cities.forEach(System.out::println); // Iterable.forEach + method reference
}
}
Output: the five city names, one per line, in insertion order.
3. Interface Evolution, Encoding, Resources and Modules
3.1 Default and Static Methods
Predicted (bank
PRED): "Explain default and static methods in interfaces with examples." Adefaultmethod has a body and is inherited by implementers, allowing an interface to grow without breaking existing classes. Astaticinterface method is called only on the interface name and is not inherited.
interface Transport {
default void start() { System.out.println("Engine started"); } // inherited
static void fuelType() { System.out.println("Petrol/Diesel/EV"); }
}
class Bus implements Transport { }
// new Bus().start(); -> Engine started
// Transport.fuelType(); -> Petrol/Diesel/EV
If two interfaces provide the same default method, the implementing class must override it; a class method always wins over an interface default.
3.2 Base64 Encode and Decode
java.util.Base64 (Java 8) converts binary data into printable ASCII and back — useful in tokens, e-mail attachments and JSON payloads.
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64Demo {
public static void main(String[] args) {
String text = "AKTU";
String enc = Base64.getEncoder().encodeToString(
text.getBytes(StandardCharsets.UTF_8));
String dec = new String(Base64.getDecoder().decode(enc),
StandardCharsets.UTF_8);
System.out.println("Encoded: " + enc);
System.out.println("Decoded: " + dec);
}
}
Output: Encoded: QUtUVQ== and Decoded: AKTU. The == padding keeps the encoded length a multiple of four.
3.3 Try-with-resources
A resource declared inside try(...) is closed automatically at block exit, even on an exception; it replaces nested finally blocks and suppresses secondary close exceptions.
try (java.util.Scanner sc = new java.util.Scanner(System.in)) {
System.out.println("Type a word: " + sc.next());
} // sc.close() is automatic; no finally needed
The resource class must implement AutoCloseable (or Closeable).
3.4 Java Module System (JPMS)
Introduced in Java 9, a module is a named, self-describing collection of packages. module-info.java declares what a module needs and exports:
module in.aktu.cse.app {
requires java.sql;
exports in.aktu.cse.app.api; // other modules may see only this package
}
Benefits: explicit dependencies, strong encapsulation (unexported packages are inaccessible), reliable configuration and smaller runtime images via jlink. requires transitive re-exports a dependency to downstream modules.
3.5 Diamond Syntax and Anonymous Classes
PYQ (2025-26, 2 marks): "Explain the Diamond Syntax (<>) introduced in Java 7. How does it make generic code easier to write?" The diamond operator lets the compiler infer type arguments from the assignment target:
Map<String, List<Integer>> m = new HashMap<>();instead of repeatingnew HashMap<String, List<Integer>>(). It removes duplication and reduces type errors. Since Java 9, the diamond may also be used with an anonymous inner class:List<String> list = new ArrayList<>() { };; before Java 9 the anonymous class had to restate the type arguments.
3.6 Local Variable Type Inference (var)
Java 10 allows var name = initializer; for local variables only. The compiler still infers a static type — Java remains strongly typed. Restrictions: no null initializer, no field/parameter/return type, no lambda target without explicit typing, and no declaration without an initializer.
var marks = 78; // inferred int
var names = List.of("A", "B"); // inferred List<String>
3.7 Text Blocks
Java 15 text blocks use triple double quotes to keep multi-line string formatting readable; trailing spaces are stripped and incidental indentation is removed.
String sql = """
SELECT id, name
FROM student
WHERE branch = 'CSE'
""";
4. Type Annotations, Repeating Annotations, Switch Expressions and Records
4.1 Annotations and Type Annotations
PYQ (2024-25, 7 marks): "Describe the role of annotations in Java and how type annotations are used."
Role: annotations are metadata consumed by the compiler (@Override, @Deprecated, @SuppressWarnings), by build tools (@Test), or at runtime through reflection. They do not change program logic by themselves but enable validation, code generation and configuration.
Java 8 extended annotations to almost any type use through ElementType.TYPE_USE, including generics, casts, arrays and new:
import java.lang.annotation.*;
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
@interface NonEmpty { }
public class TypeAnnotationDemo {
public static void main(String[] args) {
@NonEmpty String name = "Aditi"; // annotates the type use
String copy = (@NonEmpty String) name; // cast type annotated
System.out.println(name + " " + copy);
}
}
Output: Aditi Aditi. @Target(ElementType.TYPE_USE) is the decisive line — without it the annotation could not be placed on a cast or generic argument. A tool such as a checker framework can read @NonEmpty reflectively and reject an empty string.
Repeating annotations: Java 8 allows the same annotation more than once when it is declared @Repeatable and has a container annotation.
@Repeatable(Roles.class)
@interface Role { String value(); }
@interface Roles { Role[] value(); }
@Role("ADMIN") @Role("MENTOR")
class User { }
The compiler wraps repeated @Role entries into @Roles({...}); reflection can still call User.class.getAnnotationsByType(Role.class).
4.2 Switch Statement vs Switch Expression
PYQ (2023-24, 7 marks): "Compare and contrast switch-case statement with switch-expression in Java. Explain with suitable example."
| Basis | switch statement (traditional) |
switch expression (Java 14) |
|---|---|---|
| Purpose | Controls statement flow | Produces a value |
| Fall-through | Requires break in each case |
Arrow form has no fall-through |
| Syntax | case 1: ... break; |
case 1 -> value; |
| Multiple labels | case 1: case 2: |
case 1, 2 -> ... |
| Default | default: |
default -> ... (must be exhaustive) |
| Block value | Needs assignment inside case | yield value returns from a block |
| Null | Throws NPE | Throws NPE; pattern matching added later |
public class SwitchDemo {
static String gradeStatement(int marks) {
String g;
switch (marks / 10) {
case 9: case 10: g = "A+"; break;
case 8: g = "A"; break;
case 7: g = "B"; break;
default: g = "C";
}
return g;
}
static String gradeExpression(int marks) {
return switch (marks / 10) {
case 9, 10 -> "A+";
case 8 -> "A";
case 7 -> "B";
default -> "C";
};
}
static String withYield(int marks) {
return switch (marks / 10) {
case 9, 10 -> { yield "A+"; } // yield returns a value from a block
default -> "C";
};
}
public static void main(String[] args) {
System.out.println(gradeStatement(93) + " " + gradeExpression(93));
}
}
Output: A+ A+. yield is used only inside a switch-expression block; break is used in the statement form.
4.3 Records and Sealed Classes
PYQ (2025-26, 7 marks): "Describe Sealed Classes and Records in detail. How do these features improve data modeling in Java?"
Record (Java 16): a transparent carrier for immutable data. record Student(int roll, String name) { } automatically supplies a canonical constructor, private final fields, accessor methods roll() and name(), and generated equals, hashCode and toString. It reduces a 30-line POJO to one line and prevents accidental mutation. A compact constructor can validate inputs: Student { if (roll <= 0) throw new IllegalArgumentException(); }.
Sealed class (Java 17): restricts which classes may extend it, using permits; permitted subclasses must be final, sealed or non-sealed.
sealed class Shape permits Circle, Rectangle { } // closed hierarchy
final class Circle extends Shape {
final double r;
Circle(double r) { this.r = r; }
}
non-sealed class Rectangle extends Shape { } // further extension allowed
record Point(int x, int y) { }
public class ModelDemo {
public static void main(String[] args) {
System.out.println(new Point(2, 3));
System.out.println(new Circle(4) instanceof Shape);
}
}
Output: Point[x=2, y=3] followed by true.
Data-modelling improvement: records make DTOs/value objects concise and immutable; sealed classes replace open inheritance with an exhaustive, compiler-checked set of variants. Together they support algebraic data types — for example, a sealed Payment with record subclasses Card and UPI lets a switch expression check that every payment kind is handled.
PYQ (2023-24, 2 marks): "Explain the concept of Sealed classes in Java with suitable example." A sealed class is declared with
sealed ... permits A, B; only A and B may extend it. Example above; state that the modifier closes the hierarchy and enables exhaustive pattern matching.
5. Exam-Ready Question Index and Practice
| Question (source) | Where solved |
|---|---|
| Functional interface definition (2024-25, 2m) | §1 definition |
| Functional interfaces + lambdas (2024-25, 7m real) | §1.1 LambdaBasics |
| Arithmetic lambdas (2025-26, 7m predicted) | §1.1 ArithmeticLambdas |
| Stream API theory (2024-25, 7m predicted) | §2 pipeline table |
| Employee salary filter (2025-26, 7m predicted) | §2 EmployeeStream |
| Even-number sum (2023-24, 7m predicted) | §2 EvenSumStream |
| forEach with five strings (2023-24, 2m real) | §2 ForEachDemo |
| Type annotations (2024-25, 7m real) | §4.1 |
| Switch statement vs expression (2023-24, 7m real) | §4.2 |
| Sealed classes + records (2025-26, 7m real; 2023-24, 2m real) | §4.3 |
| Diamond syntax (2025-26, 2m real) | §3.5 |
Practice questions (label: practice, not real PYQs)
- Practice: Declare a functional interface
Converter<F,T>and implement it with a lambda that converts a String to its length. - Practice: Use a Stream to count words longer than four characters in a
List<String>. - Practice: Write a record
Marks(String subject, int score)with a compact constructor rejecting negative scores. - Practice: Convert a traditional
switchover days 1–7 into a switch expression usingcase 1, 2 -> .... - Practice: Create a sealed interface
Result permits Pass, Failwith record implementations and process them with a switch expression.
6. Last-Night Survival Checklist (Unit 3 only)
- One abstract method:
@FunctionalInterface+ target typing is the whole lambda story; memorisePredicate,Function,Consumer,Supplier,Comparator. - Stream pipeline: source → intermediate (
filter,map,sorted) → terminal (forEach,collect,sum); laziness and single-use are favourite theory points. - Three outputs to recall: arithmetic lambdas
11.0/5.0/24.0, employee filterADITI/NEHA, even sum30. - Syntax contrasts:
case x ->has no fall-through;yieldreturns from a block;varworks only for initialised locals;<>infers generic arguments. - Data models: record = immutable carrier with generated
equals/hashCode/toString; sealed = compiler-enforced permitted subclasses viapermits.
Final new-features reminder: State the Java version beside each feature (8 for lambda/Stream/Base64/type annotations, 9 for modules, 10 for var, 14/15 for switch/text blocks, 16 for records, 17 for sealed). Examiners reward this chronology because it prevents confusion between similar-looking features.