Advanced Java Programming (4351603) - Summer 2025 Solution

Solution guide for Advanced Java Programming (4351603) Summer 2025 exam

Question 1(a) [3 marks]

Write a difference between AWT and Swing.

Answer:

Table: AWT vs Swing Comparison

FeatureAWTSwing
PlatformPlatform dependentPlatform independent
ComponentsHeavy weightLight weight
Look and FeelNative OS lookPluggable look and feel
PerformanceFasterSlower than AWT
  • AWT: Uses native OS components
  • Swing: Uses Java's own components
  • Pluggability: Swing supports customizable UI

Mnemonic: "Swing is Smart - Platform Independent and Pluggable"

Question 1(b) [4 marks]

List out various Layout Managers. Explain Flow Layout manager with example.

Answer:

Layout Managers List:

  • FlowLayout: Left to right arrangement
  • BorderLayout: North, South, East, West, Center
  • GridLayout: Equal sized grid cells
  • CardLayout: Stack of components
  • BoxLayout: Single row or column

FlowLayout Example:

Java

Mnemonic: "Flow Like Water - Left to Right"

Question 1(c) [7 marks]

Create a Swing program using checkbox that allows users to select multiple items from a list of options. Display the selected items.

Answer:

Java

Key Features:

  • Multiple Selection: Users can select multiple checkboxes
  • Real-time Display: Shows selected items immediately
  • ItemListener: Handles checkbox state changes

Mnemonic: "Check Multiple, Display All"

Question 1(c) OR [7 marks]

Develop a Java program using various swing components.

Answer:

Java

Components Used:

  • JTextField: Text input
  • JComboBox: Dropdown selection
  • JRadioButton: Single selection
  • JButton: Action trigger

Mnemonic: "Text, Combo, Radio, Button - Complete Form"

Question 2(a) [3 marks]

Explain Swing controls with example.

Answer:

Table: Common Swing Controls

ControlPurposeExample
JButtonClick actionsnew JButton("Click Me")
JTextFieldText inputnew JTextField(10)
JLabelDisplay textnew JLabel("Hello")
JCheckBoxMultiple selectionnew JCheckBox("Option")

Basic Example:

Java

Mnemonic: "Button, Text, Label, Check - Basic Four"

Question 2(b) [4 marks]

List JDBC drivers and explain any two.

Answer:

JDBC Drivers List:

  1. Type 1: JDBC-ODBC Bridge
  2. Type 2: Native API Driver
  3. Type 3: Network Protocol Driver
  4. Type 4: Thin Driver

Detailed Explanation:

Type 1 - JDBC-ODBC Bridge:

  • Purpose: Converts JDBC calls to ODBC calls
  • Advantage: Works with any ODBC database
  • Disadvantage: Platform dependent, slower performance

Type 4 - Thin Driver:

  • Purpose: Pure Java driver, direct database communication
  • Advantage: Platform independent, best performance
  • Disadvantage: Database specific

Mnemonic: "Bridge-Native-Network-Thin: 1-2-3-4"

Question 2(c) [7 marks]

Explain Object Relational Mapping (ORM) with its advantages and tools.

Answer:

Object Relational Mapping (ORM): ORM is a technique that maps object-oriented programming concepts to relational database structures.

Table: ORM Advantages

AdvantageDescription
ProductivityReduces coding time
MaintainabilityEasy to modify and update
Database IndependenceSwitch databases easily
Object-OrientedWorks with OOP concepts

Popular ORM Tools:

  • Hibernate: Most popular Java ORM
  • JPA: Java Persistence API standard
  • MyBatis: SQL mapping framework
  • EclipseLink: Reference implementation

Working Model:

  • ObjectsORMTables
  • Automatic SQL generation
  • Type-safe queries

Mnemonic: "Objects Relate Magically"

Question 2(a) OR [3 marks]

Describe MOUSEEVENT and MOUSELISTENER interface with example.

Answer:

MouseEvent: Generated when mouse actions occur on components.

MouseListener Interface Methods:

  • mouseClicked(): Mouse button clicked
  • mousePressed(): Mouse button pressed
  • mouseReleased(): Mouse button released
  • mouseEntered(): Mouse enters component
  • mouseExited(): Mouse exits component

Example:

Java

Mnemonic: "Click-Press-Release-Enter-Exit"

Question 2(b) OR [4 marks]

List and explain the components of the JDBC API.

Answer:

Table: JDBC API Components

ComponentPurposeKey Classes
DriverManagerManages driversDriverManager.getConnection()
ConnectionDatabase connectionConnection conn
StatementSQL executionStatement stmt
ResultSetQuery resultsResultSet rs

Component Details:

  • DriverManager: Establishes connection with database
  • Connection: Represents database session
  • Statement: Executes SQL queries
  • ResultSet: Holds query results

