0% found this document useful (0 votes)
9 views9 pages

Advanced Java Important Questions

This document is a preparation guide for an Advanced Java semester examination, covering important topics across three units. It includes key questions and answers on J2EE architecture, servlets, JSP, JDBC, RMI, exceptions, socket programming, multithreading, I/O streams, and Java Swing. Each section provides concise explanations of concepts, life cycles, and examples to aid in understanding.

Uploaded by

abpro86000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Advanced Java Important Questions

This document is a preparation guide for an Advanced Java semester examination, covering important topics across three units. It includes key questions and answers on J2EE architecture, servlets, JSP, JDBC, RMI, exceptions, socket programming, multithreading, I/O streams, and Java Swing. Each section provides concise explanations of concepts, life cycles, and examples to aid in understanding.

Uploaded by

abpro86000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Java

Important Questions & Answers


Semester Examination Preparation Guide
12 Most Expected Questions | Units 1, 2 & 3

UNIT 1 — J2EE Architecture, Servlets & JSP

Q1
Explain the J2EE four-tier architecture with a neat diagram description.
.

J2EE (Java 2 Platform, Enterprise Edition) follows a four-tier architecture that separates concerns
across different layers:
1. Client Tier (Presentation Tier): Contains programs that interact directly with users. Components
include Applet Clients (inside browsers), Application Clients (standalone Java apps), and Rich Clients
(non-Java clients using HTTP/SOAP). It sends requests to the Web Tier.
2. Web Tier: Provides internet functionality using HTTP. It acts as an intermediary between the client
and business logic. Main components are Servlets and JSP (JavaServer Pages). Accepts
GET/POST/PUT requests and transmits dynamic content back.
3. EJB Tier (Business Tier): Contains business logic via Enterprise JavaBeans (EJB). Managed by
an EJB server and container. Provides concurrency, scalability, lifecycle management, security, and
fault-tolerance.
4. EIS Tier (Enterprise Information System Tier): Links the J2EE application to corporate
databases, legacy systems, and third-party resources using CORBA or Java Connectors. An Access
Control List (ACL) controls communication between tiers for security.
Key features of J2EE: Platform independence (JVM), multi-tier support, built-in security &
transaction management, scalability, and component reusability.

Q2
Describe the Servlet life cycle with its four stages and key methods.
.

A Servlet's life cycle is managed entirely by the Servlet Container (e.g., Apache Tomcat). It consists
of four main stages:
Stage 1 — Loading & Instantiation: The container loads the servlet class into memory and creates
one instance using the no-argument constructor. This happens at application startup (if configured) or
on the first client request (lazy loading).
Stage 2 — Initialization (init()): The init(ServletConfig config) method is called exactly once in the
servlet's lifetime. Used to set up resources like database connections. Unlike service(), it is NOT
called for every request.
Stage 3 — Request Handling (service()): The container calls service() for every incoming client
request. It determines the HTTP method type (GET, POST, PUT, DELETE) and delegates to the
appropriate method: doGet(), doPost(), etc. HttpServletRequest and HttpServletResponse objects
are created per request.
Stage 4 — Destruction (destroy()): Called once before the servlet is taken out of service. Used to
release resources (close DB connections, free memory). After this, the instance becomes eligible for
garbage collection.
Workflow Summary: Client → Web Server → Servlet Container → init() → service() →
doGet()/doPost() → Response → Client

Q3
What is Session Handling in Servlets? Explain its methods and key operations.
.

Session Handling is a mechanism to maintain user state across multiple HTTP requests. Since
HTTP is a stateless protocol, sessions help remember user data (such as login info, shopping cart
items) across requests.
Methods of Session Handling:
• HttpSession — Stores data on the server side (most commonly used).
• Cookies — Stores small data on the client browser.
• URL Rewriting — Appends session ID to the URL.
• Hidden Fields — Stores data inside HTML form fields.
Key Operations:
• Create session: [Link]()
• Store data: [Link]("key", value)
• Retrieve data: [Link]("key")
• Destroy session: [Link]()
Each user is assigned a unique Session ID to track their individual requests across the application.

Q4
Explain the JSP Life Cycle and its seven steps with JSP elements.
.

JSP (JavaServer Pages) is a server-side technology that allows embedding Java code directly into
HTML. When a JSP page is first requested, it is automatically converted and compiled into a servlet
by the JSP Engine.
JSP Life Cycle — 7 Steps:
1. Translation: JSP file is translated into a Java Servlet (.java file).
2. Compilation: The .java file is compiled into a .class (bytecode) file.
3. Class Loading: The .class file is loaded into memory.
4. Instantiation: An object of the generated servlet class is created.
5. Initialization: jspInit() method is called by the container once.
6. Request Processing: _jspService() handles each client request.
7. Cleanup: jspDestroy() is called before the JSP is removed from service.
Four JSP Elements:
• Expression <%= ... %> — Outputs data directly to page.
• Scriptlet <% ... %> — Embeds Java code (placed inside _jspService()).
• Directive <%@ ... %> — Page settings, file includes, tag libraries.
• Declaration <%! ... %> — Defines class-level variables and methods.
UNIT 2 — JDBC, Networking, RMI & Exceptions

