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

ST3 Last Year

The document outlines a B. Tech Even Semester Sessional Test-3 for the course OOPS with Java at ABES Engineering College, covering various topics such as ArrayList vs Vector, Iterator interface, Comparable vs Comparator, Collection Framework hierarchy, Stack class, Map interface with HashMap, Life Cycle Callbacks in Spring, and REST API. Each section includes questions and example code snippets to illustrate the concepts. The test aims to assess students' understanding of Java programming and related frameworks.

Uploaded by

amitabh29chaubey
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 views18 pages

ST3 Last Year

The document outlines a B. Tech Even Semester Sessional Test-3 for the course OOPS with Java at ABES Engineering College, covering various topics such as ArrayList vs Vector, Iterator interface, Comparable vs Comparator, Collection Framework hierarchy, Stack class, Map interface with HashMap, Life Cycle Callbacks in Spring, and REST API. Each section includes questions and example code snippets to illustrate the concepts. The test aims to assess students' understanding of Java programming and related frameworks.

Uploaded by

amitabh29chaubey
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/ 18

ABES Engineering College, Ghaziabad

B. Tech Even Semester Sessional Test-3

Printed Pages:
Session: 2023-24
Semester:
Course Code:BCS 403 Roll No.:
Course Name: OOPS with Java Time: 1 Hr 30 Mins
Maximum Marks: 40
Instructions:
1. Attempt all sections.
2. If require any missing data, then choose suitably.

Q. No. Question
1 Attempt ANY ONE part from the following
What is the difference between ArrayList and Vector?

ArrayList Vector

1) ArrayList is not Vector is synchronized.


synchronized.

2) ArrayList increments Vector increments 100% means doubles


50% of current array size if the the array size if the total number of elements
number of elements exceeds exceeds than its capacity.
from its capacity.

a) 3) ArrayList is not a Vector is a legacy class.


legacy class. It is introduced in
JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized, i.e.,


non-synchronized. in a multithreading environment, it holds the
other threads in runnable or non-runnable
state until current thread releases the lock of
the object.

5) ArrayList uses A Vector can use the Iterator interface


the Iterator interface to or Enumeration interface to traverse the
traverse the elements. elements.
Explain Iterator interface with a suitable example.
Solution: Java Iterator Interface of java collections allows us to access elements of the collection
and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve
the elements of a collection and perform operations on each element. Iterator is a universal iterator
as it can be applied to any Collection object. We can traverse only in the forward direction using
iterator. Using ListIterator which extends Iterator, can traverse in both directions. Both read and
remove operations can be performed by the iterator interface. This is included in Java JDK 1.2. The
only Enumeration is the first iterator to be included in JDK 1.0. To use an iterator, we must
import java.util package.
Example:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorExample {


public static void main(String[] args) {
// Create a list of strings
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
b)
fruits.add("Date");

// Get an iterator for the list


Iterator<String> iterator = fruits.iterator();

// Iterate through the list using the iterator


while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);

// Remove an element conditionally


if (fruit.equals("Banana")) {
iterator.remove();
}
}

// Print the list after iteration


System.out.println("Fruits after iteration: " + fruits);
}
}

2 Attempt ANY ONE part from the following


What is the difference between Comparable and Comparator Interface?

Comparable Comparator

1) Comparable provides a single sorting The Comparator


sequence. In other words, we can sort the provides multiple sorting
collection on the basis of a single element sequences. In other words, we
such as id, name, and price. can sort the collection on the
basis of multiple elements such as
id, name, and price etc.

2) Comparable affects the original class, Comparator doesn't affect the


a) i.e., the actual class is modified. original class, i.e., the actual class
is not modified.

3) Comparable provides compareTo() Comparator provides compare()


method to sort elements. method to sort elements.

4) Comparable is present A Comparator is present in


in java.lang package. the java.util package.

5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.
Write an overview of the Collection Framework hierarchy, including the main interfaces and classes.
Hierarchy of Collection Framework

b)

1. Collection Interface: The root interface of the collection hierarchy, which represents a group of
objects. Key subinterfaces include List, Set, and Queue.

2. List Interface: Extends Collection and represents an ordered collection (sequence). Key
implementations are ArrayList, LinkedList, and Vector.

3. Set Interface: Extends Collection and represents a collection that does not allow duplicate
elements. Key implementations include HashSet, LinkedHashSet, and TreeSet.

4. Queue Interface: Extends Collection and represents a collection designed for holding elements
prior to processing. Key implementations are LinkedList, PriorityQueue, and ArrayDeque.

5. Map Interface: Represents a collection of key-value pairs and does not extend the Collection
interface. Key implementations include HashMap, LinkedHashMap, TreeMap, and Hashtable.

3 Attempt ANY ONE part from the following