Basic Usage:

Java

Mnemonic: "Driver Connects, Statement Executes, ResultSet Returns"

Question 2(c) OR [7 marks]

Draw and explain the architecture of Hibernate.

Answer:

Architecture Components:

Table: Hibernate Architecture

ComponentFunction
ConfigurationReads config files
SessionFactoryCreates Session objects
SessionInterface to database
TransactionManages transactions
QueryHQL/SQL queries

Layer Description:

  • Application Layer: Java objects and business logic
  • Hibernate Layer: ORM mapping and session management
  • Database Layer: Actual data storage

Key Features:

  • Automatic table creation: Based on entity classes
  • HQL support: Object-oriented query language
  • Caching: First and second level caching

Mnemonic: "Config-Factory-Session-Transaction: CFST"

Question 3(a) [3 marks]

Describe various features of Servlet.

Answer:

Table: Servlet Features

FeatureDescription
Platform IndependentRuns on any OS with JVM
PerformanceBetter than CGI
RobustJVM managed memory
SecureJava security features

Key Features:

  • Server-side processing: Handles client requests
  • Protocol independent: HTTP, FTP, SMTP support
  • Extensible: Can be extended easily
  • Portable: Write once, run anywhere

Mnemonic: "Platform Performance Robust Secure"

Question 3(b) [4 marks]

Explain Servlet life cycle.

Answer:

Life Cycle Stages:

Table: Servlet Life Cycle

StageMethodPurpose
LoadingClass loadingJVM loads servlet class
InstantiationConstructorCreates servlet object
Initializationinit()One-time setup
Request Processingservice()Handles requests
Destructiondestroy()Cleanup resources

Method Details:

  • init(): Called once when servlet loads
  • service(): Called for each request
  • destroy(): Called when servlet unloads

Mnemonic: "Load-Create-Init-Service-Destroy"

Question 3(c) [7 marks]

Explain the session tracking in Servlet with example.

Answer:

Session Tracking Methods:

Table: Session Tracking Techniques

MethodDescriptionPros/Cons
CookiesClient-side storageEasy/Privacy issues
URL RewritingAppend session IDUniversal/Ugly URLs
Hidden FieldsForm-based trackingSimple/Form dependent
HttpSessionServer-side objectSecure/Memory usage

HttpSession Example:

Java

Session Management:

  • Creation: request.getSession()
  • Storage: session.setAttribute()
  • Retrieval: session.getAttribute()
  • Invalidation: session.invalidate()

Mnemonic: "Cookies-URLs-Hidden-HttpSession: CUHS"

Question 3(a) OR [3 marks]

Explain methods of Servlet life cycle.

Answer:

Life Cycle Methods:

Table: Servlet Life Cycle Methods

MethodCalled WhenParameters
init()Servlet initializationServletConfig config
service()Each requestServletRequest req, ServletResponse res
destroy()Servlet cleanupNone

Method Details:

  • init(ServletConfig config): Initialization code, database connections
  • service(req, res): Request handling, business logic
  • destroy(): Cleanup code, close resources

Example:

Java

Mnemonic: "Init-Service-Destroy: ISD"

Question 3(b) OR [4 marks]

Describe HTTPSERVLET class with example.

Answer:

HttpServlet Class: Abstract class extending GenericServlet, specifically for HTTP protocol.

HTTP Methods:

Table: HttpServlet Methods

MethodHTTP VerbPurpose
doGet()GETRetrieve data
doPost()POSTSubmit data
doPut()PUTUpdate data
doDelete()DELETERemove data

Example:

Java

Key Features:

  • HTTP-specific: Designed for web applications
  • Method handling: Separate methods for different HTTP verbs
  • Request/Response: HttpServletRequest and HttpServletResponse

Mnemonic: "Get-Post-Put-Delete: GPPD"

Question 3(c) OR [7 marks]

Differentiate GET and POST methods and write a java code to develop Servlet using POST method.

Answer:

Table: GET vs POST Comparison

FeatureGETPOST
Data LocationURL parametersRequest body
Data LimitLimited (~2KB)Unlimited
SecurityLess secureMore secure
CachingCacheableNot cacheable
BookmarkingPossibleNot possible

POST Method Servlet Example:

Java

HTML Form:

HTML

Key Differences:

  • GET: Data in URL, visible, limited size
  • POST: Data in body, hidden, unlimited size

Mnemonic: "GET Grabs, POST Protects"

Question 4(a) [3 marks]

List JSP Implicit Objects and explain any two.

Answer:

JSP Implicit Objects List:

  1. request (HttpServletRequest)
  2. response (HttpServletResponse)
  3. session (HttpSession)
  4. application (ServletContext)
  5. out (JspWriter)
  6. page (Object)
  7. pageContext (PageContext)
  8. config (ServletConfig)
  9. exception (Throwable)

