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:
| Feature | AWT | Swing |
|---|---|---|
| Platform | Platform dependent | Platform independent |
| Components | Heavy weight | Light weight |
| Look & Feel | Native OS look | Pluggable look & feel |
| Performance | Faster | Slower 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
| Method | Purpose |
|---|---|
| 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)
| Feature | Description |
|---|---|
| Type | Pure Java driver |
| Communication | Direct database protocol |
| Platform | Platform independent |
| Performance | Highest 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
| Method | Purpose |
|---|---|
| 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
| Advantages | Disadvantages |
|---|---|
| Platform Independent | Performance Overhead |
| Database Independent | Complex for beginners |
| Standard API | SQL dependency |
| Supports transactions | Manual 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
| Region | Position | Behavior |
|---|---|---|
| NORTH | Top | Preferred height, full width |
| SOUTH | Bottom | Preferred height, full width |
| EAST | Right | Preferred width, full height |
| WEST | Left | Preferred width, full height |
| CENTER | Middle | Takes 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
| Element | Purpose |
|---|---|
| <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
| Feature | GET | POST |
|---|---|---|
| Data Location | URL query string | Request body |
| Data Size | Limited (2048 chars) | Unlimited |
| Security | Less secure (visible) | More secure |
| Caching | Can be cached | Not cached |
| Bookmarking | Can bookmark | Cannot bookmark |
| Purpose | Retrieve data | Submit/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
| Method | Purpose | Called |
|---|---|---|
| init() | Initialize servlet | Once at startup |
| service() | Handle requests | For each request |
| destroy() | Cleanup resources | Once 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
| Method | Purpose |
|---|---|
| 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
| Phase | Description |
|---|---|
| Translation | JSP to Servlet conversion |
| Compilation | Servlet to bytecode |
| Loading | Load servlet class |
| Initialization | jspInit() called |
| Request Processing | _jspService() handles requests |
| Destruction | jspDestroy() cleanup |
Mnemonic: "Translate Compile Load Initialize Service Destroy"
Question 4(b) [4 marks]
Compare JSP and Servlet.
Answer:
Table: JSP vs Servlet Comparison
| Feature | JSP | Servlet |
|---|---|---|
| Code Type | HTML with Java code | Pure Java code |
| Development | Easier for web designers | Better for Java developers |
| Compilation | Automatic | Manual |
| Modification | No restart needed | Restart required |
| Performance | Slower first request | Faster |
| Maintenance | Easier | More 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
| Object | Type | Purpose |
|---|---|---|
| request | HttpServletRequest | Gets request data |
| response | HttpServletResponse | Sends response |
| out | JspWriter | Output to client |
| session | HttpSession | Session management |
| application | ServletContext | Application scope |
| config | ServletConfig | Servlet configuration |
| pageContext | PageContext | Page scope access |
| page | Object | Current servlet instance |
| exception | Throwable | Error 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
| Aspect | JSP Advantage |
|---|---|
| Development | Easier HTML integration |
| Maintenance | Separates presentation from logic |
| Compilation | Automatic compilation |
| Modification | No server restart needed |
| Design | Web designer friendly |
| Code Reuse | Tag 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:
| Percentage | Grade | Description |
|---|---|---|
| 90-100 | A+ | Excellent |
| 80-89 | A | Very Good |
| 70-79 | B | Good |
| 60-69 | C | Average |
| 50-59 | D | Below Average |
| 0-49 | F | Fail |
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
| Concept | Description |
|---|---|
| Aspect | Module encapsulating cross-cutting concern |
| Join Point | Point in program execution |
| Pointcut | Set of join points |
| Advice | Action taken at join point |
| Weaving | Process 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
| Feature | Description |
|---|---|
| Platform Independent | Runs on any server supporting Java |
| Server Independent | Works with different web servers |
| Protocol Independent | Supports HTTP, HTTPS, FTP |
| Persistent | Remains in memory between requests |
| Robust | Strong memory management |
| Secure | Built-in security features |
| Portable | Write once, run anywhere |
| Powerful | Full 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
| Layer | Responsibility | Components | Purpose |
|---|---|---|---|
| Model | Data and business logic | Entities, DAOs, Services | Data management |
| View | Presentation layer | JSP, HTML, CSS | User interface |
| Controller | Request handling | Servlets, Actions | Flow 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
| Feature | Description |
|---|---|
| Auto Configuration | Automatic configuration based on dependencies |
| Starter Dependencies | Curated set of dependencies |
| Embedded Servers | Built-in Tomcat, Jetty servers |
| Production Ready | Health checks, metrics, monitoring |
| No XML Configuration | Annotation-based configuration |
| Developer Tools | Hot 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
| Element | Syntax | Purpose | Example |
|---|---|---|---|
| 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
| Type | Description | Example |
|---|---|---|
| Constructor Injection | Dependencies via constructor | public Service(Repository repo) |
| Setter Injection | Dependencies via setter methods | setRepository(Repository repo) |
| Field Injection | Direct 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"