Advanced Java Programming (4351603) - Winter 2024 Solution

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

Question 1(a) [3 marks]

Describe JFC with its usage.

Answer:

JFC (Java Foundation Classes) is a comprehensive GUI framework for building desktop applications in Java.

ComponentDescription
SwingLightweight GUI components
AWTBasic windowing toolkit
Java 2DAdvanced graphics and imaging
AccessibilitySupport for assistive technologies
  • Primary Usage: Creating rich desktop applications
  • Key Advantage: Platform independence and consistent look

Mnemonic: "JFC = Java's Fantastic Components"

Question 1(b) [4 marks]

Explain Difference between AWT and Swing.

Answer:

FeatureAWTSwing
ComponentsHeavyweight (native)Lightweight (pure Java)
PlatformPlatform dependentPlatform independent
Look & FeelNative OS lookPluggable look and feel
PerformanceFasterSlightly slower
  • AWT Limitation: Limited components, platform-specific appearance
  • Swing Advantage: Rich component set, customizable UI

Mnemonic: "AWT = Always Weighs Too-much, Swing = Simply Works In New Generation"

Question 1(c) [7 marks]

List out various Event Listener. Explain anyone.

Answer:

Event Listeners List:

ListenerPurpose
ActionListenerButton clicks, menu selections
MouseListenerMouse events (click, press, release)
KeyListenerKeyboard input events
WindowListenerWindow state changes
FocusListenerComponent focus events
ItemListenerCheckbox/radio button changes

ActionListener Explanation:

  • Interface Method: actionPerformed(ActionEvent e)
  • Usage: Handles button clicks and menu actions
  • Implementation: Anonymous class or lambda expression
Java

Mnemonic: "AMKWFI Listeners = Action Mouse Key Window Focus Item"

Question 1(c OR) [7 marks]

List out various Layout Managers. Explain anyone.

Answer:

Layout Managers List:

Layout ManagerPurpose
FlowLayoutSequential component placement
BorderLayoutFive regions (North, South, East, West, Center)
GridLayoutGrid-based arrangement
CardLayoutStack of components
BoxLayoutSingle row or column
GridBagLayoutComplex grid with constraints

BorderLayout Explanation:

  • Default Layout: For JFrame and JDialog
  • Five Regions: North, South, East, West, Center
  • Resizing: Center expands, others stay preferred size

Mnemonic: "FBGCBG Layouts = Flow Border Grid Card Box GridBag"

Question 2(a) [3 marks]

List out and explain steps to connect database.

Answer:

Database Connection Steps:

StepAction
1. Load DriverClass.forName("driver.class")
2. Create ConnectionDriverManager.getConnection()
3. Create Statementconnection.createStatement()
4. Execute Querystatement.executeQuery()
5. Process ResultsresultSet.next()
6. Close ResourcesClose all connections

Mnemonic: "LCD EPR = Load Create Driver, Execute Process Results"

Question 2(b) [4 marks]

Explain 3-tier architecture with diagram.

Answer:

3-tier architecture separates application into three logical layers for better maintainability.

TierResponsibility
PresentationUser interface and user interaction
ApplicationBusiness logic and processing
DataData storage and management
  • Advantage: Better scalability and maintainability
  • Example: Web browser → Web server → Database

Mnemonic: "PAD = Presentation Application Data"

Question 2(c) [7 marks]

Describe JDBC API with interfaces and classes.

Answer:

JDBC API Components:

TypeComponentPurpose
InterfaceConnectionDatabase connection
InterfaceStatementSQL execution
InterfaceResultSetQuery results
InterfacePreparedStatementPrecompiled SQL
ClassDriverManagerDriver management
ClassSQLExceptionError handling

JDBC Architecture:

  • Core Interfaces: Connection, Statement, ResultSet, PreparedStatement
  • Key Classes: DriverManager for connection management
  • Exception Handling: SQLException for database errors

Mnemonic: "CSRP Classes = Connection Statement ResultSet PreparedStatement"

Question 2(a OR) [3 marks]

List out advantages and disadvantages of JDBC.

Answer:

JDBC Advantages vs Disadvantages:

AdvantagesDisadvantages
Platform IndependentPerformance Overhead
Standard APIComplex Configuration
Multiple Database SupportLimited ORM Features
  • Benefits: Write once, run anywhere with any database
  • Drawbacks: Requires manual SQL and connection management

Mnemonic: "PSM vs PCL = Platform Standard Multiple vs Performance Complex Limited"

Question 2(b OR) [4 marks]

Explain 2-tier architecture with diagram.

Answer:

2-tier architecture directly connects client to database server.

TierResponsibility
ClientUser interface and business logic
ServerData storage and management
  • Advantage: Simple architecture, direct communication
  • Disadvantage: Limited scalability, tight coupling
  • Example: Desktop application connecting directly to database

