Advanced Java Programming (4351603) - Summer 2024 Solution

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

Question 1(a) [3 marks]

Explain the difference between AWT and Swing.

Answer:

FeatureAWTSwing
PlatformPlatform dependentPlatform independent
ComponentsHeavy weightLight weight
Look & FeelNative OS lookPluggable look & feel
PerformanceFasterSlower than AWT

Key Points:

  • Heavy vs Light: AWT uses native OS components, Swing uses pure Java
  • Appearance: AWT follows OS style, Swing offers consistent look across platforms
  • Features: Swing provides more advanced components like JTable, JTree

Mnemonic: "Swing Provides Lightweight Components"


Question 1(b) [4 marks]

Explain Mouse Motion Listener with example.

Answer:

MouseMotionListener interface handles mouse movement events in Java Swing applications.

Table: Mouse Motion Events

MethodPurpose
mouseDragged()Called when mouse is dragged
mouseMoved()Called when mouse is moved

Code Example:

Java

Mnemonic: "Mouse Motion Makes Dynamic"


Question 1(c) [7 marks]

Develop a program to create checkboxes for different courses belonging to a university such that the course selected would be displayed.

Answer:

Java

Key Features:

  • ItemListener: Detects checkbox state changes
  • Dynamic Display: Updates selected courses in real-time
  • Multiple Selection: Allows selecting multiple courses

Mnemonic: "Check Items Listen Dynamically"


Question 1(c) OR [7 marks]

Develop a program to Implement Traffic signal (Red, Green and Yellow) by using Swing components (Using JFrame, JRadioButton, ItemListener etc.)

Answer:

Java

Diagram:

goat

Mnemonic: "Radio Buttons Paint Graphics"


Question 2(a) [3 marks]

Explain JDBC type-4 driver.

Answer:

JDBC Type-4 Driver (Native Protocol Driver)

FeatureDescription
TypePure Java driver
CommunicationDirect database protocol
PlatformPlatform independent
PerformanceHighest performance

Key Points:

  • Pure Java: No native code required
  • Direct Connection: Communicates directly with database
  • Network Protocol: Uses database's native network protocol
  • Best Performance: Fastest among all driver types

Mnemonic: "Pure Java Direct Protocol"


Question 2(b) [4 marks]

Explain Commonly used Methods of Component class.

Answer:

Table: Component Class Methods

MethodPurpose
add()Adds component to container
setSize()Sets component dimensions
setLayout()Sets layout manager
setVisible()Makes component visible/invisible
setBounds()Sets position and size
getSize()Returns component size

Key Features:

  • Layout Management: Controls component arrangement
  • Visibility Control: Shows/hides components
  • Size Management: Controls component dimensions
  • Container Operations: Manages child components

Mnemonic: "Add Set Get Visibility"


Question 2(c) [7 marks]

Develop a program using JDBC to display student's record (Enroll No, Name, Address, Mobile No and Email-ID) from table 'StuRec'.

Answer:

Java

Database Table Structure:

SQL

Mnemonic: "Connect Query Display Records"


Question 2(a) OR [3 marks]

Write down the advantages and disadvantages of JDBC.

Answer:

Table: JDBC Advantages and Disadvantages

AdvantagesDisadvantages
Platform IndependentPerformance Overhead
Database IndependentComplex for beginners
Standard APISQL dependency
Supports transactionsManual resource management

Key Points:

  • Portability: Works across different platforms and databases
  • Standardization: Uniform API for database operations
  • Performance: Additional layer causes overhead
  • Complexity: Requires proper resource management

Mnemonic: "Platform Independent Standard Complex"


Question 2(b) OR [4 marks]

Explain Border Layout.

Answer:

BorderLayout divides container into five regions: North, South, East, West, and Center.

Diagram:

goat

Table: Border Layout Regions

RegionPositionBehavior
NORTHTopPreferred height, full width
SOUTHBottomPreferred height, full width
EASTRightPreferred width, full height
WESTLeftPreferred width, full height
CENTERMiddleTakes remaining space

Code Example:

Java

Mnemonic: "North South East West Center"


Question 2(c) OR [7 marks]