Detailed Explanation:

request Object:

  • Type: HttpServletRequest
  • Purpose: Access request data and parameters
  • Example: String name = request.getParameter("name");

session Object:

  • Type: HttpSession
  • Purpose: Store user-specific data across requests
  • Example: session.setAttribute("user", username);

Mnemonic: "Request Response Session Application Out"

Question 4(b) [4 marks]

Explain features of JSP.

Answer:

Table: JSP Features

FeatureDescriptionBenefit
Easy DevelopmentHTML + JavaFaster coding
Platform IndependentWrite once, run anywherePortability
Component-basedReusable componentsMaintainability
SecureJava security modelSafe execution

Key Features:

  • Separation of Concerns: Design and logic separated
  • Extensible: Custom tags and libraries
  • Compiled: Translated to servlets for performance
  • Expression Language: Simplified syntax

JSP Elements:

  • Directives: <%@ %>
  • Declarations: <%! %>
  • Expressions: <%= %>
  • Scriptlets: <% %>

Mnemonic: "Easy Platform Component Secure"

Question 4(c) [7 marks]

Describe how to call JSP from servlet with example.

Answer:

Methods to Call JSP from Servlet:

Table: JSP Calling Methods

MethodInterfacePurpose
ForwardRequestDispatcherTransfer control
IncludeRequestDispatcherInclude content
RedirectHttpServletResponseNew request

Forward Example:

Servlet Code:

Java

JSP Code (display.jsp):

jsp

Steps:

  1. Process data in servlet
  2. Set attributes in request
  3. Get RequestDispatcher with JSP path
  4. Forward to JSP

Mnemonic: "Process-Set-Get-Forward: PSGF"

Question 4(a) OR [3 marks]

List and explain JSP scripting elements.

Answer:

Table: JSP Scripting Elements