Q5
What is JDBC? Explain the [Link] package and JDBC flow with key interfaces.
.

JDBC (Java Database Connectivity) is an API that enables Java applications to communicate with
relational databases like MySQL, Oracle, and PostgreSQL. It is contained in the [Link] and
[Link] packages.
Key Interfaces and Classes in [Link]:
• DriverManager — Manages drivers; establishes the DB connection.
• Connection — Represents a live connection to the database.
• Statement — Executes simple SQL queries.
• PreparedStatement — Executes precompiled queries; prevents SQL injection.
• ResultSet — Holds and iterates through query results.
• SQLException — Handles all database-related errors.
JDBC Flow (6 Steps):
1. Load the driver 2. Create connection 3. Create Statement
4. Execute SQL query 5. Process ResultSet 6. Close connection
Connection con = [Link](url, user, pass); Statement stmt =
[Link](); ResultSet rs = [Link]("SELECT * FROM students");
while([Link]()) { [Link]([Link](1)); }

Q6
Explain the RMI architecture with its components and working mechanism.
.

RMI (Remote Method Invocation) allows an object in one JVM to invoke methods of an object
residing in another JVM. It is used to build distributed Java applications (package: [Link]).
Key Components of RMI Architecture:
• Stub: A proxy/representative of the remote object on the client side. Acts as a gateway for the client
program to call remote methods.
• Skeleton: Resides on the server side. Receives requests from the stub and invokes the actual
remote object method.
• RRL (Remote Reference Layer): Manages references made by the client to the remote object.
• Transport Layer: Connects client and server; manages existing and new connections.
RMI Working Flow:
1. Client calls remote method → Stub receives the call.
2. Stub passes request to client-side RRL → RRL calls invoke() → Passes to server-side RRL.
3. Server RRL passes to Skeleton → Skeleton invokes the actual object on the server.
4. Result travels back through RRL → Stub → Client.
RMI Registry: A namespace where server objects are registered using bind()/rebind(). Clients locate
objects using lookup() with the bind name.
Steps to Build RMI App: Define remote interface → Implement interface → Generate Stub/Skeleton
(rmic) → Start rmiregistry → Run Server → Run Client

Q7 Differentiate Checked vs Unchecked Exceptions. How do you create custom


. exceptions?

Java exceptions are classified into Checked (compile-time) and Unchecked (runtime) exceptions.

Feature Checked Exception Unchecked Exception

Parent Class Exception RuntimeException

Compile-time Check Yes No

Mandatory Handling Yes (try-catch) No

Use Case Recoverable errors Programming/logic errors

Examples IOException, SQLException NullPointerException, ArithmeticException

Creating a Custom Checked Exception:


class InvalidAgeException extends Exception { public InvalidAgeException(String
msg) { super(msg); } } // Usage: throw new InvalidAgeException("Age must be 18+");

Creating a Custom Unchecked Exception:


class DivideByZeroException extends RuntimeException { public
DivideByZeroException(String msg) { super(msg); } }

Q8
Explain Socket Programming in Java with a client-server example using TCP.
.

Socket programming enables communication between client and server applications over TCP or
UDP using the [Link] package. TCP (Transmission Control Protocol) is connection-oriented and
ensures reliable, ordered delivery.
Key Classes:
• Socket — Represents the client-side TCP connection.
• ServerSocket — Listens for client connections on the server side.
• DataInputStream / DataOutputStream — Used to send and receive data.
Server Program:
ServerSocket ss = new ServerSocket(5000); Socket s = [Link](); // waits for
client DataInputStream dis = new DataInputStream([Link]()); String msg =
[Link](); [Link]("Client: " + msg);

Client Program:
Socket s = new Socket("localhost", 5000); DataOutputStream dos = new
DataOutputStream([Link]()); [Link]("Hello Server"); [Link]();
[Link]();

Flow: Server starts → listens on port 5000 → Client connects → sends message → Server receives and
prints message.
UNIT 3 — Multithreading, I/O Streams & Swing

Q9
What is Multithreading? Explain the Thread life cycle with all six states.
.

Multithreading is a Java feature that allows a program to execute multiple threads simultaneously,
enabling parallel task execution and efficient CPU utilization. A Thread is a lightweight, independent
unit of execution within a process. Multiple threads share the same memory space.
Two Ways to Create Threads:
1. Extending Thread class — Override run(); call start().
2. Implementing Runnable interface — Preferred when class already extends another class.
Thread Life Cycle — 6 States:
1. New: Thread is created but start() not yet called. Code not yet executing.
2. Runnable: Thread is ready to run. Scheduler decides when to allocate CPU time.
3. Blocked: Thread is waiting to acquire a lock held by another thread.
4. Waiting: Thread calls wait() or join(); waits for notification or thread completion.
5. Timed Waiting: Thread calls sleep(ms) or wait(timeout); returns after timeout.
6. Terminated: Thread finishes run() normally or due to an unhandled exception.
Note: Call start() (not run()) to create a new thread. Calling run() directly executes in the current thread
— no new thread is created.