Develop an application to store, update, fetch and delete data of Employee (NAME, AGE, SALARY and DEPARTMENT) using Hibernate CRUD operations.

Answer:

Employee Entity Class:

Java

CRUD Operations Class:

Java

Mnemonic: "Save Get Update Delete Hibernate"


Question 3(a) [3 marks]

Explain Deployment Descriptor.

Answer:

Deployment Descriptor (web.xml) is configuration file for web applications containing servlet mappings, initialization parameters, and security settings.

Table: Deployment Descriptor Elements

ElementPurpose
<servlet>Defines servlet configuration
<servlet-mapping>Maps servlet to URL pattern
<init-param>Sets initialization parameters
<welcome-file-list>Default files to serve

Key Features:

  • Configuration: Central configuration for web app
  • Servlet Mapping: URL to servlet mapping
  • Parameters: Initialization and context parameters
  • Security: Authentication and authorization settings

Mnemonic: "Web XML Configuration Mapping"


Question 3(b) [4 marks]

Explain the difference between get and post method in servlet.

Answer:

Table: GET vs POST Methods

FeatureGETPOST
Data LocationURL query stringRequest body
Data SizeLimited (2048 chars)Unlimited
SecurityLess secure (visible)More secure
CachingCan be cachedNot cached
BookmarkingCan bookmarkCannot bookmark
PurposeRetrieve dataSubmit/modify data

Key Points:

  • Visibility: GET data visible in URL, POST hidden
  • Capacity: POST can handle large data
  • Security: POST better for sensitive data
  • Usage: GET for fetching, POST for form submission

Mnemonic: "GET Visible Limited, POST Hidden Unlimited"


Question 3(c) [7 marks]

Develop a simple servlet program which maintains a counter for the number of times it has been accessed since its loading; initialize the counter using deployment descriptor.

Answer:

Servlet Code:

Java

web.xml Configuration:

xml

Key Features:

  • Thread Safety: Synchronized counter increment
  • Initialization: Counter initialized from web.xml
  • Persistent: Counter maintained across requests
  • Configuration: Deployment descriptor setup

Mnemonic: "Initialize Synchronize Count Display"


Question 3(a) OR [3 marks]

Explain the life cycle of a servlet.

Answer:

Servlet Life Cycle Diagram:

Table: Servlet Life Cycle Methods

MethodPurposeCalled
init()Initialize servletOnce at startup
service()Handle requestsFor each request
destroy()Cleanup resourcesOnce at shutdown

Key Points:

  • Initialization: Called once when servlet loads
  • Service: Handles all client requests
  • Cleanup: Called before servlet unloads
  • Container Managed: Web container controls lifecycle

Mnemonic: "Initialize Service Destroy"


Question 3(b) OR [4 marks]

Explain Servlet Config class with suitable example.

Answer:

ServletConfig provides servlet-specific configuration information and initialization parameters.

Table: ServletConfig Methods

MethodPurpose
getInitParameter()Gets init parameter value
getInitParameterNames()Gets all parameter names
getServletContext()Gets servlet context
getServletName()Gets servlet name

Example:

Java

web.xml:

xml

Mnemonic: "Config Gets Parameters Context"


Question 3(c) OR [7 marks]

Develop a simple program, when user select the subject code, name of the subject will be displayed using servlet and mysql database.

Answer:

HTML Form (index.html):

HTML

Servlet Code:

Java

Database Table:

SQL

Mnemonic: "Select Query Display Subject"


Question 4(a) [3 marks]

Explain JSP life cycle.

Answer:

JSP Life Cycle Diagram:

Table: JSP Life Cycle Phases

PhaseDescription
TranslationJSP to Servlet conversion
CompilationServlet to bytecode
LoadingLoad servlet class
InitializationjspInit() called
Request Processing_jspService() handles requests
DestructionjspDestroy() cleanup

Mnemonic: "Translate Compile Load Initialize Service Destroy"


Question 4(b) [4 marks]

Compare JSP and Servlet.

Answer:

Table: JSP vs Servlet Comparison