Explain Stack Class with a suitable program to perform all the operations of stack.
Solution: The Stack class in Java is a part of the Java Collections Framework and extends
Vector. It represents a last-in, first-out (LIFO) stack of objects. The class provides several
methods to perform standard stack operations, including push, pop, peek, empty, and search.
Stack Operations

1. Push: Adds an item to the top of the stack.


2. Pop: Removes and returns the item from the top of the stack.
a)
3. Peek: Returns the item at the top of the stack without removing it.
4. Empty: Checks if the stack is empty.
5. Search: Returns the 1-based position of an item in the stack.

import java.util.Stack;
public class StackExample {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<>();

// Push elements onto the stack

stack.push(10);

stack.push(20);

stack.push(30);

stack.push(40);

System.out.println("Stack after pushes: " + stack);

// Pop element from the stack

int poppedElement = stack.pop();

System.out.println("Popped element: " + poppedElement);

System.out.println("Stack after pop: " + stack);

// Peek at the top element of the stack

int topElement = stack.peek();

System.out.println("Top element: " + topElement);

System.out.println("Stack after peek: " + stack);

// Check if the stack is empty

boolean isEmpty = stack.empty();

System.out.println("Is stack empty? " + isEmpty);

// Search for an element in the stack


int position = stack.search(20);

System.out.println("Position of 20: " + position);

// Try to search for an element not in the stack

int nonExistentPosition = stack.search(50);

System.out.println("Position of 50: " + nonExistentPosition);

Explain the Map interface in Java. Implement a program that uses HashMap to store and retrieve
employee information (id, name, department) efficiently. Demonstrate the use of key-value pairs.
Solution:

Solution: The Map interface in Java represents a collection of key-value pairs, where each key
maps to exactly one value. It does not allow duplicate keys, but values can be duplicated. The
Map interface provides methods to add, remove, and access elements based on keys.

Key Methods of Map Interface

 put(K key, V value): Associates the specified value with the specified key in the map.
 get(Object key): Returns the value to which the specified key is mapped, or null if the
map contains no mapping for the key.
 remove(Object key): Removes the mapping for a key from the map if it is present.
 containsKey(Object key): Returns true if the map contains a mapping for the
specified key.
 containsValue(Object value): Returns true if the map maps one or more keys to the
specified value.
b)  keySet(): Returns a Set view of the keys contained in this map.
 values(): Returns a Collection view of the values contained in this map.
 entrySet(): Returns a Set view of the mappings contained in this map.

Implementation Using HashMap


import java.util.HashMap;
import java.util.Map;

class Employee {
private int id;
private String name;
private String department;

public Employee(int id, String name, String department) {


this.id = id;
this.name = name;
this.department = department;
}
public int getId() {
return id;
}

public String getName() {


return name;
}

public String getDepartment() {


return department;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", department='" + department + '\'' +
'}';
}
}