ElementSyntaxPurposeExample
Directive<%@ %>Page settings<%@ page import="java.util.*" %>
Declaration<%! %>Define methods/variables<%! int count = 0; %>
Expression<%= %>Output values<%= new Date() %>
Scriptlet<% %>Java code<% for(int i=0; i<5; i++) { %>

Detailed Explanation:

Directives:

  • Page directive: Import packages, set content type
  • Include directive: Include other files
  • Taglib directive: Custom tag libraries

Declarations:

  • Define instance variables and methods
  • Become part of servlet class

Mnemonic: "Direct Declare Express Script"

Question 4(b) OR [4 marks]

Explain JSP life cycle.

Answer:

Life Cycle Phases:

Table: JSP Life Cycle

PhaseMethodPurpose
Translation-JSP to Java servlet
Compilation-Java to bytecode
InitializationjspInit()Setup resources
Request Processing_jspService()Handle requests
DestructionjspDestroy()Cleanup

Key Points:

  • Translation: JSP engine converts JSP to servlet
  • Compilation: Java compiler creates .class file
  • Execution: Servlet container executes compiled servlet

Mnemonic: "Translate-Compile-Init-Service-Destroy"

Question 4(c) OR [7 marks]

Define cookie. Explain working of cookie with example.

Answer:

Cookie Definition: A cookie is a small piece of data stored on the client's computer by the web browser while browsing a website.

Cookie Working Process:

Table: Cookie Attributes

AttributePurposeExample
NameCookie identifierusername
ValueCookie datajohn123
DomainValid domain.example.com
PathValid path/shop/
Max-AgeExpiry time3600 seconds

Cookie Example:

Creating Cookie (Servlet):

Java

Reading Cookie (Servlet):

Java

Cookie Benefits:

  • User personalization: Remember preferences
  • Session tracking: Maintain state
  • Analytics: Track user behavior

Mnemonic: "Create-Set-Add-Read: CSAR"

Question 5(a) [3 marks]

Write difference between JSP and Servlet.

Answer:

Table: JSP vs Servlet Comparison

FeatureJSPServlet
DevelopmentHTML + JavaPure Java
CompilationAutomaticManual
MaintenanceEasierMore complex
PerformanceSlower (first request)Faster
PurposePresentation layerBusiness logic

Key Differences:

  • JSP: Better for presentation, easier for web designers
  • Servlet: Better for business logic, more control
  • Coding: JSP mixes HTML and Java, Servlet is pure Java
  • Compilation: JSP auto-compiles, Servlet needs manual compilation

Mnemonic: "JSP for Presentation, Servlet for Logic"

Question 5(b) [4 marks]

Define Spring Boot and explain its advantages.

Answer:

Spring Boot Definition: Spring Boot is a framework that simplifies the development of Spring-based applications by providing auto-configuration and embedded servers.

Table: Spring Boot Advantages

AdvantageDescription
Auto ConfigurationAutomatically configures Spring applications
Embedded ServersBuilt-in Tomcat, Jetty support
Starter DependenciesPre-configured dependency sets
Production ReadyHealth checks, metrics, monitoring

Key Features:

  • Rapid Development: Minimal configuration required
  • Microservices: Perfect for microservice architecture
  • No XML: Convention over configuration
  • Cloud Ready: Easy deployment to cloud platforms

Example:

Java

Mnemonic: "Auto Embedded Starter Production"

Question 5(c) [7 marks]

Explain the architecture of Spring framework.

Answer:

Architecture Layers:

Table: Spring Framework Modules

ModuleComponentsPurpose
Core ContainerCore, Beans, ContextIoC and DI
Data AccessJDBC, ORM, JMSDatabase operations
Web MVCWeb, Servlet, MVCWeb applications
AOPAspects, WeavingCross-cutting concerns

Core Concepts:

  • IoC (Inversion of Control): Framework controls object creation
  • DI (Dependency Injection): Dependencies injected automatically
  • AOP (Aspect-Oriented Programming): Modular cross-cutting concerns
  • MVC: Model-View-Controller pattern

Spring Container:

  • BeanFactory: Basic container
  • ApplicationContext: Advanced container with additional features

Configuration Methods:

  • XML Configuration: Traditional approach
  • Annotation Configuration: Modern approach
  • Java Configuration: Type-safe configuration

Mnemonic: "Core Data Web AOP Test"

Question 5(a) OR [3 marks]

Write advantages of JSP over Servlet.

Answer:

Table: JSP Advantages over Servlet

AdvantageJSPServlet Limitation
Easy DevelopmentHTML + Java tagsComplex HTML in Java
Automatic CompilationAuto-compiledManual compilation
Designer FriendlyWeb designers can workJava knowledge required
MaintenanceEasier to modifyCode changes need recompilation

Key Advantages:

  • Separation of Design and Logic: HTML and Java separated
  • Rapid Development: Faster prototyping and development
  • Less Code: No need for out.println() statements
  • Built-in Objects: Implicit objects readily available

Example Comparison:

JSP Code:

jsp

Servlet Code:

Java

Mnemonic: "Easy Auto Designer Maintenance"

Question 5(b) OR [4 marks]

Explain the advantages of Spring Boot.

Answer:

Table: Spring Boot Advantages

AdvantageDescriptionBenefit
Auto ConfigurationAutomatic setup based on classpathReduced configuration
Embedded ServerBuilt-in Tomcat/JettyNo external deployment
Starter POMsPre-configured dependenciesSimplified dependency management
ActuatorProduction monitoringHealth checks and metrics

Detailed Advantages:

1. Auto Configuration:

  • Automatically configures Spring application based on dependencies
  • Reduces boilerplate configuration code
  • Convention over configuration approach

2. Embedded Servers:

  • No need for external application servers
  • Easy to run applications with java -jar
  • Simplified deployment process

3. Starter Dependencies:

  • Pre-configured dependency sets
  • Version compatibility managed
  • Quick project setup

4. Production Features:

  • Health endpoints
  • Metrics collection
  • Application monitoring

Example:

Java

Mnemonic: "Auto Embedded Starter Production"

Question 5(c) OR [7 marks]

Explain MVC architecture.

Answer:

MVC (Model-View-Controller) Architecture:

MVC Components:

Table: MVC Components

ComponentResponsibilityExample
ModelData and business logicEntity classes, DAOs
ViewUser interfaceJSP, HTML, Templates
ControllerRequest handlingServlets, Spring Controllers

Detailed Explanation:

Model:

  • Represents data and business logic
  • Database operations
  • Data validation
  • Business rules implementation

View:

  • Presentation layer
  • User interface components
  • Display data to users
  • Collect user input

Controller:

  • Handles user requests
  • Coordinates between Model and View
  • Process user input
  • Select appropriate View

MVC Flow:

Spring MVC Example:

Controller:

Java

Model:

Java

View (JSP):

jsp

MVC Advantages:

  • Separation of Concerns: Clear separation of responsibilities
  • Maintainability: Easy to maintain and modify
  • Reusability: Components can be reused
  • Testability: Each component can be tested independently
  • Parallel Development: Different teams can work on different components

MVC in Web Applications:

  • Model: Database entities, business logic
  • View: JSP pages, HTML templates
  • Controller: Servlets, Spring controllers

Design Patterns Used:

  • Front Controller: Single entry point for requests
  • Observer Pattern: Model notifies View of changes
  • Strategy Pattern: Different Views for same Model

Mnemonic: "Model manages data, View shows data, Controller controls flow"