0% found this document useful (0 votes)
4 views15 pages

PUE AnswerKey

The document outlines the makeup examination solution for Object Oriented Programming with Java for B.Tech II Year IV Semester. It includes various sections covering topics such as Java Runtime Environment, keywords, streams, thread lifecycle, exception handling, and data structures. Additionally, it provides programming examples and explanations related to Java concepts and Spring framework features.
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)
4 views15 pages

PUE AnswerKey

The document outlines the makeup examination solution for Object Oriented Programming with Java for B.Tech II Year IV Semester. It includes various sections covering topics such as Java Runtime Environment, keywords, streams, thread lifecycle, exception handling, and data structures. Additionally, it provides programming examples and explanations related to Java concepts and Spring framework features.
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/ 15

PUE/ Makeup Examination Solution (2024-2025)

EVEN Semester
Department:CS/CSE/CS(AI)/CS(AI&ML)/CSIT/IT Course: B.Tech

Year: II Semester: IV

Subject Name: Object Oriented Programming with Java Subject Code: BCS 403

Duration: 3Hrs Max.Marks: 70

Note: Attempt all the questions of each section

Section A (10 x 2 Marks)


1a. Purpose of JRE and Difference from JVM

The Java Runtime Environment (JRE) is a software package that provides libraries, Java Virtual
Machine (JVM), and other components to run applications written in Java. The JVM is a part of
the JRE that executes Java bytecode and provides platform independence.

Difference:

 JVM: Executes bytecode and provides a runtime environment.


 JRE: Includes JVM + class libraries + other files to run Java programs.

1b. Final vs Static Keywords

final is used to declare constants or prevent method overriding/inheritance. static is used to


share variables/methods among all instances of a class.

final int x = 10; // value cannot be changed


static int count = 0; // shared among all instances

Key Difference:

 final: Immutability.
 static: Shared class-level context.
1c. Byte Stream vs Character Stream

Byte streams handle raw binary data, using InputStream and OutputStream classes. Character
streams handle character data (Unicode), using Reader and Writer classes.

Example:

FileInputStream fis = new FileInputStream("file.dat"); // Byte stream


FileReader fr = new FileReader("file.txt"); // Character stream

1d. Thread Lifecycle in Java


A thread in Java has the following states:

 New: Thread is created.


 Runnable: Ready to run.
 Running: Actively executing.
 Blocked/Waiting: Waiting for resources or other threads.
 Terminated: Execution complete or stopped.

Transitions happen via methods like start(), sleep(), join(), or completion of run method.

1e. Use of 'yield' Keyword in Java

In Java 14 and above, yield is a keyword used within a switch expression to return a value
from a case block.

Purpose:
To return a value from a case block when using switch expressions.

Example:

int day = 2;
String result = switch (day) {
case 1 -> "Monday";
case 2 -> {
yield "Tuesday";
}
default -> "Other Day";
};
System.out.println(result); // Output: Tuesday
1f. Functional Interface
A functional interface contains exactly one abstract method and may contain default or static
methods. It's used with lambda expressions.

@FunctionalInterface
interface Greeting {
void sayHello();
}

Greeting g = () -> System.out.println("Hello");


g.sayHello();

1g. HashSet vs TreeSet

 HashSet stores elements using hashing, offers constant time performance, but no order.
 TreeSet uses a tree structure and stores elements in sorted order.

HashSet<String> hs = new HashSet<>();


TreeSet<String> ts = new TreeSet<>();

1h. Comparator vs Comparable


 Comparable is used to define natural ordering within a class by implementing
compareTo().
 Comparator defines custom ordering externally using compare() method.

Use Case:

// Comparable in class
class Student implements Comparable<Student> {
public int compareTo(Student s) { return this.age - s.age; }
}

// Comparator for custom sorting


Collections.sort(list, (s1, s2) -> s1.name.compareTo(s2.name));

1i. Two Scopes of Spring Beans

1. Singleton (Default) – Only one instance per Spring container.


2. @Scope("singleton")
3. Prototype – New instance every time it is requested.
4. @Scope("prototype")

These scopes are declared using @Scope annotation in Spring.


1j. HTTP Methods Supported by Spring Boot
Spring Boot supports all standard RESTful HTTP methods:

 GET – Retrieve data


 POST – Create new data
 PUT – Update entire resource
 PATCH – Partially update resource
 DELETE – Remove data
 OPTIONS – Metadata about available options
 HEAD – Like GET but without response body

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping

Section B (5 x 4 Marks)
Q2a. Polymorphism in Java
Polymorphism allows objects to take on many forms. It enables a single interface to
control access to a general class of actions. This allows flexibility and reusability in
code.
There are two main types:
1. Compile-time Polymorphism (Method Overloading): Methods with the same
name but different parameters within the same class. This is resolved by the
compiler.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}

2. Runtime Polymorphism (Method Overriding): A subclass provides a specific


