B.E. / B.Tech.
- End Semester Theory Examinations – April /May 2025
Second Semester
Common to All Branches
24CS202– Java Programming (Lab Integrated)
Answer Key
Part-A (10 x 2 = 20 Marks)
1. What is the difference between == and .equals() in Java?
Each carries 1 mark
== checks reference equality — whether two object references point to the same memory
location.
.equals() checks value/content equality — whether two objects have equivalent values, as
defined by the method's implementation.
2. Write a Java code to demonstrate constructor overloading using a class Book.
Class definition – 1 mark
Constructor defined – 1 mark
class Book {
String title;
String author;
int year;
Book() {
title = "Unknown";
author = "Unknown";
year = 0;
}
Book(String t, String a) {
title = t;
author = a;
year = 0;
}
Book(String t, String a, int y) {
title = t;
author = a;
year = y;
}
void display() {
System.out.println(title + " by " + author + ", " + year);
}
public static void main(String[] args) {
Book b1 = new Book();
Book b2 = new Book("1984", "George Orwell");
Book b3 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
b1.display();
b2.display();
b3.display();
}
}
3. Define encapsulation. How is it achieved in Java?
Encapsulation – 1 mark
Achieved - 1 mark
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will
be hidden from other classes, and can be accessed only through the methods of their
current class. Therefore, it is also known as data hiding.
4. What is the purpose of the finally block in Java? Can it be skipped?
Purpose – 1 mark
Can it be skipped – 1 mark
The finally block is used to execute important cleanup code (like closing files, releasing
resources, closing database connections) regardless of whether an exception is thrown or
not. It always executes after the try and catch blocks.
Under normal circumstances, the finally block cannot be skipped. However, it can be skipped
in rare cases, such as:
1. Calling System.exit(0) before the finally block.
2. Power failure or hardware crash.
5. Write the syntax and use of the synchronized keyword in a method declaration.
Sybtax - 1mark
Use – 1 mark
In Java, the synchronized keyword ensures that only one thread can execute a specific block
of code or method at a time, preventing race conditions and data corruption in concurrent
environments.
Syntax
Java
synchronized returnType methodName(parameterList) {
// Method body
}
When a method is declared as synchronized, Java acquires a lock on the object associated
with the method before executing it.
6. Differentiate between Runnable interface and Thread class with a use case.
Each difference carries 1 mark
Thread is a class. It is used to create a thread
Runnable is a functional interface which is used to create a thread
Thread has multiple methods including start() and run()
Runnable has only abstract method run()
Each thread creates a unique object and gets associated with it
Multiple threads share the same objects.
More memory required
Less memory required
7. Write a Java program to check if a string is a palindrome.
Correct code – 2 marks
Partial – 1 mark
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input from user
System.out.print("Enter a string: ");
String original = sc.nextLine();
// Remove spaces and convert to lowercase
String cleaned = original.replaceAll("\\s+", "").toLowerCase();
// Reverse the string
String reversed = new StringBuilder(cleaned).reverse().toString();
// Check if original is equal to reversed
if (cleaned.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
sc.close();
}
}
8. What is the difference between HashMap and ArrayList?
Each carries 1 mark
ArrayList implements List Interface while HashMap is the implementation of Map interface.
ArrayList maintains the insertion order while HashMap does not maintain the insertion order
ArrayList returns the list items in the same order while HashMap doesn’t maintain any order
so returned key-values pairs any kind of order.
ArrayList stores the elements only as values and maintains internally the indexing for every
element. While HashMap stores elements with key and value pairs that means two objects.
So HashMap takes more memory comparatively.
ArrayList allows duplicate elements while HashMap doesn’t allow duplicate keys but does
allow duplicate values.
In ArrayList, an element can be fetched easily by specifying its index it. But in HashMap, the
elements are fetched by their corresponding key. It means that the key must be
remembered always.
9. List the types of JDBC drivers.
2 types – full marks
JDBC-ODBC Bridge Driver, Partial Java/Native-API Driver, Middleware/Network Protocol
Driver, Direct-to-database/Thin Driver
10. Mention any two methods of PreparedStatement in Java and their purpose.
Each method carries 1 mark
setString() and setInt(). setString() is used to bind a string value to a parameter placeholder in
the SQL statement, while setInt() is used for binding an integer value.
Part – B ( 5 x 13 = 65Marks)
11. a) i) book class – 2 marks
parameterized constructor – 3 marks
“this” keyword usage – 3 marks
class Book {
// Instance variables
private String title;
private String author;
private double price;
// Parameterized constructor
public Book(String title, String author, double price) {
this.title = title; // 'this' refers to the instance variable
this.author = author;
this.price = price;
}
// Method to display book details
public void displayDetails() {
System.out.println("Book Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: $" + price);
}
// Main method to test the class
public static void main(String[] args) {
// Creating a Book object using the parameterized constructor
Book book1 = new Book("The Alchemist", "Paulo Coelho", 399.99);
// Displaying the book details
book1.displayDetails();
}
}
ii) Discuss the differences between static and instance methods with examples.
Each difference carries 1 mark
Static method: This method belongs to the class and can be called without creating an object.
Instance method: This method belongs to an object and requires an object to be called.
Static method : Created using the static keyword and retrieved without creating an object.
Instance method : Requires an object of its class to be invoked.
Static Method : Access only static variables and methods.
Instance method : Can access both static and instance members.
Static method : Does not support runtime polymorphism
Instance method : Supports runtime polymorphism
11. b. i) Explain the concept of polymorphism in Java with code examples of method
overriding.
Polymorphism definition – 1 mark
Explanation – 2 marks
Method overriding code – 2 marks
In Java, polymorphism allows the same method or object to behave differently based on the
context. Polymorphism in Java is the task that performs a single action in different ways.
Runtime polymorphism in Java is also popularly known as Dynamic Binding or Dynamic
Method Dispatch. In this process, the call to an overridden method is resolved dynamically
at runtime rather than at compile-time.
Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
1. Method Overloading
2. Method Overriding
Method overloading is the process that can create multiple methods of the same name in the
same class, and all the methods work in different ways. Method overloading occurs when
there is more than one method of the same name in the class.
Method overriding is the process when the subclass or a child class has the same method as
declared in the parent class.
Example of Method Overriding in Java
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is moving");}
}
//Creating a child class
class Car2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("car is running safely");}
public static void main(String args[]){
Car2 obj = new Car2();//creating object
obj.run();//calling method
}
}
ii) Venicle class - 2 mark
Subclasses - 1 mark each
Method speedUp() – 1mark
Override – 3 marks
// Base class
class Vehicle {
protected int speed = 0;
public void speedUp() {
speed += 5;
System.out.println("Vehicle speeds up. Current speed: " + speed + " km/h");
}
}
// Subclass Car
class Car extends Vehicle {
@Override
public void speedUp() {
speed += 20;
System.out.println("Car speeds up rapidly. Current speed: " + speed + " km/h");
}
}
// Subclass Bicycle
class Bicycle extends Vehicle {
@Override
public void speedUp() {
speed += 2;
System.out.println("Bicycle speeds up slowly. Current speed: " + speed + " km/h");
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Vehicle();
Car myCar = new Car();
Bicycle myBicycle = new Bicycle();
myVehicle.speedUp(); // Default vehicle behavior
myCar.speedUp(); // Car-specific behavior
myBicycle.speedUp(); // Bicycle-specific behavior
}
}
12. a. marks for interface, abstract, manager class, main class, explanation – 3 marks
output – 2 marks
// Interface
interface Taxable { - 2 marks
double TAX_RATE = 0.2; // 20% tax
double calculateTax();
}
// Abstract class - 2 marks
abstract class Employee {
protected String name;
protected int id;
protected double baseSalary;
public Employee(String name, int id, double baseSalary) {
this.name = name;
this.id = id;
this.baseSalary = baseSalary;
}
// Abstract method
abstract double calculateSalary();
public void displayDetails() {
System.out.println("Employee ID: " + id);
System.out.println("Name: " + name);
}
}
// Subclass
class Manager extends Employee implements Taxable { - 2 marks
private double bonus;
public Manager(String name, int id, double baseSalary, double bonus) {
super(name, id, baseSalary);
this.bonus = bonus;
}
@Override
double calculateSalary() {
return baseSalary + bonus;
}
@Override
public double calculateTax() {
return calculateSalary() * TAX_RATE;
}
public void display() {
displayDetails();
System.out.println("Base Salary: $" + baseSalary);
System.out.println("Bonus: $" + bonus);
System.out.println("Total Salary: $" + calculateSalary());
System.out.println("Tax Deducted: $" + calculateTax());
}
}
// Main class
public class Main { - 2 marks
public static void main(String[] args) {
Manager mgr = new Manager("Alice Johnson", 101, 60000, 15000);
mgr.display();
}
}
12. b.i) What are user-defined exceptions in Java
Definition – 1 mark
Example – 1 marks
Explanation – 2 marks
User-defined exceptions in Java are those exceptions that are created by a programmer (or
user) to meet the specific requirements of the application.
• Create a custom exception class:
This class should extend Exception or a subclass of Exception. It can include custom fields or
methods to provide more information about the error.
• Throw the exception:
Use the throw keyword to throw an instance of the custom exception when the specific error
condition occurs.
• Catch the exception:
Use a try-catch block to handle the custom exception. The catch block should specify the
custom exception class to catch it.
ii) Exception class – 2 marks
throw and catch block – 2 marks
Main class – 2 marks
Other parts of code – 3 marks
// Custom Exception Class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Registration class
class Registration {
public void registerUser(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Registration failed: Age must be 18 or older.");
} else {
System.out.println("Registration successful!");
}
}
// Main method
public static void main(String[] args) {
Registration reg = new Registration();
try {
int userAge = 16; // Example age input
reg.registerUser(userAge);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
13. a. i) 2 thread creation – 2 marks each
Synchronization – 2 marks
Other parts of code (main, output) – 2 marks
Java Code
java
CopyEdit
class Printer {
private boolean letterTurn = true;
public synchronized void printLetter(char letter) throws InterruptedException {
while (!letterTurn) {
wait();
}
System.out.print(letter + " ");
letterTurn = false;
notify();
}
public synchronized void printNumber(int number) throws InterruptedException {
while (letterTurn) {
wait();
}
System.out.print(number + " ");
letterTurn = true;
notify();
}
}
class LetterThread extends Thread {
private Printer printer;
public LetterThread(Printer printer) {
this.printer = printer;
}
public void run() {
for (char ch = 'A'; ch <= 'Z'; ch++) {
try {
printer.printLetter(ch);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class NumberThread extends Thread {
private Printer printer;
public NumberThread(Printer printer) {
this.printer = printer;
}
public void run() {
for (int i = 1; i <= 26; i++) {
try {
printer.printNumber(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class AlternatePrint {
public static void main(String[] args) {
Printer printer = new Printer();
Thread letterThread = new LetterThread(printer);
Thread numberThread = new NumberThread(printer);
letterThread.start();
numberThread.start();
}
}
ii) Thread and thread priorities definition – 2 marks
Thread state definition and types – 3 marks
Thread priorities dictate the order in which threads are executed by the operating system,
with higher priority threads generally being favored. Thread states, on the other hand,
describe the current status of a thread in its lifecycle, transitioning through various phases
like New, Runnable, Running, Blocked, and Terminated.
Thread Priorities:
• Definition:
Thread priority is a numerical value (e.g., 1 to 10 in Java) that influences the order of thread
execution.
• Purpose:
It helps the scheduler prioritize threads, ensuring that more critical or important tasks are
processed first.
• How it works:
Higher priority threads are more likely to be chosen by the scheduler to run, but it's not a
guaranteed deterministic order.
• Example:
In Java, Thread.MIN_PRIORITY is the lowest, Thread.NORM_PRIORITY is the default,
and Thread.MAX_PRIORITY is the highest.
Thread States:
• Definition: Thread states represent the different phases of a thread's lifecycle.
• Common states:
o New: A thread that has just been created but not yet started.
o Runnable: A thread that is ready to run but is waiting for its turn to be assigned a CPU.
o Running: A thread that is currently executing on the CPU.
o Blocked: A thread that is waiting for a resource or condition to become available (e.g.,
waiting for an I/O operation to complete).
o Waiting: A thread that is waiting indefinitely for another thread to perform a specific
action or for a condition to become true.
o Timed Waiting: A thread that is waiting for a specified amount of time.
o Terminated: A thread that has completed its execution.
• Transitions: Threads can transition between these states based on events like starting a
thread, yielding control, or waiting for a resource.
13. b. i) Any five classes from the java.io package
Each class carries 1 mark
Example – 3 marks
• BufferedInputStream −The BufferedInputStream class adds functionality to another input
stream, the ability to buffer the input and to support the mark and reset methods.
• BufferedOutputStream −The BufferedOutputStream class implements a buffered output
stream. By setting up such an output stream, an application can write bytes to the
underlying output stream without necessarily causing a call to the underlying system for
each byte written.
• BufferedReader −The BufferedReader class reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters, arrays, and
lines.
• BufferedWriter −The BufferedWriter class writes text to a character-output stream,
buffering characters so as to provide for the efficient writing of single characters, arrays,
and strings.
• ByteArrayInputStream −The ByteArrayInputStream class contains an internal buffer that
contains bytes that may be read from the stream. An internal counter keeps track of the
next byte to be supplied by the read method.
• ByteArrayOutputStream −The ByteArrayOutputStream class implements an output stream
in which the data is written into a byte array. The buffer automatically grows as data is
written to it.
FileOutputStream −The FileOutputStream class is an output stream for writing data to a File
or to a FileDescriptor.
FilePermission −The FilePermission class represents access to a file or directory.It consists of
a pathname and a set of actions valid for that pathname.
FileReader −The FileReader class is a convenience class for reading character files.
FileWriter −The FileWriter class is a convenience class for writing character files.
FilterInputStream −The FilterInputStream class contains some other input stream, which it
uses as its basic source of data, possibly transforming the data along the way or providing
additional functionality.
FilterOutputStream −The FilterOutputStream class is the superclass of all classes that filter
output streams.
FilterReader −The FilterReader class is for reading filtered character streams.
ii) Each step carries equal mark – 1 mark
Create a FileWriter object: Instantiate the FileWriter class, passing the file path as an
argument to the constructor. Handle potential IOException using a try-catch block.
Write data to the file: Use the write() method to write strings or characters to the file.
Close the FileWriter: The try-with-resources statement automatically closes the FileWriter. If
not using it, ensure to close it in a finally block to release resources.
Handle exceptions: Implement appropriate error handling to manage potential IOExceptions
that might occur during file operations.
14. a. i) Each part carries 3 marks
import java.util.*;
public class ParagraphProcessor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read paragraph input
System.out.println("Enter a paragraph:");
String paragraph = scanner.nextLine();
// Count words
String[] words = paragraph.split("\\s+");
System.out.println("Total number of words: " + words.length);
// Count word frequencies
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
word = word.toLowerCase().replaceAll("[^a-z]", ""); // Normalize word
if (!word.isEmpty()) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}
// Find most frequent word
String mostFrequent = null;
int maxCount = 0;
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
if (entry.getValue() > maxCount) {
mostFrequent = entry.getKey();
maxCount = entry.getValue();
}
}
System.out.println("Most frequent word: " + mostFrequent + " (appears " + maxCount +
" times)");
// Replace all vowels with '*'
String replacedParagraph = paragraph.replaceAll("(?i)[aeiou]", "*");
System.out.println("Paragraph after replacing vowels:");
System.out.println(replacedParagraph);
}
}
ii) Correct answer – 2 marks
Explanation – 2 marks
In Java, String is a derived type, also known as a non-primitive type. It is not one of the
eight primitive data types (boolean, byte, char, short, int, long, float, and
double). Instead, String is a class, and instances of classes are objects. Because String is a
class, it has methods associated with it that can be used to perform operations on strings,
such as substring(), indexOf(), equals(), and toUpperCase(). Primitive types do not have
methods.
14. b. i) Each carries 1 mark
clear(), clone(), compute(), computeIfAbsent(), entrySet() - any method
ii) HashMap creation – 2 marks
for each operation – 2 marks
import java.util.HashMap;
import java.util.Scanner;
public class StudentHashMap {
public static void main(String[] args) {
HashMap<Integer, String> studentMap = new HashMap<>();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Student Record Operations ---");
System.out.println("1. Insert Student");
System.out.println("2. Search Student by Roll Number");
System.out.println("3. Delete Student by Roll Number");
System.out.println("4. Display All Students");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
choice = scanner.nextInt();
switch (choice) {
case 1: // Insert
System.out.print("Enter Roll Number: ");
int roll = scanner.nextInt();
scanner.nextLine(); // consume newline
System.out.print("Enter Name: ");
String name = scanner.nextLine();
studentMap.put(roll, name);
System.out.println("Student inserted successfully.");
break;
case 2: // Search
System.out.print("Enter Roll Number to Search: ");
int searchRoll = scanner.nextInt();
if (studentMap.containsKey(searchRoll)) {
System.out.println("Student Found: " + studentMap.get(searchRoll));
} else {
System.out.println("Student with Roll Number " + searchRoll + " not found.");
}
break;
case 3: // Delete
System.out.print("Enter Roll Number to Delete: ");
int deleteRoll = scanner.nextInt();
if (studentMap.remove(deleteRoll) != null) {
System.out.println("Student deleted successfully.");
} else {
System.out.println("Roll Number not found.");
}
break;
case 4: // Display All
System.out.println("\nAll Student Records:");
for (Integer key : studentMap.keySet()) {
System.out.println("Roll No: " + key + ", Name: " + studentMap.get(key));
}
break;
case 5: // Exit
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a number between 1 and 5.");
}
} while (choice != 5);
scanner.close();
}
}
15. a. i) PreparedStatement - 2 mark
Insert and Update – 2 marks each
Example – 1 mark
PreparedStatement is a subclass of Statement in Java used for executing parameterized SQL
queries. It helps in:
• Preventing SQL injection attacks.
• Improving performance by precompiling the SQL query.
• Handling dynamic input data safely and efficiently.
Steps to Use PreparedStatement for INSERT/UPDATE:
1. Load the JDBC driver
2. Establish connection to MySQL
3. Create SQL query with placeholders (?)
4. Create a PreparedStatement object
5. Set values using setXXX() methods
6. Execute the query using executeUpdate()
import java.sql.*;
public class StudentDB {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "your_password";
try {
Connection conn = DriverManager.getConnection(url, user, password);
// INSERT student details
String insertQuery = "INSERT INTO students (id, name, age) VALUES (?, ?, ?)";
PreparedStatement pstmtInsert = conn.prepareStatement(insertQuery);
pstmtInsert.setInt(1, 101);
pstmtInsert.setString(2, "John Doe");
pstmtInsert.setInt(3, 20);
pstmtInsert.executeUpdate();
System.out.println("Student inserted successfully.");
// UPDATE student age
String updateQuery = "UPDATE students SET age = ? WHERE id = ?";
PreparedStatement pstmtUpdate = conn.prepareStatement(updateQuery); ///needed
pstmtUpdate.setInt(1, 21);
pstmtUpdate.setInt(2, 101);
pstmtUpdate.executeUpdate();
System.out.println("Student updated successfully.");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ii) Connection pooling definition – 2 marks
creation steps – 4 marks
Connection pooling means a pool of Connection Objects. Connection pooling is based on
an object pool design pattern. Object pooling design pattern is used when the cost (time &
resources like CPU, Network, and IO) of creating new objects is higher. As per the Object
pooling design pattern, the application creates an object in advance and place them in Pool
or Container. Whenever our application requires such objects, it acquires them from the
pool rather than creating a new one.
15. b. Each carries its given marks in QP
1. students
sql
CopyEdit
CREATE TABLE students (
student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100) UNIQUE
);
2. questions
sql
CopyEdit
CREATE TABLE questions (
question_id INT PRIMARY KEY AUTO_INCREMENT,
question_text TEXT,
option_a VARCHAR(100),
option_b VARCHAR(100),
option_c VARCHAR(100),
option_d VARCHAR(100),
correct_option CHAR(1) CHECK (correct_option IN ('A','B','C','D'))
);
3. results
sql
CopyEdit
CREATE TABLE results (
result_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
total_questions INT,
correct_answers INT,
score DECIMAL(5,2),
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
b) SQL Queries (4)
1. Insert a new question:
sql
CopyEdit
INSERT INTO questions (question_text, option_a, option_b, option_c, option_d,
correct_option)
VALUES (?, ?, ?, ?, ?, ?);
2. Fetch all questions for the exam:
sql
CopyEdit
SELECT * FROM questions;
3. Insert student result:
sql
CopyEdit
INSERT INTO results (student_id, total_questions, correct_answers, score)
VALUES (?, ?, ?, ?);
4. Retrieve result for a student:
sql
CopyEdit
SELECT * FROM results WHERE student_id = ?;
c) Functionalities (6)
1. Add Questions
• Admin uses GUI or console to input question, options, and correct answer.
• JDBC executes the insert SQL to store into questions table.
2. Student Login/Registration
• Student provides name/email.
• System checks/creates student record using the students table.
3. Display Questions
• System fetches questions using SELECT * FROM questions.
• Presents them one by one to the student.
4. Evaluate Answers
• Student selects options.
• System compares each answer with correct_option field.
• Count of correct answers is stored.
5. Store Results
• After evaluation, results table is updated using the INSERT query.
6. View Results
• Student’s score is fetched from results and displayed with total and correct answers.
Sample JDBC Snippet (Insert Question)
java
CopyEdit
Connection conn = DriverManager.getConnection(url, user, pass);
String sql = "INSERT INTO questions (question_text, option_a, option_b, option_c,
option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "What is Java?");
ps.setString(2, "A language");
ps.setString(3, "A platform");
ps.setString(4, "Both");
ps.setString(5, "None");
ps.setString(6, "C");
ps.executeUpdate();
Part – C ( 1 x 15 = 15 Marks)
16. a. Generic interface definition – 2 mark
Reusable code – 3 marks
Procedure for implementation – 4 marks
Type parameter – 3 marks
Example with explanation – 3 marks
Generic interfaces in Java allow the creation of interfaces that can operate with various
data types while maintaining type safety. They allow specifying type parameters, which
are placeholders for actual types that will be determined later when the interface is
implemented.
Generics allows us to create reusable code components that can work with a variety of
types. By writing generic classes and methods, we avoid duplicating code for similar
functionalities and promote code reuse across different projects.
Implementation
A generic class is a class that can operate on objects of different types using a type
parameter. Like C++, we use <> to specify parameter types in generic class creation. To
create objects of a generic class, we use the following syntax:
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
16. b a) Definition – 2 marks
Working process – 2 marks
Example program – 3 marks
In Java, a functional interface is an interface that contains exactly one abstract
method. These interfaces are used to support lambda expressions and method references,
which were introduced in Java 8 to facilitate functional programming paradigms. While a
functional interface must have only one abstract method, it can contain default and static
methods, as these have implementations and do not need to be implemented by classes that
use the interface.
The @FunctionalInterface annotation can be used to explicitly declare an interface as a
functional interface. While this annotation is not mandatory, it is good practice to use it
because it enables the compiler to catch errors if the interface does not conform to the rules
of a functional interface.
Several built-in functional interfaces are available in the java.util.function package,
including:
• Function<T, R>: Represents a function that accepts one argument of type T and produces a
result of type R.
• Consumer<T>: Represents an operation that accepts a single input argument of type T and
returns no result.
• Supplier<T>: Represents a supplier of results.
• Predicate<T>: Represents a predicate (boolean-valued function) of one argument.
• BinaryOperator<T>: Represents an operation that takes two operands of the same type and
returns a result of the same type.
Java
@FunctionalInterface
interface MyFunctionalInterface {
int myMethod(int a, int b);
}
Java
MyFunctionalInterface addition = (a, b) -> a + b;
int result = addition.myMethod(5, 3); // result is 8
16. b. Correct program – 8 marks
b) import java.util.Arrays;
import java.util.List;
public class EvenNumberFilter {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35, 40);
System.out.println("Even numbers in the list:");
numbers.stream()
.filter(n -> n % 2 == 0) // Lambda expression to filter even numbers
.forEach(System.out::println); // Print each even number
}
}