0% found this document useful (0 votes)
44 views25 pages

OOPS - Complete Previous PUT Solution - Bharat - Agg

The document contains a series of short and long answer questions related to Java programming concepts, including byte code, exception handling, object-oriented programming principles, and Spring framework features. It covers topics such as the roles of final, static, and private keywords, method overloading and overriding, as well as the concepts of dependency injection and bean scopes in Spring. Additionally, it discusses the Java Collection Framework and the differences between Comparable and Comparator interfaces.
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)
44 views25 pages

OOPS - Complete Previous PUT Solution - Bharat - Agg

The document contains a series of short and long answer questions related to Java programming concepts, including byte code, exception handling, object-oriented programming principles, and Spring framework features. It covers topics such as the roles of final, static, and private keywords, method overloading and overriding, as well as the concepts of dependency injection and bean scopes in Spring. Additionally, it discusses the Java Collection Framework and the differences between Comparable and Comparator interfaces.
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

Section-A #20 Marks (Short Answer TYpe Questions)

Attempt ALL thc qucstions. Each Qucstion is of 2 marks (10 x 2- 20 mark1)

Q. No. COs Attempt ALL the qucstions. Each Qucstion is of 2marks


A Coil Define Byte Code. (BKL: K1-K2 Level).
B Coi What is Object and class? (BKL: KI-K2Level).
Co2 What do you mean by Exception Handling? (BKL: KI-K2 Level).
D Co2 Differentiate between sleep(0 and start(). (BKL: KI-K2 Level).
E CO3 Write down any two advantages of Functional Interface. (BKL: KI-K2 Level).
F CO3 What is Inner Anonymous Class. (BKL: K1-K2 Levcl).
CO4| Write some methods name of Collection interface. (BKL: KI-K2 Level).
G
H CO4| What is Properties class? (BKL: K1-K2 Level).
COs Define Auto Wiring. (BK: KI-K2 Level).
J COs Explain Spring boot Logger. (BKL: K1-K2 Level).
Q: Define Byte Code.

Ans: Byte code is the intermediate code generated by the Java compiler after compiling a Java

program. It is a platform-independent code that runs on the Java Virtual Machine (JVM). Byte code
has a class extension.

Q: What is Object and CIlass?

Ans: A class is a blueprint or template for creating objects. It defines properties (fields) and
behaviors (methods). An object is an instance of a class. It represents a real-world entity and

occupies memory.

Q: What do you mean by Exception Harndling?


Ans: Exception handling is a mechanism in Java to handle runtime errors. It maintains the normal

flow of the application using blocks like 'try', `catch, finally', and 'throw'.

Q: Differentiate between sleep) and start().


Ans: sleep(): Used to pause the execution of a thread for a specified time.

start(): Used to begin the execution of a new thread. It invokes the run() method internally.

Q: Write down any two advantages of Functional Interface.


Ans: 1. Supports lambda expressions for cleaner code.
2. Helps in writing concise and readable code using functional programming.

Q: What is Inner Anonymous Class?

Ans: An inner anonymous class is a class without aname defined and instantiated in a single
statement. It is usually used to override methods of classes or interfaces in a concise way.

Q: Write some methods' name of Collection interface.

Ans: 1.add()

2. remove()

3. size()
4. iterator()!
5. contains()

Q: What is Properties class?


Ans: Properties isa Java class in java.util used to maintain configuration data in key-value pairs. It is
commonly used to store application settings.

Q: Define Auto Wiring.

Ans: Auto wiring is a feature in Spring Framework that allows automatic dependency injection.

Spring automatically resolves and injects the dependent beans without explicit configuration.

Q:Explain Spring Boot Logger.


Ans: Spring Boot Logger is used to log messages in a Spring Boot application. It uses logging
frameworks like Logback, Log4j, or Java Util Logging to print logs for debugging and monitoring.
Section-B #3O Marks (Long / Medium Answer Type Ouestions)
of 6 marks (5 x 6 = 30 marks)
Attempt ALL the questions. Each Question is
of final, static and private keyword in Java with Suitable example?
0.2(CO-1) : Explain the role
Example.
Overloading and Method Overriding with
OR
Constructor, Method
Explain the concept of
example. Why Exception Handling is
required?
Handling in details with
Q.3 (C0-2): Illustrate Exception
OR
and Character Streams? Explain with suitable Example.
What is the difference between Byte Streams

and static method with cxample.


Q.4 (CO-3): Explain Default method
OR
Variable Type Inference and Yield Keyword with example?
Discuss the role of Local

Q.5 (CO-4): Explain Collection Framework with Hierarchy.


OR
Interface.
Discuss the Concepts of Comparable Interface and Comparator
Q.2 (C0-1)
(a) Explain the role of final, static and private
keyword in Java with suitable example.

Answer:

In Java, keywords like final, static, and private are


modifiers that change the behavior of variables, methods, or
classes. Understanding their usage is essential in
object-oriented programming.

1. final Keyword:
o The final keyword is used to declare constants,
prevent method overriding, or stop inheritance.
o If a variable is declared as final, it cannot be
reassigned.
o If a method is declared final, it cannot be overridden
by subclasses.
o If a class is declared final, it cannot be extended.

Example:

Java Copy code

final int x = 10;


17 x = 20; /7 Compilation error: cannot assign a
value to final variable

2. static Keyword:
o The static keyword indicates that the member
belongs to the class rather than an instance of the
class.

o It can be used for variables, methods, blocks, and


nested classes.

o Static members are shared across all instances.

Example:

Java Copy code

class Counter {
static int count = 0;
Counter() {
count ++;

3. private Keyword:

o The private keyword restricts the visibility of a


member to within the same class.

o It provides encapsulation by preventing external


access to sensitive data.

Example:

Java OCopy code

class Demo {
private int data = 100;
private void show() {
System.out. println("Private method" ) :
}
(b) Explain the concept of Constructor, Method
Overloading and Method Overriding with Example.
Answer:

These are core features of Java's object-oriented nature.

1. Constructor:

o A
constructor is a special method that gets called
when an object is created.
o It has the same name as the class and no return type.

o Constructors are used to initialize object variables.


Example:

Java O Copy code

class Student {
String name;
Student (String n) {
name = n;
}

2. Method Overloading:
o This is the process of defining multiple methods with
the same name but different parameters within the
same class.

o It increases readability and flexibility in method calls.


Example:

Java
O
Copy code

class Calculator {
int add(int a, int b) {
return a + b:
}
double add(double a, double b) {
return a + b;

3. Method Overriding:
oWhen asubclass provides a specific implementation
of a methodthat is already defined in its superclass.
o It is used for runtime polymorphism.
Example:

Java
OCopy code
class Animal {
void sound() {
System.out. println ("Animal sound");
}
class Dog extends Animal {
void sound() {
System.out . println(" Dog barks" );
}
Q.3 (C0-2)
(a) Illustrate Exception Handling in detail with
example. Why is Exception Handling required?
Answer:

Exception Handling in Java is a powerful mechanism that


handles runtime errors, allowing the program to continue
running instead of crashing.

"Exceptions are unexpected conditions like division by


zero, file not found, or null pointer access.
" Java provides a structured way to handle exceptions
using:
otry: block that contains code that may cause an
exception.
o catch: block to handle the exception.
o finally: block that always executes (used for
clean-up).
o throwand throws: for manually or method-level
exception declaration.

Why it is required:

1. Prevents program termination due to runtime errors.


2. Helps in debugging by providing meaningful error
messages.

3. Allows graceful handling of unexpected inputs.


4. Improves program robustness and reliability.

Example:

Java Copy code

public class Example {


public static void main(String[l args) {
try {
int a = 10 / 0:
} catch (Arithmet icException e) {
Syst em . out .println (" Caught Exception: "
e);
} finally {
System.out . println("Finally block
executed. ") ;
(b) What is the difference between Byte Streams
Character Streams? Explain with suitable example.
Write 6 points.

Answer:

Java provides two main types of i/0 streams for reading and
writing:

Byte Stream Character Stream

Handles raw binary data (8-bit) Handles text (16-bit Unico


characters)

For image, audio, video, binary For reading and writing tex
files files

InputStream, OutputStream, Reader, Writer, FileReade


FileInputStream FileWriter

Does not handle encoding Handles character encodin


automatically
Efficient for non-text data Efficient for character/text
data

new new FileReade r("a. txt")


FileInputStream("a.jpg"):
Q.4 (C0-3)
(a) Explain Default method and Static method with
example.
Answer:

In Java 8, interfaces were enhanced with new capabilities.

1. Default Method:

o Introduced to add method implementations to


interfaces.
o Useful for backward compatibility so that old
implementations do not break.

o Must be prefixed with default.


Example:

Java Copy code

interface Printable {
default void print() {
System . out . println ("Default print method" ):

2. Static Method:

o Defined in interfaces with the static keyword.


o Cannot be overridden and should be accessed using
interface name.

Example:

Java Copy code

inter face Utility {


static void display() {
System.out .println("Static method in
inter face" );

(b) Discuss the role of Local Variable Type Inference


andyield Keyword with example.
Answer:

1. Local Variable Type Inference (var):


o Introduced in Java 10.

o Automatically infers the variable's data type from the


assigned value.
o Reduces code verbosity and improves readability.
Example:

Java
OCopy code

var message = "Hello Java"; 11 inferred as String


var number = 123; 1/ inferred as int
2. yield Keyword:
o Introduced in Java 13, used with switch expressions
to return a value.

o It replaces the need for break and supports returning


values directly.
Example:

Java OCopy code

String result = switch (5) {


case 1 -> "One" :
case 5 -> {
yield "Five" :

default -> "0ther";


}:
System.out .println(result) ;

Q.5 (CO-4)
(a) Explain Collection Framework with Hierarchy.
Answer:

Java Collection Framework provides standardized


architecture for storing and manipulating groups of data
(objects). It is part of java . util package and includes
interfaces and classes.

Key Components:

" Collection Interface - root of all collections.

" List Interface - ordered collection (ArrayList, LinkedList).


"Set Interface - unique elements (HashSet, TreeSet).
" Map Interface - key-value pairs (HashMap, TreeMap).

Hierarchy Overview:

OCopycode
Collection

List Se

ArrayList HashSet

Map

HashMap

Example:

Java Copy code

List<String> names = new ArrayList <>0;


names.add("Alice"):

Set<Integer> numbers = new HashSet<>();


numbers.add(10);
(b) Discuss the Concepts of Comparable Interface
and Comparator Interface.

Answer:

Both are used for sorting objects but serve different


purposes.

1. Comparable Interface:

oPresent in java. lang.

" Defines natural ordering.


o Requires class to implement compareTo().
Example:

Java Copy code

class Student implements Comparable<Student> {


int marks;
public int compareTo(Student s) {
return this.marks - s.marks;

2. Comparator Interface:
o Present in java. util.
o Used for custom ordering.
" Implement compare(T o1, T o2) method.
Example:

Java Copy code

class SortByName implements Comparator<student> {


public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2 .name) :

Difference Table:

Comparable Comparator

java.lang java.util

compareTo() compare()

Natural Custom

When single sorting logic is When multiple or external


needed sorting logic is needed
0.6)): Take n uitnble eyle nnt explam tle concept of
Injectio. Sping Inversion of Control and Dependency

OR
1ixnlain the conwepts of len Seopes Singleton, Iioloype, Request, Session, Applicat1on.

Seetlon -(W50 Marks (Medlum/Long Answer Type Ouetions)


Altempt ALL the questions. Pach (uestion is of 10 marks.

0.7(C0-I): Altempt any 1WO question, Bach queation is of 5marks.


a. State the basie features/chnrncteristics of Object-Oriented Programming (00P)
b. Whatdo you mean by lEncapsulation? Give suitable example.
c. Differentinte abstraction and interface with example?

Q.8 (CO-2) : Attempt any TWO question. Each question is of 5 / 10 marks.


a. Write a program in java to implcmcnt try with multiple catch.
b. llustraute concepts of tread life cycl.
c. Write a program in Java to implement Thrcading using Thread class and Runnable interface.
Each question is of 5/ 10 marks.
Q.9 (CO-3): Attempt any TWO question. interface.
a. Expluin conccpts of Functional Explain with Example.
b. What is the necd of Scaledclass?
with example?
c. Explain Type Annotations, Repeating Annotations

Attempt any TWO question. Each question is of 5/ 10 marks.


Q.10 (CO-4): example.
a. Explain List interface with interface with example.
b. Discuss the concept of Set example for HashMap class.
c. What is Map interface. Write
marks.
Attempt any TWO question. Each question is of S/ 10
Q.11 (C0-5): framework.
a. Explain the advantage of Spring
two of the followings.
b. Write short notes on any
i. Web Socket ii. Request Body System.
c. Discuss the role of Spring Boot Build
Q.6 (C0-5)
A. Spring Inversion of Control and Dependency Injection
(DI):

Inversion of Control (loC) isafundamental concept in the


Spring framework where the control of object creation,
configuration,and management is transferred from the
program itself to the Spring container. Traditionally, objects
are responsible for creating their dependencies. In Spring,
this responsibility is inverted - the container takes care of
dependency management.

Dependency Injection (DI) is the process of supplying the


dependencies (objects a class needs to function) from the
outside, rather than letting the class create them. Spring
supports three types of dependency injection:

1. Constructor Injection
2. Setter Injection
3. Field Injection (via annotations)

Example:

Java OCopy code

@Component

public class Engine {


public void start () {
System .out .println (" Engine Started'" ):

@Component
public class Car {
private Engine engine;

@Autowired
public Car(Engine engine)
this.engine = engine

public void drive() {


engine.start():
System.out.println(" Car is running"):

In this example:

" Engine is a dependency of Car.


"Using @Autowired, Spring automatically injects an
instance of Engine into the Car class.

" The programmer does not have to manage object


creation manually.

This promotes loose coupling, reusability, testability, and


separation of concerns.

B. Bean Scopes in Spring:

In Spring, bean scope refers to the lifecycle and visibility of


the bean instances managed by the Spring container. The
following are the common scopes:

1. Singleton (Default Scope):


Onlyone instance of the bean is created per Spring
container. Every request for the bean returns the same
instance.
Java
DCopy code

@Scope ("singleton")

2. Prototype:
A new bean instance is created every time the bean is
requested. Useful when you want independent beans.
Java O Copy code

@Scope("prototype")

3. Request:
One bean instance per HTTP request. This is applicable
in web applications only.

Java
DCopy code

@Scope(""request")

4. Session:
One bean instance per HTTP session. Also applicable in
web contexts.

Java
O Copy code

@Scope ("session")

5. Application:
A
single bean instance for the entire lifecycle of the
ServletContext.

Java O
Copy code

@Scope("applicat ion" )

Each scope allows better control of memory and behavior


depending on the requirement of the application.
Q.7 (C0-1)
a. Basic Features of Object-Oriented Programming (00P):

1 Encapsulation - Binding data and code into a single


unit.

2. Inheritance - Mechanism by which one class can


inherit the properties of another.
3. Polymorphism - Allows methods to behave differently
based on context (overloading &overriding).
4. Abstraction - Hiding internal details and showing only
necessary features.
5. Reusability - Using existing code for new purposes,
reducing redundancy.
6. Modularity - Dividing the program into independent
modules.
7 Class and Object - Class is a blueprint; object is the
instance.

Message Passing - Objects communicate via method


calls.

9. Dynamic Binding - Method to be executed is


determined at runtime.
10. Robustness and Security - With access modifiers and
exception handling.
These features make 00P highlysuitable for complex and
scalable applications.

b. What is Encapsulation? Example:

Encapsulation is the concept of wrappingdata (variables)


and methods that manipulate the data into asingle unit
called a class. It restricts direct access to some of the
object's components, which is a means of preventing
unintended interference and misuse.

Example:

Java O Copy code

publicclass Student {
private String name;
private int age;

17 Setter
public void setAge(int age) {
this.age = age;

11 Getter
public int getAge() {
return age;
}

Here, the age is private and accessed through public


methods. This ensures that the internal representation of the
object is hidden from outside interference.
C. Difference between Abstraction and Interface:

" Abstraction is a process of hiding implementation details


and showing only functionality.
"Interface is a contract that defines a set of methods that
implementing classes must provide.

Feature Abstraction Interface

Type Abstract class Pure abstract type

Implementation Can have partial Cannot have any

Access Modifiers Can use any Only public


Inheritance Single Multiple (in Java)

Example:

Java O Copy code

abstract class An imal {


abstract void sound():

interface Vehicle {
void start();

Q.8 (CO-2)
a. Java Program with Try and Multiple Catch:

Java Copy code

public class MultiCat ch Examp le {


public static void main (String [] args) {
try {
int a =10;
int b = a / 0; 11 Arithmetic Exception
String s = null;
System. out.println(s. length()); |
NullPointer Exception
}catch (Arithmetic Exception e){
System.out . println("Arithmetic Error
occurred."):
}.catch (NullPointer Exception e){
System.out . println("Null Pointer Error
Occurred."):

} catch (Exception e) {
System.out .print ln("General Exception
occurred. "):

This demonstrates how different exceptions are caught and


handled accordingly.
b. Thread Life Cycle in Java:

1. New - When a thread is created.

2. Runnable - After calling start(), thread is ready to run.


3. Running - Thread scheduler picks the thread for
execution.

4. Blocked - Waiting to acquire a lock.


5. Waiting - Waiting indefinitely for another thread.
6. Timed Waiting - Waiting for a specific time using
sleep), join), etc.
7. Terminated - After run) completes or exception occurs.

c. Threading using Thread Class and Runnable Interface:

UsingThread class:

Java O Copy code

class MyThread extends Thread {


public void run() {
System.out . println ("Thread using Thread
class"):
}

public static void main(String[] args) {


MyThread t = new MyThread();
t.start();

Using Runnable interface:

Java
O
Copy code

class MyRunnable implements Runnable {


public void run() {
System. out. println("Thread using Runnable
interface" );

public static void main(String [] args) {


Thread t = new Thread(new MyRunnable()):
t.start():

Using Runnable is preferred for better object-oriented design


and when extending other classes.
Q.9 (CO-3) a. Explain concepts of Functional Interface
A functional interface in Java is an interface that contains exactly one abstract method. These are used

extensively in lambda expressions and functional programming paradigms..

Example:

@Functionallnterface

interface MyFunction {

int operation (int a, int b):

Functional interfaces are part of the java.util.function package which includes interfaces like Predicate<T>,

Function<T, R>, Supplier<T>, Consumer<T>, etc.

They help improve code readability and are heavily used in streams and lambda expressions.

Q.9 (CO-3) b. What is the need of Sealed class? Explain with Example.
Sealed classes were introduced in Java 15 to restrict which other classes or interfaces may extend or

implement them. This improves control over class hierarchies...

Syntax:
public sealed class Vehicle permits Car, Bike )
public final class Car extends Vehicle (}

public final class Bike extends Vehicle ()

Need:

- To provide controlled inheritance.

- Better maintainability.

- More secure and predictable design for class hierarchies.

- Useful in pattern matching.

Q.9 (CO-3) c. Explain Type Annotations, Repeating Annotations with example?


Type Annotations:

These are annotations applied to types (introduced in Java 8). Useful in static analysis and null checks.

Example:
@NonNull String name;

Repeating Annotations:

Allows the same annotation to be applied multiple times to the same declaration.

Syntax:
@Repeatable(Hints.class)
public @interface Hint (

String value():
public @interface Hints {

Hint[] value():

Usage:

@Hint("hint1")

@Hint("hint2")
public class Demo (0

Q.10(Co-4) a. Explain List interface with example.


The List interface in Java is a part of the java.util package and extends the Collection interface. It represents

an ordered collection of elements that may contain duplicates.

Common classes: ArrayList, LinkedList, Vector.

Example:

List<String> fruits = new ArrayList<>():

fruits.add("Apple"):
fruits.add("Banana"):

System.out.printin(fruits);

Features:
- Allows duplicates
- Maintains insertion order

- IndexX-based access

Q.10 (C0-4) b. Discuss the concept of Set interface with example.


Set is a collection that contains no duplicate elements. It models the mathematical set abstraction.

Implemernted by: Hash Set, LinkedHashSet, TreeSet.

Example:
Set<String> countries = new Hash Set<> ():
countries.add("India");

countries.add("USA");

countries.add("India"); // Duplicate ignored

Features:

- No duplicates

- Unordered (except LinkedHash Set and TreeSet)

Efficient membership test

Q.10 (C0-4) c. What is Map interface? Write example for HashMap class.
Map is not part of the Collection hierarchy but it is part of java.util. It stores key-value pairs.

Common implementations: Hash Map, TreeMap, LinkedHashMap.


Example:

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


marks.put("Math", 95):

marks.put("Science", 90);

System.out.printin(marks.get("Math");

Features:

- No duplicate keys

- Each key maps to exactly one value

- Fast retrieval via key


Q.11 (CO-5)
a. Advantages of Spring Framework:

1. Dependency Injection simplifies testing and


maintenance.
2. Lightweight - Doesn't require heavy configuration or
containers.
3. Modular - Pick only what youneed.
4. Integrated Framework - Supports ORM (Hibernate,
JPA), security,etc.
5. AOP Support - Separates cross-cutting concerns.
6. Transaction Management - Declarative and
programmatic options.
7. Testing Support - Integrated testing tools and
annotations.

8 MVC Framework - For building web applications.


9. Easy Integration - With legacy and third-party APls.
10. Community Support - Extensive documentation and
tools.
Q.11 (CO-5)
b. Write short notes on any two of the following:

i. WebSocket:

WebSocket is aprotocol that provides full-duplex


communication channels over a single TCP connection. It is
especially useful for applications that require real-time
communication, such as chat applications, live sports
updates, stock tickers, multiplayer games, and loT
dashboards.
Key features of WebSocket:

" Bidirectional Communication: Both the client and the


server can send messages independently.
" Low Latency: Unlike HTTP which requires a new request
for each communication, WebSocket stays open, reducing
overhead.

"Persistent Connection: Once established, the connection


remains open until either client or server closes it.
"Reduced Bandwidth Usage: Because it avoids repeated
HTTP handshakes, it saves bandwidth.

WebSocket in Spring:

Spring provides support for WebSocket communication


using @ServerEndpoint, STOMP (Simple Text Oriented
Messaging Protocol), and @MessageMapping. Spring
WebSocket can work in conjunction with Spring Boot and
provides easy integration with front-end clients using
SockJS and STOM.

i. @RequestBody:

The @Request Body annotation is used in Spring MVC to bind


the HTTP request body to a method parameter in a
controller. This is particularly useful when developing
RESTful APls.

Use Case Example: Suppose a client sends a POST request


with JSON data. Spring can automatically deserialize the
JSON into a Java object using @RequestBody.

Java Copy code

@PostMapping("/register")
public ResponseEntity<String>
registerUser(@RequestBody User user) {
7 The user object is populated from the request
body
userService.save (user):
return ResponseEntity. ok("User registered
Successfully'");

Advantages:

" Simplifies parsing of JSON/XML input.

"Enhances REST API design and decouples frontend and


backend.
" Works seamlessly with validation annotations (like
@Valid).

C. Discuss the role of Spring Boot Build System:

Spring Boot simplifies project setup and deployment through


integration with buildsystems like Maven and Gradle. The
build system automates tasks such as compiling code,
packaging, dependency management, and running the
application.
Key roles of Spring Boot Build System:

1. Dependency Management:
o Spring Boot uses "starter dependencies" that simplify
configuration. For example,
spring-boot -starter-web includes everything
needed to build a web application.
o Version conflicts are managed using Spring Boot's
dependency management plugin.
2. Project Initialization:
o With tools like Spring Initializr, Maven or Gradle
projects are quickly bootstrapped with necessary
dependencies and configurations.
3. Packaging and Deployment:
" Spring Boot applications are usually packaged as
executable JARs.

oThese JARS can be run independently without


requiring external servlet containers like Tomcat or
Jetty.
4. Plugins:
o Maven (spring-boot -maven-plugin) and Gradle
(spring-boot -gradle- plugin) plugins support
building and running applications directly from the
command line or IDE.

5. Custom Build Profiles:

o Different configurations for environments (dev, test,


production) can be specified using
application . properties or application. yml with
build profiles.
6. Build Automation:

o Integrates with CI/CD pipelines, enabling automated


testing, packaging, and deployment.
7. Improved Developer Experience:
oOffers rapid development and testing using built-in
server (spring-boot -devtools), and fast packaging
with fewer configurations.

You might also like