Mnemonic: "CD = Client Data (direct connection)"

Question 2(c OR) [7 marks]

List out JDBC driver types and Explain TYPE-4.

Answer:

JDBC Driver Types:

TypeNameDescription
Type-1JDBC-ODBC BridgeUses ODBC driver
Type-2Native-API DriverPart Java, part native
Type-3Network Protocol DriverPure Java, middleware
Type-4Native Protocol DriverPure Java, direct

TYPE-4 Driver Explanation:

  • Pure Java: Completely written in Java
  • Direct Communication: Directly communicates with database
  • Platform Independent: No native libraries required
  • Best Performance: Fastest among all types
  • Examples: MySQL Connector/J, PostgreSQL JDBC

Mnemonic: "ONNN Drivers = ODBC Native Network Native-pure"

Question 3(a) [3 marks]

Explain Application of servlet.

Answer:

Servlet Applications:

ApplicationUsage
Web FormsProcess HTML form data
Database OperationsConnect and manipulate database
Session ManagementTrack user sessions
File UploadHandle file uploads
  • Primary Use: Server-side Java programs for web applications
  • Common Tasks: Request processing, response generation

Mnemonic: "WDSF = Web Database Session File"

Question 3(b) [4 marks]

Explain difference between Applet and Servlet.

Answer:

FeatureAppletServlet
ExecutionClient-side (browser)Server-side (web server)
PurposeUser interfaceRequest processing
SecurityRestricted (sandbox)Full server access
PerformanceLimited by clientServer resources
  • Applet: Runs in web browser, limited capabilities
  • Servlet: Runs on web server, full Java capabilities

Mnemonic: "Client vs Server = Applet vs Servlet"

Question 3(c) [7 marks]

Explain life cycle of a servlet in detail.

Answer:

Servlet Life Cycle:

PhaseMethodDescription
LoadingClass loadingWeb container loads servlet class
Initializationinit()Called once, setup resources
Serviceservice()Handles each request (doGet/doPost)
Destructiondestroy()Cleanup before unloading
  • Thread Safety: Multiple requests handled concurrently
  • Single Instance: One servlet instance handles all requests
  • Container Managed: Web container manages lifecycle

Mnemonic: "LISD = Load Init Service Destroy"

Question 3(a OR) [3 marks]

Explain web.xml file in servlet.

Answer:

web.xml Purpose:

ElementDescription
Deployment DescriptorConfiguration file for web application
Servlet MappingMaps URL patterns to servlets
InitializationServlet parameters and load order
  • Location: WEB-INF directory
  • Format: XML configuration file

Mnemonic: "DMI = Deployment Mapping Initialization"

Question 3(b OR) [4 marks]

List out and Explain feature of servlet.

Answer:

Servlet Features:

FeatureDescription
Platform IndependentWrite once, run anywhere
Server-sideExecutes on web server
Protocol IndependentSupports HTTP, FTP, etc.
PersistentStays in memory between requests
SecureBuilt-in security features
  • Performance: Better than CGI scripts
  • Scalability: Handles multiple requests efficiently

Mnemonic: "PSPPS = Platform Server Protocol Persistent Secure"

Question 3(c OR) [7 marks]

Explain session tracking in servlet.

Answer:

Session Tracking Methods:

MethodDescription
CookiesSmall data stored in browser
URL RewritingSession ID in URL
Hidden Form FieldsSession data in forms
HttpSessionServer-side session object

HttpSession Implementation:

Java
  • Purpose: Maintain state across HTTP requests
  • HttpSession: Most commonly used method

Mnemonic: "CUHH = Cookies URL Hidden HttpSession"

Question 4(a) [3 marks]

Explain architecture of JSP with diagram.

Answer:

JSP Architecture:

ComponentRole
JSP EngineTranslates JSP to servlet
Web ContainerManages JSP lifecycle
Generated ServletActual execution unit

Mnemonic: "JSP = Java Server Pages (Page to Servlet)"

Question 4(b) [4 marks]

Explain JSP scripting elements with example.

Answer:

JSP Scripting Elements:

ElementSyntaxPurpose
Scriptlet<% code %>Java code block
Expression<%= expression %>Output value
Declaration<%! declaration %>Variables/methods

Examples:

jsp

Mnemonic: "SED = Scriptlet Expression Declaration"

Question 4(c) [7 marks]

Explain JSP life cycle.

Answer:

JSP Life Cycle Phases:

PhaseDescription
TranslationJSP converted to servlet source
CompilationServlet source compiled to bytecode
LoadingServlet class loaded by JVM
InstantiationServlet object created
InitializationjspInit() method called
Request Processing_jspService() handles requests
DestructionjspDestroy() cleanup method
  • Container Managed: Web container handles entire lifecycle
  • Automatic: Translation and compilation happen automatically