public class HashMapExample {


public static void main(String[] args) {
// Create a HashMap to store employee information
Map<Integer, Employee> employeeMap = new HashMap<>();

// Add employees to the HashMap


employeeMap.put(101, new Employee(101, "Alice", "HR"));
employeeMap.put(102, new Employee(102, "Bob", "Finance"));
employeeMap.put(103, new Employee(103, "Charlie", "IT"));

// Retrieve and display employee information by id


System.out.println("Employee with ID 101: " + employeeMap.get(101));
System.out.println("Employee with ID 102: " + employeeMap.get(102));
System.out.println("Employee with ID 103: " + employeeMap.get(103));

// Display all employees


System.out.println("\nAll employees:");
for (Map.Entry<Integer, Employee> entry : employeeMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

// Check if a key exists in the map


int searchId = 104;
if (employeeMap.containsKey(searchId)) {
System.out.println("\nEmployee with ID " + searchId + " exists: " +
employeeMap.get(searchId));
} else {
System.out.println("\nEmployee with ID " + searchId + " does not exist.");
}

// Remove an employee by id
employeeMap.remove(102);
System.out.println("\nAfter removing employee with ID 102:");
for (Map.Entry<Integer, Employee> entry : employeeMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}

4 Attempt ANY ONE part from the following


Explain about Life Cycle Call backs with a neat diagram. advantages of using Dependency
Injection.

Life Cycle Callbacks in Spring

In Spring, the lifecycle of a bean is managed by the Spring IoC container. The lifecycle
includes several stages, such as instantiation, dependency injection, initialization, and
destruction. The diagram you provided outlines these stages, including custom initialization
and destruction methods.

detailed explanation of each stage and the lifecycle callbacks:


a)
1. Container Started: The Spring container is started, initializing the necessary
resources to manage beans.
2. Bean Instantiated: The container creates an instance of the bean using the no-
argument constructor or a specified factory method.
3. Dependencies Injected: The container performs dependency injection, setting the
bean's properties and resolving dependencies.
4. Custom Init Method: After the properties are set and dependencies are injected, the
container invokes a custom initialization method, if defined. This method can be
specified using:
o The @PostConstruct annotation.
o Implementing the InitializingBean interface and overriding the
afterPropertiesSet() method.
o Specifying an init-method in the bean configuration (XML or Java-based).
5. Custom Utility Method: Throughout the bean's lifecycle, utility methods can be
called to perform business logic.
6. Custom Destroy Method: Before the container shuts down, it invokes a custom
destruction method, if defined. This method can be specified using:
o The @PreDestroy annotation.
o Implementing the DisposableBean interface and overriding the destroy()
method.
o Specifying a destroy-method in the bean configuration (XML or Java-based).
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements InitializingBean, DisposableBean {

public MyBean() {
System.out.println("Bean Instantiated");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Custom Init Method");
}

public void customUtilityMethod() {


System.out.println("Custom Utility Method");
}

@Override
public void destroy() throws Exception {
System.out.println("Custom Destroy Method");
}

@PostConstruct
public void postConstruct() {
System.out.println("PostConstruct Method");
}

@PreDestroy
public void preDestroy() {
System.out.println("PreDestroy Method");
}
}
Explain REST API with a suitable example.
Solution:
Definition

A REST API (Representational State Transfer Application Programming Interface) is a set of


rules and conventions for building and interacting with web services. RESTful APIs follow a
stateless, client-server architecture and use HTTP requests to perform CRUD (Create, Read,
Update, Delete) operations on resources.

Key Characteristics

1. Stateless: Each request from a client to the server must contain all the information the
server needs to fulfill the request. The server does not store client context between
requests.
2. Client-Server Architecture: The client and server are separate entities. The client sends
requests and the server responds, enabling a clear separation of concerns.
3. Cacheable: Responses from the server can be marked as cacheable to improve
performance.
4. Uniform Interface: Resources are identified using URIs (Uniform Resource Identifiers), and
standard HTTP methods (GET, POST, PUT, DELETE) are used for operations.
b) 5. Layered System: The architecture can have multiple layers, improving scalability and
security.

Advantages of REST API

1. Scalability: REST APIs are stateless, allowing servers to handle more requests efficiently.
2. Flexibility: REST APIs can be consumed by any client that understands HTTP, including
browsers, mobile devices, and other servers.
3. Maintainability: The separation of client and server concerns simplifies code maintenance
and updates.
4. Performance: Caching of responses can reduce server load and improve performance.
5. Interoperability: REST APIs can be used across different platforms and programming
languages, facilitating integration.
5 Attempt ANY ONE part from the following
Explain Spring Boot Architecture with a suitable diagram.
The Spring Boot is built on top of the core Spring framework. It is a simplified and automated
version of the spring framework. The spring boot follows a layered architecture in which each
layer communicates to other layers(Above or below in hierarchical order).
Spring Boot Layers
The spring boot consists of the following four layers:
1. Presentation Layer – Authentication & Json Translation
2. Business Layer – Business Logic, Validation & Authorization
3. Persistence Layer – Storage Logic
4. Database Layer – Actual Database

a)

Explanation:
 The Client makes an HTTP request(GET, PUT, POST, etc.)
 The HTTP request is forwarded to the Controller. The controller maps the request.
It processes the handles and calls the server logic.
 The business logic is performed in the Service layer. The spring boot performs all the
logic over the data of the database which is mapped to the spring boot model class
through Java Persistence Library(JPA).
 The JSP page is returned as Response from the controller.
Describe the Spring IoC container. What are its main responsibilities?
The Spring framework can be considered as a collection of sub-frameworks, also referred to as layers,
such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. You can use any of
these modules separately while constructing a Web application. The modules may also be grouped
together to provide better functionalities in a web application.
Spring provides two types of Containers namely as follows:
1. BeanFactory Container
2. ApplicationContext Container
Here are its main responsibilities:
1. Bean Definition and Configuration

 Loading Bean Definitions: The container reads configuration metadata from various sources
(XML, Java annotations, or Java code) to understand how to create and configure beans.
 Bean Scope Management: It supports different scopes for beans, such as singleton (one
instance per container) and prototype (new instance every time).

2. Dependency Injection (DI)

 Constructor Injection: Dependencies are provided via constructor parameters.


 Setter Injection: Dependencies are provided via setter methods.
 Field Injection: Dependencies are provided directly into fields (less recommended due to
limited testability and maintainability).

3. Bean Lifecycle Management

 Initialization and Destruction: It calls lifecycle methods (such as @PostConstruct and


@PreDestroy or custom init/destroy methods) to perform any necessary setup or cleanup
tasks.
b)  Autowiring and Dependency Resolution: The container resolves and injects dependencies
automatically based on annotations (@Autowired, @Inject) or configuration.