FeatureJSPServlet
Code TypeHTML with Java codePure Java code
DevelopmentEasier for web designersBetter for Java developers
CompilationAutomaticManual
ModificationNo restart neededRestart required
PerformanceSlower first requestFaster
MaintenanceEasierMore complex

Key Points:

  • Ease of Use: JSP easier for presentation layer
  • Performance: Servlet better for business logic
  • Flexibility: JSP better for dynamic content
  • Control: Servlet provides more control

Mnemonic: "JSP Easy HTML, Servlet Pure Java"


Question 4(c) [7 marks]

Develop a JSP web application to display student monthly attendance in each subject of current semester via enrolment number.

Answer:

Input Form (attendance.html):

HTML

JSP Page (attendanceCheck.jsp):

jsp

Database Tables:

SQL

Mnemonic: "JSP Database Query Display Table"


Question 4(a) OR [3 marks]

Explain implicit objects in JSP.

Answer:

Table: JSP Implicit Objects

ObjectTypePurpose
requestHttpServletRequestGets request data
responseHttpServletResponseSends response
outJspWriterOutput to client
sessionHttpSessionSession management
applicationServletContextApplication scope
configServletConfigServlet configuration
pageContextPageContextPage scope access
pageObjectCurrent servlet instance
exceptionThrowableError page exception

Key Features:

  • Automatic: Available without declaration
  • Scope Access: Different scope levels
  • Request Handling: Input/output operations
  • Session Management: User session tracking

Mnemonic: "Request Response Out Session Application"


Question 4(b) OR [4 marks]

Explain why JSP is preferred over servlet.

Answer:

Table: JSP Advantages over Servlet

AspectJSP Advantage
DevelopmentEasier HTML integration
MaintenanceSeparates presentation from logic
CompilationAutomatic compilation
ModificationNo server restart needed
DesignWeb designer friendly
Code ReuseTag libraries and custom tags

Key Points:

  • Separation of Concerns: Clear separation of presentation and business logic
  • Rapid Development: Faster development cycle
  • Designer Friendly: Web designers can work with HTML-like syntax
  • Automatic Features: Container handles compilation and lifecycle

Mnemonic: "Easy HTML Automatic Designer Friendly"


Question 4(c) OR [7 marks]

Develop a JSP program to display the grade of a student by accepting the marks of five subjects.

Answer:

Input Form (gradeInput.html):

HTML

JSP Grade Calculator (gradeCalculator.jsp):

jsp

Grade Scale Table:

PercentageGradeDescription
90-100A+Excellent
80-89AVery Good
70-79BGood
60-69CAverage
50-59DBelow Average
0-49FFail

Mnemonic: "Calculate Total Percentage Grade Result"


Question 5(a) [3 marks]

Explain Aspect-oriented programming (AOP).

Answer:

AOP is programming paradigm that separates cross-cutting concerns from business logic using aspects.

Table: AOP Core Concepts

ConceptDescription
AspectModule encapsulating cross-cutting concern
Join PointPoint in program execution
PointcutSet of join points
AdviceAction taken at join point
WeavingProcess of applying aspects

Key Benefits:

  • Separation: Separates business logic from system services
  • Modularity: Improves code modularity
  • Reusability: Cross-cutting concerns are reusable
  • Maintenance: Easier to maintain and modify

Mnemonic: "Aspect Join Pointcut Advice Weaving"


Question 5(b) [4 marks]

List various features of Servlet.

Answer:

Table: Servlet Features

FeatureDescription
Platform IndependentRuns on any server supporting Java
Server IndependentWorks with different web servers
Protocol IndependentSupports HTTP, HTTPS, FTP
PersistentRemains in memory between requests
RobustStrong memory management
SecureBuilt-in security features
PortableWrite once, run anywhere
PowerfulFull Java API access

Key Points:

  • Performance: Better performance than CGI
  • Memory Management: Efficient memory usage
  • Multithreading: Handles multiple requests simultaneously
  • Extensible: Can be extended for specific protocols

Mnemonic: "Platform Server Protocol Persistent Robust"


Question 5(c) [7 marks]

Explain Model layer, View layer and Controller layer in details.

Answer:

MVC Architecture Diagram:

Table: MVC Layer Details