Mnemonic: "TCLIIRD = Translation Compilation Loading Instantiation Init Request Destroy"

Question 4(a OR) [3 marks]

Explain difference between JSP and Servlet.

Answer:

FeatureJSPServlet
Code StyleHTML with JavaPure Java code
DevelopmentEasier for UIBetter for logic
CompilationAutomaticManual
ModificationNo recompilation neededRequires recompilation

Mnemonic: "HTML vs Java = JSP vs Servlet"

Question 4(b OR) [4 marks]

List out and Explain advantage of JSP.

Answer:

JSP Advantages:

AdvantageDescription
Easy DevelopmentHTML-like syntax with Java
Automatic CompilationNo manual compilation needed
Platform IndependentRuns on any Java-enabled server
Separation of ConcernsDesign separated from logic
Reusable ComponentsTag libraries and beans
  • Developer Friendly: Web designers can work with JSP easily
  • Maintenance: Easier to modify than servlets

Mnemonic: "EAPSR = Easy Automatic Platform Separation Reusable"

Question 4(c OR) [7 marks]

What is cookie? Explain how to Read and delete cookie using JSP page.

Answer:

Cookie Overview: Cookie is a small piece of data stored on client's browser to maintain state.

Cookie Operations:

OperationJSP Code
CreateCookie cookie = new Cookie("name", "value");
Addresponse.addCookie(cookie);
ReadCookie[] cookies = request.getCookies();
Deletecookie.setMaxAge(0);

Reading Cookie Example:

jsp

Deleting Cookie Example:

jsp

Mnemonic: "CARD = Create Add Read Delete"

Question 5(a) [3 marks]

Explain importance of MVC architecture.

Answer:

MVC Importance:

BenefitDescription
Separation of ConcernsLogic, presentation, data separated
MaintainabilityEasy to modify individual components
TestabilityComponents can be tested independently
  • Code Organization: Better structure and organization
  • Team Development: Multiple developers can work simultaneously

Mnemonic: "SMT = Separation Maintainability Testability"

Question 5(b) [4 marks]

Explain Aspect oriented programming and dependency injection in brief.

Answer:

Aspect Oriented Programming (AOP):

ConceptDescription
Cross-cutting ConcernsLogging, security, transactions
AspectsModular units of cross-cutting functionality
Join PointsPoints where aspects are applied

Dependency Injection (DI):

ConceptDescription
Inversion of ControlDependencies provided externally
Loose CouplingObjects don't create dependencies
ConfigurationDependencies configured externally

Mnemonic: "AOP = Aspects Over Points, DI = Dependencies Injected"

Question 5(c) [7 marks]

Explain MVC architecture.

Answer:

MVC Components:

ComponentResponsibility
ModelBusiness logic and data management
ViewUser interface and presentation
ControllerRequest handling and flow control

MVC Flow:

  1. User Request → Controller receives request
  2. Controller → Processes request, calls Model
  3. Model → Performs business logic, returns data
  4. Controller → Selects appropriate View
  5. View → Renders response to user

Advantages:

  • Maintainability: Clear separation of responsibilities
  • Reusability: Components can be reused
  • Testability: Each layer can be tested independently

Mnemonic: "MVC = Model View Controller (Business UI Control)"

Question 5(a OR) [3 marks]

Explain advantages of MVC architecture.

Answer:

MVC Advantages:

AdvantageDescription
Code ReusabilityComponents can be reused across applications
Parallel DevelopmentMultiple developers work on different layers
Easy TestingEach component tested independently
MaintenanceChanges in one layer don't affect others

Mnemonic: "CPEM = Code Parallel Easy Maintenance"

Question 5(b OR) [4 marks]

Explain difference between spring and spring boot.

Answer:

FeatureSpringSpring Boot
ConfigurationManual XML/Java configAuto-configuration
Setup TimeMore setup requiredMinimal setup
Embedded ServerExternal server neededBuilt-in server
DependenciesManual dependency managementStarter dependencies
  • Spring: Comprehensive framework requiring configuration
  • Spring Boot: Convention over configuration approach

Mnemonic: "Manual vs Auto = Spring vs SpringBoot"

Question 5(c OR) [7 marks]

Explain architecture of Spring framework.

Answer:

Spring Framework Architecture:

Spring Modules:

ModulePurpose
Core ContainerIoC container, dependency injection
Data AccessJDBC, ORM, transaction management
WebWeb MVC, REST services
AOPAspect-oriented programming
SecurityAuthentication and authorization
TestTesting support and mock objects

Key Features:

  • IoC Container: Manages object creation and dependencies
  • AOP Support: Cross-cutting concerns handling
  • Transaction Management: Declarative transaction support
  • MVC Framework: Web application development

Mnemonic: "CDWAST = Core Data Web AOP Security Test"