4. Configuration Management

 Property Sources: It manages externalized configuration properties using property sources.


 Profiles: It allows different beans or configurations to be activated based on environment
profiles (e.g., development, production).

5. Event Handling

 Application Events: The container supports publishing and listening to application events,
allowing beans to communicate without being tightly coupled.

6. AOP (Aspect-Oriented Programming) Integration

 Aspect Management: It supports AOP, allowing the declaration of aspects (cross-cutting


concerns like logging, security) which can be applied to beans.

7. Resource Management

 Resource Loading: It provides mechanisms to access resources like files, classpath


resources, URLs, etc.

8. Conversion and Formatting

 Type Conversion: It handles type conversion and formatting, ensuring that configuration
properties and dependencies are correctly converted to the required types.
6 Attempt ANY ONE part from the following
Write a code for simple Spring application using annotations, xml or java to configure beans and
demonstrate dependency injection.
Code: Pojo Class
package in.abes.CSEDS;

public class Student {


private String Name;
private int rollno;
private String email;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
a) this.email = email;
}
public void display()
{
System.out.println("Name :" +Name);
System.out.println("Rollno :" +rollno);
System.out.println("Email :" +email);
}
}

XML Configuration:<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->


<bean class= "in.abes.CSEDS.Student" id="stdId">
<property name ="Name" value="Yash" />
<property name= "rollno" value="101" />
<property name="email" value="[email protected]" />
</bean>
</beans>
Main file:
package in.abes.main;

import org.springframework.context.ApplicationContext;

import in.abes.CSEDS.Student;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

String config_loc= "/in/abes/resources/applicationContext.xml";

ApplicationContext context =new ClassPathXmlApplicationContext(config_loc);

Student s=(Student)context.getBean("stdId");

s.display();

}}

Explain the concept of Dependency Injection and IOC in Spring. How does it promote loose
coupling in applications? Provide an example using constructor injection.
Solution: Inversion of Control (IoC)

IoC is a design principle in software engineering where the control of object creation and
management is inverted from the application's code to a framework or container. In
traditional programming, the application code is responsible for creating and managing the
lifecycle of its dependencies. With IoC, the control is shifted to a framework or container
(like the Spring container).

Dependency Injection (DI)

Dependency Injection is a design pattern used to implement IoC. It involves providing an


b) object (a dependency) to another object (a client) rather than the client creating the
dependency itself. DI allows for the injection of dependencies into a class rather than having
the class create its own dependencies. This results in a decoupling of components, making
the system more modular and easier to maintain.

How DI and IoC Promote Loose Coupling

1. Decoupling Components: By injecting dependencies rather than hard-coding them,


components are less dependent on specific implementations and more dependent on
abstractions (like interfaces). This decoupling makes it easier to swap out
implementations and reduces the impact of changes in one part of the system on
others.
2. Easier Testing: Since dependencies are injected, you can easily replace them with
mocks or stubs for testing purposes. This makes unit testing more straightforward and
less dependent on complex setup code.
3. Enhanced Flexibility: Changes to dependency implementations or configurations
can be made in a single place (the configuration) rather than across

Example Using Constructor Injection in Spring

1. Define the Service Interface and Implementation

public interface GreetingService {

String greet();

public class GreetingServiceImpl implements GreetingService {

@Override

public String greet() {

return "Hello, World!";

2. Define the Client Class:

public class GreetingController {

private final GreetingService greetingService;

// Constructor Injection

@Autowired

public GreetingController(GreetingService greetingService) {

this.greetingService = greetingService;

public void printGreeting() {

System.out.println(greetingService.greet());
3. Configure Spring (Java Configuration)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

@Bean
public GreetingService greetingService() {
return new GreetingServiceImpl();
}

@Bean
public GreetingController greetingController(GreetingService greetingService) {
return new GreetingController(greetingService);
}
}
4. Main Application:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApplication {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
GreetingController controller = context.getBean(GreetingController.class);
controller.printGreeting();
}
}

 GreetingService Interface and Implementation: Define a service and its


implementation.
 GreetingController: Depends on GreetingService. It is injected via the constructor.
 AppConfig: Spring configuration class that defines beans and their relationships. It tells
Spring how to create and wire the beans.
 MainApplication: Starts the Spring application context and retrieves the
GreetingController bean
Either of Q 1, 2, 4 & 5 one should be Previous Year GATE Question if applicable.
CO Course Outcomes mapped with respective question
KL Bloom's knowledge Level (K1, K2, K3, K4, K5, K6)
K1-Remember, K2-Understand, K3-Apply, K4-Analyze, K5- Evaluate, K6-Create

You might also like