LayerResponsibilityComponentsPurpose
ModelData and business logicEntities, DAOs, ServicesData management
ViewPresentation layerJSP, HTML, CSSUser interface
ControllerRequest handlingServlets, ActionsFlow control

Model Layer Details:

  • Data Access: Database operations and data persistence
  • Business Logic: Core application logic and rules
  • Validation: Data validation and integrity checks
  • Entity Classes: Java beans representing data structures

Example Model:

Java

View Layer Details:

  • Presentation: User interface rendering
  • Display Logic: How data is presented to user
  • User Interaction: Forms, buttons, navigation
  • Responsive Design: Adapts to different devices

Controller Layer Details:

  • Request Handling: Processes user requests
  • Flow Control: Determines next view to display
  • Model Coordination: Calls appropriate model methods
  • Response Generation: Prepares response for user

Example Controller:

Java

Benefits of MVC:

  • Separation of Concerns: Clear responsibility division
  • Maintainability: Easier to maintain and modify
  • Testability: Each layer can be tested independently
  • Scalability: Supports large application development
  • Team Development: Multiple developers can work simultaneously

Mnemonic: "Model Data View Present Controller Handle"


Question 5(a) OR [3 marks]

Explain Features in Spring Boot.

Answer:

Table: Spring Boot Features

FeatureDescription
Auto ConfigurationAutomatic configuration based on dependencies
Starter DependenciesCurated set of dependencies
Embedded ServersBuilt-in Tomcat, Jetty servers
Production ReadyHealth checks, metrics, monitoring
No XML ConfigurationAnnotation-based configuration
Developer ToolsHot reloading, automatic restart

Key Benefits:

  • Rapid Development: Quick project setup and development
  • Convention over Configuration: Sensible defaults
  • Microservices Ready: Easy microservices development
  • Cloud Native: Ready for cloud deployment

Mnemonic: "Auto Starter Embedded Production Annotation Developer"


Question 5(b) OR [4 marks]

Write Short note on JSP scripting elements.

Answer:

Table: JSP Scripting Elements

ElementSyntaxPurposeExample
Scriptlet<% %>Java code execution<% int x = 10; %>
Expression<%= %>Output value<%= x + 5 %>
Declaration<%! %>Variable/method declaration<%! int count = 0; %>
Directive<%@ %>Page configuration<%@ page import="java.util.*" %>
Comment<%-- --%>JSP comments<%-- This is comment --%>

Examples:

jsp

Key Points:

  • Scriptlet: Contains Java statements
  • Expression: Evaluates and outputs result
  • Declaration: Creates instance variables/methods
  • Directive: Provides page-level information

Mnemonic: "Script Express Declare Direct Comment"


Question 5(c) OR [7 marks]

Explain Dependency injection (DI) and Plain Old Java Object (POJO) in details.

Answer:

Dependency Injection (DI):

Dependency Injection is design pattern where objects receive their dependencies from external source rather than creating them internally.

Table: DI Types

TypeDescriptionExample
Constructor InjectionDependencies via constructorpublic Service(Repository repo)
Setter InjectionDependencies via setter methodssetRepository(Repository repo)
Field InjectionDirect field injection@Autowired Repository repo

DI Example:

Java

Spring DI Configuration:

Java

Plain Old Java Object (POJO):

POJO is simple Java object that doesn't inherit from any specific framework classes or implement specific interfaces.

POJO Characteristics:

  • No inheritance: Doesn't extend framework classes
  • No interfaces: Doesn't implement framework interfaces
  • No annotations: Can work without framework annotations
  • Simple: Contains only business logic and data

POJO Example:

Java

Benefits of DI:

  • Loose Coupling: Reduces dependencies between classes
  • Testability: Easy to inject mock objects for testing
  • Flexibility: Easy to change implementations
  • Maintainability: Easier to maintain and extend code

Benefits of POJO:

  • Simplicity: Easy to understand and maintain
  • Testability: Simple to unit test
  • Portability: Can be used across different frameworks
  • Lightweight: No framework overhead

DI and POJO Together:

Java

Mnemonic: "DI Injects Dependencies, POJO Plain Objects"