implementation of a method that is already defined in its superclass. This is
resolved during runtime.
class Animal {
void sound() { System.out.println("Animal Sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}

Difference:
 Overloading is resolved during compilation.
 Overriding is resolved at runtime using dynamic dispatch.
Q2b. Student Grades Analysis
This program demonstrates the use of arrays and control statements to process student
scores. It calculates the highest and average score from the input.
import java.util.Scanner;

public class StudentGrades {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] scores = new int[5];
int sum = 0, max = Integer.MIN_VALUE;

for (int i = 0; i < scores.length; i++) {


System.out.print("Enter score of student " + (i+1) + ": ");
scores[i] = sc.nextInt();
sum += scores[i];
if (scores[i] > max) max = scores[i];
}

double average = sum / (double) scores.length;


System.out.println("Highest Score: " + max);
System.out.println("Average Score: " + average);
}
}

Q3a. Exception Handling in Java


Exception handling ensures that the normal flow of the program is maintained even
when unexpected events (exceptions) occur. Java uses five keywords:
 try: Block of code to monitor for errors.
 catch: Handles the exception.
 finally: Executes code after try/catch.
 throw: Used to explicitly throw an exception.
 throws: Declares exceptions a method might throw.
public class ExceptionExample {
static void checkAge(int age) throws Exception {
if(age < 18) {
throw new Exception("Age must be 18+");
}
System.out.println("Access granted");
}

public static void main(String[] args) {


try {
checkAge(16);
} catch(Exception e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Check completed");
}
}
}

Q3b. Two Threads Printing Numbers


This example demonstrates multithreading using the Thread class and the Runnable
interface. Two threads print alternate numbers from 1 to 5.
class ThreadOne extends Thread {
public void run() {
for(int i = 1; i <= 5; i+=2) {
System.out.println("Thread 1: " + i);
}
}
}

class ThreadTwo implements Runnable {


public void run() {
for(int i = 2; i <= 5; i+=2) {
System.out.println("Thread 2: " + i);
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
ThreadOne t1 = new ThreadOne();
Thread t2 = new Thread(new ThreadTwo());
t1.start();
t2.start();
}
}

Q4a. Switch Statement vs Switch Expression


A switch statement is a control flow statement that allows a variable to be tested for
equality against multiple values. Switch expressions (Java 14+) enhance this with more
concise syntax and return values.
Switch Statement:
int day = 2;
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid");
}

Switch Expression:
int day = 2;
String result = switch(day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Invalid";
};
System.out.println(result);

Q4b. File Writing and Reading


This program demonstrates file I/O in Java using character streams. It writes a string to
a file and reads it back using try-with-resources.
import java.io.*;

public class FileReadWrite {


public static void main(String[] args) {
String text = "Welcome to Java 8";

// Writing to file
try (Writer writer = new FileWriter("sample.txt")) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}

// Reading from file


try (Reader reader = new FileReader("sample.txt")) {
int ch;
while((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Q5a. HashMap to Store Product Prices

A HashMap is a collection that stores data in key-value pairs. This program stores product names
and prices, then prints them.

import java.util.*;

public class ProductMap {


public static void main(String[] args) {
HashMap<String, Double> products = new HashMap<>();

products.put("Laptop", 55000.0);
products.put("Mouse", 500.0);
products.put("Keyboard", 1500.0);

for (Map.Entry<String, Double> entry : products.entrySet()) {


System.out.println(entry.getKey() + " : Rs." + entry.getValue());
}
}
}

Q5b. HashMap vs LinkedHashMap vs TreeMap vs Hashtable


These are Java Map implementations with key differences:

 HashMap: Unordered, allows one null key.


 LinkedHashMap: Maintains insertion order.
 TreeMap: Stores keys in sorted (natural or custom) order.
 Hashtable: Thread-safe, does not allow null keys or values.

Map<String, Integer> hashMap = new HashMap<>();


Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
Map<String, Integer> hashtable = new Hashtable<>();

hashMap.put("Apple", 1);
linkedHashMap.put("Banana", 2);
treeMap.put("Cherry", 3);
hashtable.put("Date", 4);

Q6a. Dependency Injection (DI) vs Inversion of Control (IoC)

 IoC is a principle where control of objects is transferred to the framework (e.g., Spring).
 DI is a specific implementation of IoC where dependencies are injected into a class.
Example:

@Component
class Engine {
public String getType() { return "Petrol"; }
}

@Component
class Car {
@Autowired
Engine engine;
}

Here, Spring injects the Engine into Car, thus managing control (IoC).

Q6b. RestController and RequestMapping in Spring Boot

 @RestController: Combines @Controller and @ResponseBody.


 @RequestMapping: Maps HTTP requests to handler methods.

@RestController
@RequestMapping("/api")
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}

This REST controller handles GET requests to /api/hello.

Section C (5 x 6 Marks)
Q7a. BankAccount Class
This class models a simple bank account with fields for account number, holder name,
and balance. It also includes methods for depositing money and displaying account
details.
public class BankAccount {
private String accountNumber;
private String holderName;
private double balance;
static double interestRate = 3.5;
public BankAccount(String acc, String name, double bal) {
this.accountNumber = acc;
this.holderName = name;
this.balance = bal;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void displayInfo() {


System.out.println("Account: " + accountNumber);
System.out.println("Holder: " + holderName);
System.out.println("Balance: " + balance);
}
}

Q7b. Book Class and Filter by Price


This program defines a Book class and filters out books with a price greater than 300.
class Book {
String title;
String author;
double price;

Book(String title, String author, double price) {


this.title = title;
this.author = author;
this.price = price;
}

void display() {
System.out.println(title + " by " + author + " - Rs." + price);
}
}

public class BookFilter {


public static void main(String[] args) {
Book[] books = {
new Book("Java Basics", "A. Sharma", 250),
new Book("Spring Boot", "R. Verma", 400),
new Book("DSA", "S. Kumar", 500),
new Book("AI Concepts", "M. Rao", 200),
new Book("Cloud Computing", "T. Sen", 350)
};
System.out.println("Books priced above 300:");
for(Book b : books) {
if(b.price > 300) b.display();
}
}
}

Q8a. Exception Hierarchy


This example defines a custom exception hierarchy for a bank system. It includes
AccountNotFoundException and InsufficientBalanceException to model real-world
banking errors.
class AccountNotFoundException extends Exception {
public AccountNotFoundException(String msg) {
super(msg);
}
}

class InsufficientBalanceException extends Exception {


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

class Bank {
double balance = 1000;

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {
throw new InsufficientBalanceException("Insufficient funds");
}
balance -= amount;
}
}

Q8b. Train Reservation with Synchronization


This program simulates a train ticket booking system using multiple threads and
synchronization to avoid overbooking.
class Train {
int seats = 2;
synchronized void bookTicket(String name, int wantedSeats) {
if (wantedSeats <= seats) {
System.out.println(name + " booked " + wantedSeats + " seat(s)."
);
seats -= wantedSeats;
} else {
System.out.println("Sorry " + name + ", not enough seats
available.");
}
}
}

class BookingThread extends Thread {


Train train;
String name;
int seats;

BookingThread(Train t, String name, int seats) {


this.train = t;
this.name = name;
this.seats = seats;
}

public void run() {


train.bookTicket(name, seats);
}
}

public class TrainReservationSystem {


public static void main(String[] args) {
Train train = new Train();
BookingThread t1 = new BookingThread(train, "User1", 1);
BookingThread t2 = new BookingThread(train, "User2", 2);
t1.start();
t2.start();
}
}

Q9a. Record Class Example


Java 14 introduced record classes as a concise way to create immutable data-holding
classes. This example demonstrates creating and printing a list of students using
records.
import java.util.*;

record Student(String name, int rollNo, double marks) {}


public class RecordExample {
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Alice", 1, 85.5),
new Student("Bob", 2, 90.0),
new Student("Charlie", 3, 78.0)
);

students.forEach(System.out::println);
}
}

Q9b. Lambda and Stream Filter Example


This program demonstrates the use of lambda expressions and the stream filter
method.
import java.util.*;
import java.util.stream.*;

public class LambdaFilterExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 25, 30, 5, 40, 50);

System.out.println("Numbers > 25:");


numbers.stream()
.filter(n -> n > 25)
.forEach(System.out::println);
}
}

Q10a. Stack Navigation


A Stack is a Last-In-First-Out (LIFO) data structure. This example simulates browser
navigation using a stack of web pages.
import java.util.Stack;

public class BrowserNavigation {


public static void main(String[] args) {
Stack<String> history = new Stack<>();
history.push("Home");
history.push("About");
history.push("Contact");

history.pop(); // back to About


System.out.println("Current Page: " + history.peek());
}
}

Q10b. LinkedList Grocery Items


This example uses LinkedList to add, remove, and iterate grocery items using
Iterator.
import java.util.*;

public class GroceryList {


public static void main(String[] args) {
LinkedList<String> groceries = new LinkedList<>();
groceries.add("Milk");
groceries.add("Bread");
groceries.add("Eggs");
groceries.add("Butter");
groceries.add("Cheese");

groceries.remove("Eggs");
groceries.remove("Butter");

System.out.println("Remaining Items:");
Iterator<String> it = groceries.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}

Q11a. Spring Boot CRUD API


This example shows a REST API built using Spring Boot to perform CRUD operations
on a student entity using standard annotations like @RestController and
@RequestMapping.
@RestController
@RequestMapping("/students")
public class StudentController {

@Autowired
private StudentRepository repo;

@PostMapping("/")
public Student create(@RequestBody Student s) {
return repo.save(s);
}
@GetMapping("/{id}")
public Student get(@PathVariable int id) {
return repo.findById(id).orElse(null);
}

@DeleteMapping("/{id}")
public void delete(@PathVariable int id) {
repo.deleteById(id);
}
}

Q11b. Spring Boot Bookstore REST API


This Spring Boot REST controller provides endpoints to add, view, and delete books.
@RestController
@RequestMapping("/books")
public class BookController {

@Autowired
private BookRepository repo;

@PostMapping("/")
public Book addBook(@RequestBody Book b) {
return repo.save(b);
}

@GetMapping("/{id}")
public Book getBook(@PathVariable int id) {
return repo.findById(id).orElse(null);
}

@DeleteMapping("/{id}")
public void deleteBook(@PathVariable int id) {
repo.deleteById(id);
}
}

You might also like