Q1
What is Synchronization in Java? Explain with types and a code example.
0.

Synchronization is a mechanism that ensures only one thread can access a shared resource
(variable, object, or method) at a time. It prevents race conditions and ensures data integrity in
concurrent environments.
Why Synchronization is Needed:
• Prevents Data Inconsistency from simultaneous access.
• Avoids Race Conditions (unpredictable results when threads compete).
• Maintains Thread Safety and Data Integrity.
Three Ways to Achieve Synchronization:
1. Synchronized Method — Only one thread executes the method at a time on the same instance.
2. Synchronized Block — Synchronizes only a critical section of code (more efficient).
3. Synchronized Static Method — Locks the class-level (Class object) monitor.
Example — Synchronized Method:
public class Counter { private int count = 0; public synchronized void increment()
{ count++; // only one thread at a time } public int getCount() { return count; } }

Inter-Thread Communication: Use wait() (releases lock, pauses thread), notify() (wakes one waiting
thread), and notifyAll() (wakes all waiting threads). These belong to the Object class and must be used
inside a synchronized block.
Q1 Explain I/O Streams in Java: Byte Streams, Character Streams, and File
1. Streams.

Java I/O ([Link] package) provides classes and streams for reading data from sources (files,
keyboard, network) and writing data to destinations (files, console, sockets).
Standard Streams:
• [Link] — Standard input (keyboard).
• [Link] — Standard output (screen).
• [Link] — Standard error (error messages).
1. Byte Streams (8-bit data — binary):
Handle raw binary data (images, audio, video). Key classes:
• FileInputStream / FileOutputStream — Read/write files byte-by-byte.
• BufferedInputStream / BufferedOutputStream — Efficient buffered reading/writing.
• DataInputStream / DataOutputStream — Read/write Java primitive types.
2. Character Streams (16-bit Unicode — text):
Handle text data. Key classes:
• FileReader / FileWriter — Read/write character files.
• BufferedReader / BufferedWriter — Buffered text reading/writing.
• InputStreamReader / OutputStreamWriter — Bridge between byte and character streams.
Byte Stream Example (File Copy):
FileInputStream src = new FileInputStream("[Link]"); FileOutputStream tgt =
new FileOutputStream("[Link]"); int temp; while ((temp = [Link]()) != -1) {
[Link]((byte)temp); } [Link](); [Link]();

Q1 Explain Java Swing: MVC architecture, basic components, and Pluggable Look
2. & Feel.

Java Swing is a GUI toolkit (part of JFC — Java Foundation Classes) used to create
platform-independent window-based applications. It extends AWT and uses [Link] package.
Swing components are pure Java (lightweight) unlike AWT (platform-dependent/heavyweight).
MVC Architecture in Swing:
Swing follows the Model-View-Controller pattern:
• Model — Holds business data and logic (e.g., Student class with name, marks).
• View — Displays data to the user (e.g., StudentView with displayStudent()).
• Controller — Bridges Model and View; handles user input and updates both.
Basic Swing Components:
• JFrame — Top-level container/main window. Use setVisible(true), setSize().
• JButton — Clickable button; use setBounds() and addActionListener().
• JTextField — Single-line text input. Methods: getText(), setText(), setEditable().
• JCheckBox — Multi-select options; isSelected() to check state.
• JRadioButton + ButtonGroup — Single-select options from a group.
• JToggleButton — Two-state button (ON/OFF); isSelected() to check.
Pluggable Look and Feel (PLAF):
Allows the visual appearance (Look) and interactive behavior (Feel) of Swing components to be
changed at runtime without modifying application code. Based on a modified MVC pattern where
View and Controller are combined into a UI Delegate. Available L&Fs: Metal (default), Nimbus,
Windows, GTK.
[Link]("[Link]");
[Link](frame);

Quick Reference Summary


Q# Topic Unit

Q1 J2EE Four-Tier Architecture Unit 1

Q2 Servlet Life Cycle (4 Stages) Unit 1

Q3 Session Handling in Servlets Unit 1

Q4 JSP Life Cycle & JSP Elements Unit 1

Q5 JDBC & [Link] Package Unit 2

Q6 RMI Architecture & Working Unit 2

Q7 Custom Exceptions (Checked vs Unchecked) Unit 2

Q8 Socket Programming (TCP) Unit 2

Q9 Multithreading & Thread Life Cycle Unit 3

Q10 Synchronization in Java Unit 3

Q11 I/O Streams (Byte & Character) Unit 3

Q12 Java Swing: MVC, Components, PLAF Unit 3

Good Luck with your Semester Examination! ■

You might also like