📚 Chapters

☕ Project Based Learning in Java

Unit 3 — Enterprise Java Development & RESTful Services

🧱Chapter 3.1 — Servlet, JSP, Spring Core, Hibernate/JPA
🧱 CHAPTER 3.1 — MIND MAP
Servlet → Java class on the server. Life cycle init → service → destroy. Input: HttpServletRequest, output: HttpServletResponse
JSP → HTML with Java inside. Becomes a servlet. Scriptlet, declaration, expression, directive, include, EL
Spring Core → IoC container creates and wires beans. DI by constructor, setter or field
Spring Boot → Auto-configuration + application.properties
JPA / Hibernate → @Entity, @Table, @Id, @GeneratedValue, @OneToMany, @ManyToOne, @ManyToMany
Transactions and errors → @Transactional, @ExceptionHandler, @ControllerAdvice

1. Servlet and its life cycle

📖 Servlet: a Java class that runs on a web server (container such as Tomcat) and handles HTTP requests. The container creates it, calls it for every request and finally destroys it.
💡 Analogy: A receptionist at an office. The browser (visitor) gives a form, the servlet reads it and hands back a reply.
Load + init()→service() for every request→doGet() / doPost()→destroy()
MethodWhen it runs
init()Once, when the servlet is first loaded
service()For every request. Calls doGet() or doPost() by the HTTP method
doGet() / doPost()Your code for GET (URL data) or POST (form body)
destroy()Once, before the servlet is removed
ObjectRoleImportant methods
HttpServletRequestCarries everything the browser sentgetParameter(name), getParameterValues(name), getMethod(), getHeader(), getSession(), setAttribute()
HttpServletResponseCarries the reply to the browsersetContentType(), getWriter(), sendRedirect(), setStatus()
Function of HttpServletRequest in form input: getParameter("name") returns the value of the form field with that name (always a String, or null if missing). getParameterValues() returns all values of checkboxes or multi-selects.
<!-- welcome.html --> <form action="welcome" method="post"> Name: <input type="text" name="name"> <input type="submit" value="Submit"> </form>
import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/welcome") public class WelcomeServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); // 1) read the form field response.setContentType("text/html"); // 2) say what the reply contains PrintWriter out = response.getWriter(); // 3) get the writer of the reply out.println("<h2>Welcome, " + name + "!</h2>"); // 4) write the reply } }
// Expected output (needs Tomcat / Spring Boot, not run here) Welcome, Amit!
Security: printing raw user input can allow script injection (XSS). Escape the text before writing it to HTML in real projects. Use javax.servlet instead of jakarta.servlet on Tomcat 9 or older.

2. JSP (JavaServer Pages)

📖 JSP: a page that mixes HTML with Java code. The container converts it into a servlet on the first request. Use servlets for logic and JSP for the page that the user sees.
ElementSyntaxPurpose
Declaration<%! int x = 0; %>Declares variables or methods at class level
Scriptlet<% ... %>Java statements inside the request method
Expression<%= x %>Evaluates and prints a value
Directive<%@ page ... %>, include, taglibInstructions to the container (page settings, include a file, import tags)
Include action<jsp:include page="f.jsp"/>Includes another page at request time
Expression Language${param.user}Short way to read request, session and bean data without Java code
include directive<jsp:include> action
WhenTranslation time (merged once)Request time (every request)
ContentStatic, same for allCan be dynamic
Change in included filePage must be recompiledSeen at once
<%@ page language="java" contentType="text/html; charset=UTF-8" %> <%-- directive --%> <%@ include file="header.jsp" %> <%-- directive: static include --%> <%! int visits = 0; %> <%-- declaration (class level) --%> <% visits++; // scriptlet (java code) String user = request.getParameter("user"); %> <h3>Hello, <%= user %></h3> <%-- expression: prints a value --%> <p>Hello again, ${param.user}</p> <%-- Expression Language (EL) --%> <p>Page visits: <%= visits %></p> <jsp:include page="footer.jsp" /> <%-- action: dynamic include --%>
// Output for /page.jsp?user=Amit (header and footer text not shown) Hello, Amit Hello again, Amit Page visits: 1
Why JSP helps reusability: header, footer and menu are written once and included in every page. EL and tags remove Java code from the page.

3. Spring Core: IoC container and Bean life cycle

📖 Inversion of Control (IoC): the framework, not your code, creates objects and connects them. Normally you write new Engine(). With IoC you only declare what you need and the IoC container (ApplicationContext) gives it to you. A bean is an object managed by the container.
💡 Analogy: Instead of cooking yourself, you order from a restaurant. The kitchen (container) prepares and serves the dish.
AnnotationUse
@ComponentGeneric class to be managed as a bean
@ServiceBusiness logic layer
@RepositoryDatabase access layer (also translates DB exceptions)
@AutowiredAsk the container to inject a dependency
@ConfigurationClass that holds bean definitions
@BeanA method whose return value is registered as a bean
Bean life cycle
  1. Container creates the bean (constructor)
  2. Container injects dependencies (DI)
  3. Aware callbacks run (BeanNameAware and others)
  4. @PostConstruct / init-method runs: bean is ready
  5. Bean is used by the application
  6. On shutdown @PreDestroy / destroy-method runs
@Component public class Demo { public Demo() { System.out.println("1 constructor"); } @Autowired public void setDep(Dep d) { System.out.println("2 dependency injected"); } @PostConstruct public void init() { System.out.println("3 @PostConstruct"); } @PreDestroy public void cleanup() { System.out.println("5 @PreDestroy"); } }
// Expected output (needs Tomcat / Spring Boot, not run here) 1 constructor 2 dependency injected 3 @PostConstruct ...bean in use... 5 @PreDestroy
Default bean scope is singleton: one shared instance per container. prototype gives a new instance every time.

4. Dependency Injection (DI) types

📖 Dependency Injection: the way the container supplies the objects a class needs. It is how IoC is implemented. It reduces tight coupling and makes testing easy.
TypeHowRemark
ConstructorDependencies are constructor parametersRecommended. Dependency is mandatory, field can be final
Setter@Autowired on a setter methodFor optional dependencies that can change
Field@Autowired directly on the fieldShortest, but hard to unit test and hides dependencies
@Service public class OrderService { private final PaymentService payment; // 1) constructor injection private EmailService email; // 2) setter injection @Autowired private AuditLog audit; // 3) field injection public OrderService(PaymentService payment) { // @Autowired optional: only one constructor this.payment = payment; } @Autowired public void setEmail(EmailService email) { this.email = email; } } @Configuration public class AppConfig { @Bean // method result becomes a Spring bean public PaymentService paymentService() { return new PaymentService(); } }

5. Spring Boot: Auto-Configuration and application.properties

📖 Spring Boot: a layer over Spring that gives ready-to-run setup. Auto-configuration looks at the libraries on the classpath and configures beans for them. For example, if a database driver and Spring Data JPA are present, it sets up the DataSource and Hibernate.
@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
# src/main/resources/application.properties server.port=8081 spring.datasource.url=jdbc:mysql://localhost:3306/college spring.datasource.username=root spring.datasource.password=secret spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
Benefits: no XML, embedded Tomcat, starter dependencies, and settings changed in one file (application.properties or application.yml).

6. Spring Data JPA with Hibernate

📖 JPA and Hibernate: JPA is the standard for ORM (mapping Java objects to tables). Hibernate is the main implementation. Spring Data JPA adds repositories such as JpaRepository so common queries need no code.
AnnotationPurpose
@EntityMarks the class as a table-mapped entity
@Table(name="...")Gives the table name (and schema, constraints)
@IdPrimary key field
@GeneratedValueKey is generated by the database (IDENTITY, SEQUENCE, AUTO)
@OneToManyOne row relates to many (Department → Students)
@ManyToOneMany rows relate to one (Student → Department). Holds the foreign key
@ManyToManyMany to many using a join table (Student ↔ Course)
@Entity @Table(name = "student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @ManyToOne @JoinColumn(name = "dept_id") // foreign key column private Department department; @ManyToMany @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) private List<Course> courses = new ArrayList<>(); // getters and setters } @Entity public class Department { @Id @GeneratedValue private Long id; private String name; @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) private List<Student> students = new ArrayList<>(); }
public interface StudentRepository extends JpaRepository<Student, Long> { List<Student> findByName(String name); // query is created from the method name }

7. Spring and Hibernate together: layered architecture

📖 Layered architecture: the application is split into layers. Controller takes the HTTP request, Service holds the logic and transactions, DAO / Repository talks to the database using Hibernate. Spring connects the layers by DI.
Client→Controller (@RestController)→Service (@Service)→DAO (@Repository)→Hibernate / JPA→Database
// MODEL: Student entity (see @Entity example) // DAO layer: talks to the database through Hibernate (JPA) @Repository public class StudentDao { @PersistenceContext private EntityManager em; public void save(Student s) { em.persist(s); } public Student find(Long id) { return em.find(Student.class, id); } } // SERVICE layer: business logic and transactions @Service public class StudentService { private final StudentDao dao; public StudentService(StudentDao dao) { this.dao = dao; } // constructor injection @Transactional public void register(Student s) { dao.save(s); } public Student get(Long id) { return dao.find(id); } } // CONTROLLER layer: receives HTTP requests @RestController @RequestMapping("/students") public class StudentController { private final StudentService service; public StudentController(StudentService service) { this.service = service; } @PostMapping public String add(@RequestBody Student s) { service.register(s); return "Saved"; } @GetMapping("/{id}") public Student one(@PathVariable Long id) { return service.get(id); } }
Spring creates each bean, injects the next layer, opens the Hibernate session and manages the transaction. You write only the annotations.

8. Transaction management and error handling

📖 Transaction: a group of operations that is all or nothing (ACID). @Transactional on a method makes Spring begin, commit or roll back the transaction. By default it rolls back on RuntimeException (use rollbackFor for checked ones).
AnnotationUse
@TransactionalRuns the method in one transaction
@ExceptionHandlerMethod that handles a given exception
@ControllerAdviceOne class that handles exceptions for all controllers
Custom error responseA JSON body with status, error and message through ResponseEntity
@Entity public class Account { @Id private Long id; private String holder; private double balance; // getters and setters } public interface AccountRepository extends JpaRepository<Account, Long> { } public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException(String m) { super(m); } } @Service public class BankService { private final AccountRepository repo; public BankService(AccountRepository repo) { this.repo = repo; } @Transactional // both updates commit together, or both roll back public void transfer(Long fromId, Long toId, double amount) { Account from = repo.findById(fromId).orElseThrow(() -> new IllegalArgumentException("No account " + fromId)); Account to = repo.findById(toId).orElseThrow(() -> new IllegalArgumentException("No account " + toId)); if (from.getBalance() < amount) throw new InsufficientFundsException("Balance too low"); from.setBalance(from.getBalance() - amount); // debit to.setBalance(to.getBalance() + amount); // credit } } @RestController @RequestMapping("/bank") public class BankController { private final BankService service; public BankController(BankService service) { this.service = service; } @PostMapping("/transfer") public String transfer(@RequestBody TransferRequest r) { service.transfer(r.from(), r.to(), r.amount()); return "Transfer successful"; } } record TransferRequest(Long from, Long to, double amount) { }
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(InsufficientFundsException.class) public ResponseEntity<Map<String, Object>> handle(InsufficientFundsException ex) { Map<String, Object> body = Map.of("status", 400, "error", "Bad Request", "message", ex.getMessage()); return ResponseEntity.badRequest().body(body); } }
// Response when balance is too low (expected) HTTP 400 {"status":400,"error":"Bad Request","message":"Balance too low"}
Common mistake: @Transactional does not work when a method calls another method of the same class (the proxy is bypassed), or on private methods.
🌐Chapter 3.2 — REST APIs and Design Patterns
🌐 CHAPTER 3.2 — MIND MAP
REST → Resources with URLs, stateless. GET read, POST create, PUT update, DELETE remove
Spring Boot REST → @RestController, @RequestMapping, @PathVariable, @RequestBody. JSON by Jackson
Consuming APIs → RestTemplate (blocking) and WebClient (non-blocking)
Design patterns → Creational: Singleton, Factory. Behavioral: Observer, Strategy

1. REST architecture and HTTP methods

📖 REST (Representational State Transfer): a style for web services where everything is a resource with a URL (/students/5) and the client uses standard HTTP methods on it. Data usually travels as JSON.
  • Client–server: UI and data are separate
  • Stateless: every request carries all the information the server needs
  • Uniform interface: standard methods and URLs
  • Cacheable and layered system
MethodAction (CRUD)Idempotent?Typical status
GETReadYes200 OK
POSTCreateNo201 Created
PUTUpdate / replaceYes200 OK
DELETERemoveYes204 No Content
Errors400 bad request, 404 not found, 500 server error

2. Building RESTful APIs with Spring Boot and JSON (Jackson)

AnnotationUse
@RestController@Controller + @ResponseBody: return values are written as JSON
@RequestMappingMaps a URL (and method) to a class or method. Short forms: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
@PathVariableReads a value from the URL path (/students/{id})
@RequestParamReads a query value (?name=Amit)
@RequestBodyConverts the JSON body of the request into a Java object
@RestController @RequestMapping("/api/students") public class StudentRestController { private final StudentService service; public StudentRestController(StudentService service) { this.service = service; } @GetMapping("/{id}") // GET /api/students/5 public Student one(@PathVariable Long id) { return service.get(id); } @PostMapping // POST /api/students + JSON body @ResponseStatus(HttpStatus.CREATED) public Student create(@RequestBody Student s) { service.register(s); return s; } @PutMapping("/{id}") // PUT /api/students/5 public Student update(@PathVariable Long id, @RequestBody Student s) { return service.update(id, s); } @DeleteMapping("/{id}") // DELETE /api/students/5 public void delete(@PathVariable Long id) { service.delete(id); } }
POST /api/students { "name": "Amit", "marks": 88 } Response 201 Created { "id": 1, "name": "Amit", "marks": 88 }
Jackson is the library Spring Boot uses to convert Java object ↔ JSON automatically (serialization and deserialization). Useful annotations: @JsonProperty (rename), @JsonIgnore (hide a field).

3. Consuming REST APIs: RestTemplate and WebClient

RestTemplateWebClient
StyleBlocking (waits for reply)Non-blocking, reactive
StatusOlder, in maintenance modeModern, recommended
Dependencyspring-boot-starter-webspring-boot-starter-webflux
// RestTemplate (blocking, older) RestTemplate rt = new RestTemplate(); Student s = rt.getForObject("http://localhost:8081/api/students/1", Student.class); // WebClient (non-blocking, modern; needs spring-boot-starter-webflux) WebClient client = WebClient.create("http://localhost:8081"); Student s2 = client.get().uri("/api/students/{id}", 1) .retrieve() .bodyToMono(Student.class) .block(); // block() only to get the value in plain code

4. Design patterns: Singleton, Factory, Observer, Strategy

📖 Design pattern: a proven solution to a common design problem. It is a template, not ready code.
PatternTypeIdeaSeen in Spring
SingletonCreationalOnly one instance and one global access point (private constructor)Default bean scope
FactoryCreationalA method creates objects so the caller does not use newBeanFactory / ApplicationContext
ObserverBehavioralWhen the subject changes, all subscribed observers are notifiedApplicationEvent and listeners
StrategyBehavioralKeep many algorithms behind one interface and swap them at run timeInjecting different implementations of an interface
import java.util.*; public class DesignPatterns { // 1) Singleton: only one instance static class Config { private static Config instance; private Config() { System.out.println("Config created"); } static synchronized Config getInstance() { if (instance == null) instance = new Config(); return instance; } } // 2) Factory: creates objects without exposing new interface Shape { double area(); } static class Circle implements Shape { public double area() { return 3.14 * 2 * 2; } } static class Square implements Shape { public double area() { return 16; } } static class ShapeFactory { static Shape create(String type) { if (type.equals("circle")) return new Circle(); if (type.equals("square")) return new Square(); throw new IllegalArgumentException("Unknown shape: " + type); } } // 3) Observer: subject notifies all observers interface Observer { void update(String news); } static class Channel { private final List<Observer> list = new ArrayList<>(); void subscribe(Observer o) { list.add(o); } void publish(String news) { for (Observer o : list) o.update(news); } } // 4) Strategy: swap the algorithm at run time interface Payment { void pay(int amt); } static class Upi implements Payment { public void pay(int a) { System.out.println("Paid " + a + " by UPI"); } } static class Card implements Payment { public void pay(int a) { System.out.println("Paid " + a + " by Card"); } } public static void main(String[] args) { System.out.println("Singleton same object: " + (Config.getInstance() == Config.getInstance())); System.out.println("Factory circle area = " + ShapeFactory.create("circle").area() + ", square area = " + ShapeFactory.create("square").area()); Channel ch = new Channel(); ch.subscribe(n -> System.out.println("Amit got: " + n)); ch.subscribe(n -> System.out.println("Neha got: " + n)); ch.publish("Exam on Monday"); Payment p = new Upi(); p.pay(500); p = new Card(); p.pay(900); } }
// Output (run with Java 21) Config created Singleton same object: true Factory circle area = 12.56, square area = 16.0 Amit got: Exam on Monday Neha got: Exam on Monday Paid 500 by UPI Paid 900 by Card
Applying in a project: use a Singleton for configuration, a Factory to build the right object from a type, Observer for notifications, and Strategy for payment or discount rules.
⚡Ready for Exam?Sab padh liya? Ab Quick Revision karo — definition, example aur PYQ ek jagah!Quick Revision Karo →
⚡Quick Revision — Last Minute Exam Prep!
📌 How to use: Har topic mein pehle Definition, phir Example, phir Diagram / Table hai.

3.1 — Servlet, JSP, Spring, JPA

1. Servlet
📖 Definition: Java class on a server that handles HTTP requests. Life cycle: init, service (doGet / doPost), destroy.
💡 Example: getParameter("name") reads a form field.
init()→service()→doGet/doPost→destroy()
2. JSP
📖 Definition: HTML with Java. Converted to a servlet. Elements: declaration, scriptlet, expression, directive, include, EL.
💡 Example: <%= name %> and ${param.name}
3. IoC and DI
📖 Definition: Container creates and injects objects. DI types: constructor (best), setter, field.
💡 Example: @Autowired on a constructor.
@Component→Container→Bean→@Autowired
4. Bean life cycle
📖 Definition: Constructor, DI, @PostConstruct, in use, @PreDestroy. Default scope: singleton.
💡 Example: @Bean method inside @Configuration.
5. Spring Boot
📖 Definition: Auto-configuration from classpath + application.properties. @SpringBootApplication.
💡 Example: server.port=8081
6. JPA / Hibernate
📖 Definition: ORM maps class to table. @Entity, @Table, @Id, @GeneratedValue. Relations: @OneToMany, @ManyToOne, @ManyToMany.
💡 Example: Student → Department is @ManyToOne.
Controller→Service→DAO→Hibernate→Database
7. Transactions and errors
📖 Definition: @Transactional = all or nothing (rolls back on RuntimeException). @ExceptionHandler handles one exception, @ControllerAdvice handles for all controllers.
💡 Example: Fund transfer: debit and credit in one transaction.

3.2 — REST and Design Patterns

1. REST and HTTP methods
📖 Definition: Resources with URLs, stateless. GET read, POST create, PUT update, DELETE remove.
💡 Example: POST /api/students returns 201.
MethodCRUD
GETRead
POSTCreate
PUTUpdate
DELETEDelete
2. Spring Boot REST
📖 Definition: @RestController returns JSON. @RequestMapping maps URL. @PathVariable from path, @RequestBody from JSON body. Jackson converts object ↔ JSON.
💡 Example: @GetMapping("/{id}")
3. RestTemplate vs WebClient
📖 Definition: RestTemplate is blocking and older. WebClient is non-blocking and modern.
💡 Example: client.get().uri("/x").retrieve()
4. Design patterns
📖 Definition: Creational: Singleton (one instance), Factory (creates objects). Behavioral: Observer (notify subscribers), Strategy (swap algorithm).
💡 Example: Spring beans are singletons by default.
📄Previous Year Questions
📌 End Semester Paper, Academic Year 2025-2026. Subject: Project Based Learning in Java (23CSH-304 / 23ITH-304), BE(CSE/IT). Paper ke saare 13 sawal neeche hain (Unit 1, 2 aur 3 ke), har sawal par uska unit likha hai. Instructions: Section A aur B compulsory. Section C mein Q10 aur Q11 compulsory, Q12 ya Q13 mein se koi ek.
Section A (5 × 2 = 10 marks)
2MET 2025-26
Q1. Describe the bytecode concept and its relevance to the JVM. [CO1 | BT2 | Unit 1]▼
Answer:
📖 Bytecode: the platform-independent intermediate code (a .class file) that the compiler javac makes from Java source code. It is not machine code of one CPU. It is the instruction set of the JVM.
Hello.java→javac→Hello.class (bytecode)→JVM→Machine code
  • Write once, run anywhere: the same .class file runs on Windows, Linux or Mac because each system has its own JVM
  • Loading and security: the JVM class loader loads the class and the bytecode verifier checks it before running
  • Execution: the JVM interprets the bytecode and the JIT compiler turns frequently used parts into fast machine code
  • Compact: small files, easy to send over a network
javac Hello.java // creates Hello.class (bytecode) java Hello // JVM runs the bytecode
2MET 2025-26
Q2. Identify two I/O classes from the character stream category and describe their use. [CO4 | BT2 | Unit 2]▼
Answer:
📖 Character streams: handle text (16-bit characters). Base classes are Reader and Writer.
ClassUse
FileWriterWrites characters (text) to a file
FileReaderReads characters (text) from a file
BufferedReaderWraps a reader and adds buffering and readLine() (faster)
import java.io.*; public class CharStreamDemo { public static void main(String[] args) throws IOException { // FileWriter: writes characters (text) to a file try (FileWriter fw = new FileWriter("notes.txt")) { fw.write("Java is platform independent.\n"); fw.write("Bytecode runs on the JVM.\n"); } // BufferedReader wraps FileReader: reads text line by line try (BufferedReader br = new BufferedReader(new FileReader("notes.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println("Read: " + line); } } } }
// Output Read: Java is platform independent. Read: Bytecode runs on the JVM.
2MET 2025-26
Q3. Identify the function of HttpServletRequest in handling form input. [CO5 | BT2 | Unit 3]▼
Answer:
📖 HttpServletRequest: an object created by the container for every request. It carries the data the browser sent, including the form fields.
  • getParameter("name") gives the value of one form field (String, null if absent)
  • getParameterValues("hobby") gives all values of checkboxes or multi-select
  • getParameterNames() lists all field names
  • It also gives the method, headers and session (getMethod(), getHeader(), getSession())
String name = request.getParameter("name");
2MET 2025-26
Q4. Describe the purpose of @Entity and @Table annotations. [CO5 | BT2 | Unit 3]▼
Answer:
AnnotationPurpose
@EntityTells JPA/Hibernate that the class is mapped to a database table. Each object is a row. It needs an @Id field
@Table(name="student")Sets the table name (and schema or constraints). Without it the class name is used
@Entity @Table(name = "student") public class Student { @Id @GeneratedValue private Long id; private String name; }
2MET 2025-26
Q5. Define the concept of Inversion of Control (IoC) in Spring. [CO5 | BT2 | Unit 3]▼
Answer:
📖 Inversion of Control: the control of creating objects and connecting them is given to the Spring container instead of the programmer. The container (ApplicationContext) reads the annotations or configuration, creates the beans and injects dependencies (DI).
Class declares need (@Autowired)→IoC container→Creates and injects bean
Benefit: loose coupling, easy testing and easy change of implementation.
Section B (4 × 5 = 20 marks)
5MET 2025-26
Q6. Demonstrate a Java program that demonstrates method overloading. Explain how the compiler distinguishes between overloaded methods. [CO2 | BT3 | Unit 1]▼
Answer:
📖 Method overloading: several methods in the same class with the same name but different parameter lists. It is compile-time polymorphism.
public class OverloadDemo { static int add(int a, int b) { System.out.print("add(int,int) -> "); return a + b; } static int add(int a, int b, int c) { System.out.print("add(int,int,int) -> "); return a + b + c; } static double add(double a, double b) { System.out.print("add(double,double) -> "); return a + b; } static String add(String a, String b) { System.out.print("add(String,String) -> "); return a + b; } public static void main(String[] args) { System.out.println(add(2, 3)); // two ints System.out.println(add(2, 3, 4)); // three ints System.out.println(add(2.5, 3.5)); // two doubles System.out.println(add("Ja", "va")); // two Strings System.out.println(add(2, 3.5)); // int is widened to double } }
// Output add(int,int) -> 5 add(int,int,int) -> 9 add(double,double) -> 6.0 add(String,String) -> Java add(double,double) -> 5.5
How the compiler chooses the method
  1. It looks at the method signature: name + number, type and order of parameters
  2. It picks the exact match of the argument types
  3. If none matches, it tries widening (int → double, as in add(2, 3.5)), then boxing, then varargs
  4. The choice is fixed at compile time (static or early binding)
Not allowed: two methods that differ only in return type cannot be overloaded. The compiler reports an error because the signature is the same.
5MET 2025-26
Q7. Demonstrate multithreading by creating two threads, one to print even numbers and the other for odd numbers from 1 to 20. Explain how thread priority works in Java. [CO3 | BT3 | Unit 2]▼
Answer:
public class EvenOddThreads { static void pause() { try { Thread.sleep(50); } catch (InterruptedException e) { } } public static void main(String[] args) throws InterruptedException { Thread even = new Thread(() -> { for (int i = 2; i <= 20; i += 2) { System.out.println("Even: " + i); pause(); } }, "EvenThread"); Thread odd = new Thread(() -> { for (int i = 1; i <= 19; i += 2) { System.out.println("Odd : " + i); pause(); } }, "OddThread"); even.setPriority(Thread.MAX_PRIORITY); // 10 (hint to the scheduler) odd.setPriority(Thread.MIN_PRIORITY); // 1 even.start(); odd.start(); even.join(); // main waits for both threads odd.join(); System.out.println("Priorities: even=" + even.getPriority() + ", odd=" + odd.getPriority()); } }
// Sample run (the order of lines can change on every run) Even: 2 Odd : 1 Odd : 3 Even: 4 Odd : 5 Even: 6 Even: 8 Odd : 7 Even: 10 Odd : 9 Odd : 11 Even: 12 Even: 14 Odd : 13 Odd : 15 Even: 16 Even: 18 Odd : 17 Odd : 19 Even: 20 Priorities: even=10, odd=1
📖 Thread priority: a number from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default 5 (NORM_PRIORITY), set with setPriority(). The scheduler may give a higher priority thread more CPU time, but it is only a hint, not a guarantee. A new thread gets the priority of the thread that created it.
Here the even thread has priority 10 and the odd thread 1, yet the output still alternates, because both sleep and the OS decides the final order. join() makes main wait for both threads. Never use priority for correctness. Use synchronization for that.
5MET 2025-26
Q8. Apply the concept of HttpServletRequest and HttpServletResponse by creating a servlet that receives a student's name and displays a welcome message. [CO5 | BT3 | Unit 3]▼
Answer:
📖 Idea: HttpServletRequest brings the name from the form. HttpServletResponse sends the welcome message back.
<!-- welcome.html --> <form action="welcome" method="post"> Name: <input type="text" name="name"> <input type="submit" value="Submit"> </form>
import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/welcome") public class WelcomeServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); // 1) read the form field response.setContentType("text/html"); // 2) say what the reply contains PrintWriter out = response.getWriter(); // 3) get the writer of the reply out.println("<h2>Welcome, " + name + "!</h2>"); // 4) write the reply } }
// Expected output (needs Tomcat / Spring Boot, not run here) Welcome, Amit!
Flow: browser sends POST /welcome with name=Amit → container calls doPost() → servlet reads the name from the request → writes HTML to the response.
5MET 2025-26
Q9. Demonstrate how Spring and Hibernate work together in a layered architecture using annotations. Focus on service, DAO, and controller layers. [CO5 | BT3 | Unit 3]▼
Answer:
Controller→Service→DAO→Hibernate→Database
LayerAnnotationJob
Controller@RestControllerTakes HTTP request, calls service
Service@Service, @TransactionalBusiness logic and transaction
DAO@RepositoryHibernate (EntityManager) saves and reads entities
Model@EntityClass mapped to the table
// MODEL: Student entity (see @Entity example) // DAO layer: talks to the database through Hibernate (JPA) @Repository public class StudentDao { @PersistenceContext private EntityManager em; public void save(Student s) { em.persist(s); } public Student find(Long id) { return em.find(Student.class, id); } } // SERVICE layer: business logic and transactions @Service public class StudentService { private final StudentDao dao; public StudentService(StudentDao dao) { this.dao = dao; } // constructor injection @Transactional public void register(Student s) { dao.save(s); } public Student get(Long id) { return dao.find(id); } } // CONTROLLER layer: receives HTTP requests @RestController @RequestMapping("/students") public class StudentController { private final StudentService service; public StudentController(StudentService service) { this.service = service; } @PostMapping public String add(@RequestBody Student s) { service.register(s); return "Saved"; } @GetMapping("/{id}") public Student one(@PathVariable Long id) { return service.get(id); } }
Spring injects each layer into the next (@Autowired or constructor), and Hibernate turns the entity calls into SQL.
Section C (3 × 10 = 30 marks)
10MET 2025-26
Q10. Build a Java application that performs file-based employee management (Add, View, Delete) using serialization. [CO3 | BT6 | Unit 2]▼
Answer:
📖 Idea: the Employee class implements Serializable. The whole List<Employee> is saved in a file with ObjectOutputStream (serialization) and read back with ObjectInputStream (deserialization). Every operation loads the list, changes it and saves it again.
Menu (Add / View / Delete)→load() from employees.dat→Change the list→save() to employees.dat
import java.io.*; import java.util.*; public class EmployeeApp { static class Employee implements Serializable { private static final long serialVersionUID = 1L; int id; String name; double salary; Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public String toString() { return id + " | " + name + " | " + salary; } } static final String FILE = "employees.dat"; @SuppressWarnings("unchecked") static List<Employee> load() { // deserialization File f = new File(FILE); if (!f.exists()) return new ArrayList<>(); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(f))) { return (List<Employee>) in.readObject(); } catch (IOException | ClassNotFoundException e) { return new ArrayList<>(); } } static void save(List<Employee> list) { // serialization try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE))) { out.writeObject(list); } catch (IOException e) { System.out.println("Save failed: " + e.getMessage()); } } static void add(Employee e) { List<Employee> list = load(); list.add(e); save(list); System.out.println("Added: " + e.name); } static void view() { List<Employee> list = load(); if (list.isEmpty()) { System.out.println("No employees"); return; } for (Employee e : list) System.out.println(e); } static void delete(int id) { List<Employee> list = load(); boolean removed = list.removeIf(e -> e.id == id); save(list); System.out.println(removed ? "Deleted id " + id : "Id " + id + " not found"); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.println("1 Add 2 View 3 Delete 4 Exit"); int ch = Integer.parseInt(sc.nextLine().trim()); if (ch == 1) { System.out.println("Enter id, name, salary:"); int id = Integer.parseInt(sc.nextLine().trim()); String name = sc.nextLine().trim(); double sal = Double.parseDouble(sc.nextLine().trim()); add(new Employee(id, name, sal)); } else if (ch == 2) { view(); } else if (ch == 3) { System.out.println("Enter id to delete:"); delete(Integer.parseInt(sc.nextLine().trim())); } else { System.out.println("Bye"); break; } } } }
// Sample run (typed input: 1, 101, Amit, 45000, 1, 102, Neha, 52000, 2, 3, 102, 2, 4) 1 Add 2 View 3 Delete 4 Exit Enter id, name, salary: Added: Amit 1 Add 2 View 3 Delete 4 Exit Enter id, name, salary: Added: Neha 1 Add 2 View 3 Delete 4 Exit 101 | Amit | 45000.0 102 | Neha | 52000.0 1 Add 2 View 3 Delete 4 Exit Enter id to delete: Deleted id 102 1 Add 2 View 3 Delete 4 Exit 101 | Amit | 45000.0 1 Add 2 View 3 Delete 4 Exit Bye
Rules used
  1. Class implements java.io.Serializable and has a serialVersionUID
  2. writeObject(list) saves the list, readObject() reads it (cast needed)
  3. try-with-resources closes the streams automatically
  4. A transient field (for example a password) would not be saved
Data stays in employees.dat even after the program closes, so the next run shows the same employees.
10MET 2025-26
Q11. Develop a JSP-based Student Attendance Portal where data is saved to a database using Servlets and JDBC. [CO4 | BT5 | Unit 3]▼
Answer:
attendance.jsp (form)→AttendanceServlet (doPost)→JDBC PreparedStatement→MySQL table→Redirect to JSP
Roles (MVC): JSP = View, Servlet = Controller, JDBC code and table = Model.
CREATE TABLE attendance ( id INT AUTO_INCREMENT PRIMARY KEY, roll_no VARCHAR(20), name VARCHAR(50), att_date DATE, status VARCHAR(10) );
<!-- attendance.jsp --> <%@ page contentType="text/html; charset=UTF-8" %> <form action="saveAttendance" method="post"> Roll No: <input name="roll" required> Name: <input name="name" required> Date: <input type="date" name="date" required> <input type="radio" name="status" value="Present" checked> Present <input type="radio" name="status" value="Absent"> Absent <button type="submit">Save</button> </form> <% if (request.getParameter("saved") != null) { %> <p>Attendance saved.</p> <% } %>
import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; import java.sql.*; @WebServlet("/saveAttendance") public class AttendanceServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String roll = req.getParameter("roll"), name = req.getParameter("name"); String date = req.getParameter("date"), status = req.getParameter("status"); String sql = "INSERT INTO attendance(roll_no, name, att_date, status) VALUES (?,?,?,?)"; try (Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", "root", "secret"); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, roll); ps.setString(2, name); ps.setDate(3, java.sql.Date.valueOf(date)); // yyyy-MM-dd from the form ps.setString(4, status); ps.executeUpdate(); // row saved in the database res.sendRedirect("attendance.jsp?saved=1"); // back to the JSP } catch (SQLException e) { throw new ServletException(e); } } }
// Expected output (needs Tomcat / Spring Boot, not run here) Attendance saved.
Add the MySQL driver JAR in WEB-INF/lib. PreparedStatement prevents SQL injection. A second servlet with SELECT and a ResultSet can list the records.
Optional Question of Section C (attempt Q12 or Q13)
10MET 2025-26
Q12. Evaluate the use of JSP in dynamic web page development. Discuss various components such as scriptlets, declarations, directives, include tag, and expression language. Justify how they enhance reusability. [CO5 | BT5 | Unit 3]▼
Answer:
📖 JSP in dynamic pages: JSP lets the page show data that changes per request (user name, database rows) by mixing HTML with Java. It is converted to a servlet once and then runs fast.
ComponentUseReusability / evaluation
Declaration <%! %>Class-level variables and methodsMethod can be reused in the page. Shared variables are not thread-safe
Scriptlet <% %>Java logic in the pageQuick, but mixes logic with design. Keep it small
Expression <%= %>Print a valueReplaces many out.println calls
Directive page / include / taglibPage settings, static include, tag librariesInclude merges header and footer in every page. Taglib gives reusable tags
<jsp:include>Dynamic include at request timeOne footer or menu serves all pages and stays up to date
EL ${...}Read request, session, bean dataCleaner than scriptlets. Easy for designers
<%@ page language="java" contentType="text/html; charset=UTF-8" %> <%-- directive --%> <%@ include file="header.jsp" %> <%-- directive: static include --%> <%! int visits = 0; %> <%-- declaration (class level) --%> <% visits++; // scriptlet (java code) String user = request.getParameter("user"); %> <h3>Hello, <%= user %></h3> <%-- expression: prints a value --%> <p>Hello again, ${param.user}</p> <%-- Expression Language (EL) --%> <p>Page visits: <%= visits %></p> <jsp:include page="footer.jsp" /> <%-- action: dynamic include --%>
Justification: common parts (header, footer, menu) are written once and included everywhere, EL and tags keep Java out of the page, and a change is made in one file. Limitation: too many scriptlets make pages hard to maintain, so put logic in servlets or services (MVC).
10MET 2025-26
Q13. (OR) Create a Spring–Hibernate based banking system that allows users to transfer funds between accounts with transaction management. [CO5 | BT5 | Unit 3]▼
Answer:
POST /bank/transfer→BankController→BankService (@Transactional)→AccountRepository→Database
@Entity public class Account { @Id private Long id; private String holder; private double balance; // getters and setters } public interface AccountRepository extends JpaRepository<Account, Long> { } public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException(String m) { super(m); } } @Service public class BankService { private final AccountRepository repo; public BankService(AccountRepository repo) { this.repo = repo; } @Transactional // both updates commit together, or both roll back public void transfer(Long fromId, Long toId, double amount) { Account from = repo.findById(fromId).orElseThrow(() -> new IllegalArgumentException("No account " + fromId)); Account to = repo.findById(toId).orElseThrow(() -> new IllegalArgumentException("No account " + toId)); if (from.getBalance() < amount) throw new InsufficientFundsException("Balance too low"); from.setBalance(from.getBalance() - amount); // debit to.setBalance(to.getBalance() + amount); // credit } } @RestController @RequestMapping("/bank") public class BankController { private final BankService service; public BankController(BankService service) { this.service = service; } @PostMapping("/transfer") public String transfer(@RequestBody TransferRequest r) { service.transfer(r.from(), r.to(), r.amount()); return "Transfer successful"; } } record TransferRequest(Long from, Long to, double amount) { }
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(InsufficientFundsException.class) public ResponseEntity<Map<String, Object>> handle(InsufficientFundsException ex) { Map<String, Object> body = Map.of("status", 400, "error", "Bad Request", "message", ex.getMessage()); return ResponseEntity.badRequest().body(body); } }
// Response when balance is too low (expected) HTTP 400 {"status":400,"error":"Bad Request","message":"Balance too low"}
How the transaction works
  1. Transaction starts when transfer() is called
  2. Both accounts are loaded and the balance is checked
  3. Debit and credit are changed in memory
  4. If no exception: commit, both changes are saved together
  5. If a RuntimeException occurs: rollback, neither account changes
This keeps the data consistent (ACID): money is never taken from one account without reaching the other.