0% found this document useful (0 votes)
3 views6 pages

Java

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)
3 views6 pages

Java

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

Q1) a) What is meant by package? List out the advantages a) Explain the concept of Interfaces in Java with example.

of packages. Definition: An interface in Java is a reference type, similar


Definition of Package: In Java (and many object-oriented to a class, that contains only abstract methods, default
programming languages), a package is a namespace that methods, static methods, and constants. Interfaces are
organizes a set of related classes and interfaces. used to define a contract for what a class can do, without
Conceptually, it is similar to folders on your computer. For specifying how it does it.
example, the Java API is grouped into packages such as Key Points: 1) Abstraction Tool: Interfaces provide a way to
[Link], [Link], and [Link]. Packages help avoid name achieve abstraction in Java by defining method signatures
conflicts and can control access with the use of access without implementations.
modifiers (like public, private, protected . 2) No Object Creation: Interfaces cannot be instantiated
Advantages of Packages: directly. 3) Multiple Inheritance: Java does not support
1) Namespace Management: Packages prevent naming multiple inheritance with classes but allows it with
conflicts. For example, two classes with the same name can interfaces. A class can implement multiple interfaces.
exist in different packages. 2) Access Protection: Classes in 4) Implicit Modifiers: All fields in an interface are implicitly
packages can be set to have package-private access, public, static, and final. All methods are public and abstract
limiting visibility only to other classes in the same package. by default except static and default methods from Java 8
3) Modularity: Packages help divide a project into logical onward. 6) Implementation Requirement: Any class that
partn s, which makes the project more organized and implements an interface must provide concrete
maintainable. 4) Code Reusability: Code in packages can be implementations for all its abstract methods.
reused across different projects or parts of the same example
project. 5) Easier Maintenance: Since related classes are interface Animal {
grouped together, it becomes easier to locate and maintain void sound(); // abstract method }
code. 6) Security:Packages can help enforce security class Dog implements Animal {
restrictions on classes by controlling their visibility. public void sound() {
[Link]("Dog barks");
b ) What is inheritance? Explain the use of } }
extends keyword in it
Inheritance : Inheritance is a fundamental concept in b) Explain the concept of static Members and member
object-oriented programming (OOP) that allows one class function of Java.
called the subclass or derived class to acquire the Static members (variables and methods) in Java are
properties and behaviors such as fields and methods of associated with the class itself rather than with any
another class called the superclass or base class. particular instance (object) of the class. They are shared
It supports the concept of "reusability" and "hierarchical across all instances.
classification". Instead of writing the same code multiple Static Members (Variables):
times, a subclass can reuse code from a superclass, and also 1) Class-Level Variables: Static variables are declared using
add its own specific features. the static keyword and belong to the class.
Advantages of Inheritance: 2) Single Copy: Only one copy of a static variable exists,
1) Code Reusability: Common features written in the regardless of how many objects are created.
superclass can be reused in all subclasses. 3) Shared Value: All objects share the same value of the
2) Method Overriding: A subclass can provide its own static variable. 4) Access: Can be accessed using the class
specific implementation of methods defined in the name or through an object.
superclass. 3) Extensibility: It’s easier to enhance or extend Example – class Counter {
the functionality of existing code. static int count = 0; // static variable
4) Organized Structure: Helps in logically grouping similar Counter() {
classes and promoting clean code architecture. count++;
Use of extends Keyword : [Link](count);
In Java, the extends keyword is used to establish an }}
inheritance relationship between two classes. It tells the Static Member Functions (Static Methods):
compiler that the current child class is inheriting from 1) Belongs to Class: Static methods are not tied to a specific
another parent class. object and can be called without creating an instance of the
Syntax : class. 2) No Access to Instance Variables: They cannot
class SubClass extends SuperClass { directly access non-static (instance) members because they
// SubClass inherits all accessible members of SuperClass do not operate on a specific object. 3) Usage: Commonly
} used for utility or helper methods (e.g., [Link]()).
The subclass inherits all non-private members (fields and 4) Declaration: Declared using the static keyword before
methods) of the superclass. the method name.
The subclass can override methods of the superclass to Example- class Utility {
provide a specific implementation. static void greet() {
The extends keyword is used only for class-to-class [Link]("Hello from static method"); }}
inheritance for interface implementation.
a) Describe thread Synchronization concept in details. 3) Creates a new File instance from a parent File object and
Thread Synchronization in Java is the process of controlling a child pathname string.
the access of multiple threads to shared resources (like Example: File parentDir = new File("C:\\Documents");
variables, objects, files, etc.) to avoid data inconsistency or File file = new File(parentDir, "[Link]");
race conditions.
Key Points: a) What is meant by multithreading? Explain different
1) Why Synchronization is Needed: When multiple threads priority can be set in.
access a shared resource without proper coordination, it Multithreading is a programming concept in Java where
can lead to inconsistent or unexpected results. multiple threads run concurrently within a single program.
Synchronization ensures that only one thread at a time can A thread is the smallest unit of execution, and
access the critical section of code. multithreading allows multiple threads to execute
2) Synchronized Block: Java provides a synchronized block independently and simultaneously, improving the efficiency
to lock a specific part of the code so that only one thread and performance of programs.
can execute it at a time. Threads share the same memory space but run
synchronized (object) { independently.
// synchronized code } Multithreading helps in performing multiple tasks at the
3) Synchronized Method: You can also synchronize entire same time, such as handling user input while processing
methods to prevent simultaneous access by multiple data.
threads. It improves CPU utilization and makes applications faster
synchronized void display() { and more responsive.
// critical section } Thread Priorities:
4) Intrinsic Lock / Monitor: Every object in Java has an Every thread in Java has a priority value which indicates its
intrinsic lock or monitor. When a thread enters a importance.
synchronized block or method, it acquires the object's lock, Thread priorities range from 1 to 10:
and no other thread can enter any synchronized Thread.MIN_PRIORITY (1): Lowest priority
method/block on the same object. Thread.NORM_PRIORITY (5): Normal/default priority
5) Deadlock Risk: Improper synchronization can lead to Thread.MAX_PRIORITY (10): Highest priority
deadlocks, where two or more threads wait indefinitely for Higher priority threads are scheduled to run before lower
each other to release resources. priority threads.
6) Thread Safety: Synchronization helps in making code Priorities can be set using the setPriority(int priority)
thread-safe, meaning it functions correctly even when method on a thread.
accessed by multiple threads simultaneously. However, thread scheduling is dependent on the JVM and
b) What is the utilization of file class? Explain different operating system, so priorities are suggestions, not
constructors associated with file class guarantees.
Definition: The File class in Java belongs to the [Link]
package. It is used to represent file and directory b) What are the reader and writer classes available in java
pathnames in an abstract manner. It can be used to create, Java provides Reader and Writer classes in the [Link]
delete, inspect, or check the existence of files and package for handling character-based input and output
directories. operations. These classes are designed to work with text
Utilization of File Class: data.
1) File Creation and Deletion: You can create new files or Reader Classes:
delete existing ones. Reader: Abstract class for reading character streams.
2) Checking File Properties: The File class allows checking if BufferedReader: Buffers input to provide efficient reading
a file exists, if it is readable, writable, executable, or a and methods like readLine().
directory. FileReader: Reads characters from a file.
3) Directory Operations: It supports operations like listing CharArrayReader: Reads characters from an array.
files in a directory, creating new directories, and checking StringReader: Reads characters from a string.
file paths. InputStreamReader: Converts byte streams to character
Path Management: streams (used with byte-based input).
Provides methods to get absolute path, canonical path, file Writer Classes:
name, parent directory, etc. Writer: Abstract class for writing character streams.
1) Constructors of File Class: File(String pathname) BufferedWriter: Buffers output for efficient writing.
Creates a new File instance by converting the given FileWriter: Writes characters to a file.
pathname string into an abstract pathname. CharArrayWriter: Writes characters to a character array.
Example: File file = new File("C:\\[Link]"); StringWriter: Writes characters to a string buffer.
File(String parent, String child) OutputStreamWriter: Converts character streams to byte
2) Creates a new File instance from a parent pathname streams (used with byte-based output).
string and a child pathname string. These classes help in reading and writing text efficiently,
Example: File file = new File("C:\\Documents", "[Link]"); support Unicode, and simplify file handling operations in
File(File parent, String child) Java.
Q5) a) Write a note on Adapter classes in Java. Q6). a) Write the similarities and dissimilarities between
Adapter classes in Java are abstract classes that provide swing and AWT.
default (empty) implementations for listener interfaces in Similarities:
the AWT event-handling system. 1) Both are used to create Graphical User Interfaces (GUIs)
They are useful when a listener interface contains multiple in Java.
methods, and the programmer wants to override only some 2) Both provide components like buttons, labels, text fields,
of them. etc.
Key Points: 3) Both follow event-driven programming.
Found in the [Link] package. 4) Both can be used in applets and applications.
Saves coding effort by preventing the need to implement all Feature AWT Swing
methods.
Common examples: GUI Type Heavyweight Lightweight
MouseAdapter – for MouseListener and Platform- Platform-
Platform
MouseMotionListener dependent (uses independent (pure
Dependency
KeyAdapter – for KeyListener OS resources) Java)
WindowAdapter – for WindowListener Pluggable look
FocusAdapter – for FocusListener Look & Feel Native OS look
and feel
Example: Faster, more
Speed & Slower and less
class MyWindow extends WindowAdapter { powerful
Flexibility flexible
public void windowClosing(WindowEvent e) { components
[Link]("Window is closing..."); More extensible
[Link](0);
Extensibility Less extensible
and customizable
}
}
Conclusion: b) Explain lifecycle of an applet with diagram.
Adapter classes simplify event handling by allowing us to An applet is a small Java program that runs in a browser or
override only the required methods. applet viewer. It has a defined life cycle managed by the
browser or Java runtime.
Applet Life Cycle Methods:
b) Illustrate different types of containers in AWT. init() : Called once when the applet is first [Link] to
Containers in AWT are classes that can hold and organize initialize resources (like UI components).
GUI components like buttons, labels, and text fields. There start() : Called after init() or when the applet becomes
are three main types of AWT containers: active. Used to start animations, threads, etc.
1. Window : A top-level container without borders or title paint(Graphics g) : Called whenever the applet needs to be
[Link] is rarely used directly. redrawn. Used to draw graphics or output text.
2. Frame : A fully functional window with title bar, stop() : Called when the applet is no longer visible (e.g.,
close/minimize buttons. Most common container used to user navigates away). Used to pause animations or threads.
create GUI applications. destroy() : Called when the applet is being removed from
Frame f = new Frame("My Frame"); [Link] to release resources.
3. Panel : A generic container for holding Diagram :
[Link] contain menu bars or be displayed on init() -> start() -> paint() -> stop() -> destroy()
its own. Must be added to another container (like Frame).
Panel p = new Panel(); Here's a simple example illustrating the applet life cycle
[Link](p); methods:
4. Dialog : A pop-up window used for short interactions import [Link];
(e.g., alerts, confirmations). Can be modal or non-modal. import [Link];
AWT containers help structure GUI elements and determine
public class LifeCycleApplet extends Applet {
how they are displayed and managed on screen. public void init() {
[Link]("Applet initialized"); }

public void start() {


[Link]("Applet started"); }
public void stop() {
[Link]("Applet stopped"); }

public void destroy() {


[Link]("Applet destroyed"); }
public void paint(Graphics g) {
[Link]("Applet Life Cycle", 20, 20); } }
Q7) a) Explain with diagram of all drivers in JDBC. ResultSet rs = [Link]("SELECT * FROM
JDBC (Java Database Connectivity) drivers are software students");
components that enable Java applications to interact with while([Link]()) {
databases. There are four types of JDBC drivers, each with [Link]([Link](1) + " " + [Link](2));
its own architecture and use case: }
Type 1: JDBC-ODBC Bridge Driver [Link]();
Converts JDBC calls into ODBC calls, which are then handled }
by the ODBC driver. }
Requires ODBC driver installation on the client machine. In this example, Connection, Statement, and ResultSet
Not recommended for production use; obsolete in modern interfaces are used to connect to the database, execute a
Java versions. query, and process results.
Type 2: Native-API Driver
Converts JDBC calls into database-specific native calls using
client-side libraries. Q8) a) Explain with example types of statements in JDBC.
Requires native library installation on the client machine. JDBC provides three main types of statements
Faster than Type 1 but platform-dependent. Statement: Used for executing simple SQL queries without
Type 3: Network Protocol Driver (Middleware Driver) parameters.
Pure Java driver that sends JDBC calls to a middleware Example:
server, which then communicates with the database. Statement stmt = [Link]();
Platform-independent and supports multiple databases. ResultSet rs = [Link]("SELECT * FROM
Middleware server adds flexibility and features like students");
connection pooling.
Type 4: Thin Driver (Native Protocol Driver) PreparedStatement: Used for executing precompiled SQL
Pure Java driver that converts JDBC calls directly into the queries with parameters, improving performance and
database’s native protocol. security.
No client-side libraries required; platform-independent. PreparedStatement pstmt = [Link]("SELECT
Best performance and widely used in modern applications. * FROM students WHERE id = ?");
Diagram: JDBC Driver Types [Link](1, 101);
text ResultSet rs2 = [Link]();
Type 1: Java App → JDBC API → JDBC-ODBC Bridge → ODBC
Driver → Database CallableStatement: Used for executing stored procedures
Type 2: Java App → JDBC API → Native-API Driver → Native in the database.
Library → Database CallableStatement cstmt = [Link]("{call
Type 3: Java App → JDBC API → Network Protocol Driver → getStudent(?)}");
Middleware Server → Database [Link](1, 101);
Type 4: Java App → JDBC API → Thin Driver → Database ResultSet rs3 = [Link]();

b) Explain the interfaces used in JDBC with example. b) Write a program create connection in JDBC.
JDBC provides several key interfaces for database import [Link].*;
operations: public class JDBCConnection {
DriverManager: Manages a list of database drivers and public static void main(String[] args) {
establishes a connection to the database. try {
Connection: Represents a session with a specific database, // Load and register JDBC driver
allowing SQL statement execution. [Link]("[Link]");
Statement: Used to execute static SQL queries. // Create connection object
PreparedStatement: Used for executing precompiled SQL Connection con = [Link](
queries with parameters. "jdbc:mysql://localhost:3306/mydatabase",
ResultSet: Represents the result set of a query and allows "username", "password");
data retrieval. [Link]("Connection Established
CallableStatement: Used to execute stored procedures. Successfully.");
Example: Using JDBC Interfaces // Close connection
import [Link].*; [Link]();
public class JdbcExample { } catch (Exception e) {
public static void main(String[] args) throws Exception { [Link]();
// Load driver (optional in modern Java) }
// [Link]("[Link]"); }
Connection con = [Link]( }
"jdbc:mysql://localhost:3306/mydb", "user",
"password");
Statement stmt = [Link]();
Q9) a) Explain various va Networking Terminologies.
1) IP Address (Internet Protocol Address): A unique Q10) a) What is Datagram? Write a note on Datagram
numerical label assigned to each device connected to a Server & Client.
network. It identifies the device’s location on the network Datagram: A datagram is a basic transfer unit associated
and allows communication between devices. with a connectionless packet-switched network, such as the
2) Port Number: A logical endpoint in network User Datagram Protocol (UDP).
communication that identifies a specific process or service It is a self-contained, independent packet of data that
on a device. For example, port 80 is typically used for HTTP carries enough information to be routed from the source to
traffic. the destination without relying on earlier exchanges.
3) Protocol: A set of rules and standards that define how Unlike TCP, datagrams do not guarantee delivery, order, or
data is transmitted and received over a network. Examples error-checking — making them faster but less reliable.
include TCP (Transmission Control Protocol), UDP (User Datagram Server:
Datagram Protocol), and HTTP (HyperText Transfer A Datagram Server listens on a specific port for incoming
Protocol). datagram packets.
4) Socket: An endpoint for communication between two It receives datagrams sent by clients, processes them, and
machines. A socket is identified by an IP address and a port can send a response back.
number, allowing data to be sent and received. Since UDP is connectionless, the server does not establish a
5) DNS (Domain Name System): A system that translates persistent connection with clients.
human-readable domain names (like [Link]) into Datagram Client:
IP addresses, making it easier to access websites. A Datagram Client sends datagram packets to the server’s
6) MAC Address (Media Access Control Address): A unique IP address and port.
identifier assigned to a network interface card (NIC) used The client creates a datagram packet with data and
for communication on the physical network segment. It destination address and sends it using a DatagramSocket.
operates at the data link layer.
7) LAN (Local Area Network): A network that connects
computers within a limited area such as a home, office, or b) Explain any three classes in [Link] package.
building. The [Link] package provides classes and interfaces for
implementing networking applications in Java. Below are
three important classes commonly used:
1. InetAddress Class
Represents an IP address (either IPv4 or IPv6).
b) What is URL? Explain various URL connection Class Used to get IP addresses or host names.
Methods. Common Methods:
URL (Uniform Resource Locator) is a reference (address) getByName(String host): Returns the IP address of the given
used to access resources on the internet. host.
It specifies the location of a resource as well as the protocol getHostName(): Returns the host name.
to access it. getHostAddress(): Returns the IP address as a string.
Example: [Link] Example: InetAddress address =
Various Methods of the URLConnection Class [Link]("[Link]");
URLConnection is a Java class used to represent a [Link]([Link]());
connection to a URL. It provides methods to interact with 2. Socket Class
the resource referred to by the URL. Used for client-side TCP communication.
connect() : Establishes a connection to the resource pointed It establishes a connection to a server over a specific port.
to by the URL. Common Methods:
getInputStream() : Returns an InputStream to read data getInputStream(): Reads data from the server.
from the URL resource. getOutputStream(): Sends data to the server.
getOutputStream(): Returns an OutputStream to send data close(): Closes the socket.
to the URL resource (used mainly for HTTP POST). Example: Socket socket = new Socket("localhost", 1234);
getContentLength() : Returns the length (in bytes) of the 3. ServerSocket Class
content received from the resource. Used for server-side TCP communication.
getContentType(): Returns the MIME type of the content It listens for incoming connection requests on a specified
(e.g., text/html, image/png). port.
getHeaderField(String name): Returns the value of a specific Common Methods:
HTTP header field from the resource. accept(): Waits for and accepts a connection from a client.
close(): Closes the server socket.
Example: ServerSocket server = new ServerSocket(1234);
Socket client = [Link]();
Q11). a) Write a note on Life cycle of Servlet Q12)a) Write a difference between Servlet & JSP.
The Servlet Life Cycle defines the process by which a servlet Servlet JSP
is created, initialized, serves requests, and is eventually
destroyed. The Servlet container (like Tomcat) manages this A text-based document
life cycle using three main methods of the A Java class that handles HTTP
combining HTML and
[Link] interface: requests and responses.
Java code.
1) init() Method : Called once when the servlet is first
loaded into memory. Used to perform initialization tasks
like opening database connections or loading configuration Pure Java code written using HTML with embedded
settings. classes and methods. Java code using JSP tags.
Signature: public void init(ServletConfig config) throws
ServletException Handling business logic and Presentation logic (user
2. service() Method : Called each time the servlet receives control flow. interface).
a request. Handles client requests and generates responses.
It is the core method where most logic (processing data, Code-heavy; separates HTML HTML-heavy; Java code is
calling business logic, sending responses) is written. using print statements. embedded in HTML.
Signature: public void service(ServletRequest req,
ServletResponse res) Requires writing a lot of code Easier for web designers;
3. destroy() Method : Called once when the servlet is being even for simple output. looks like an HTML page.
taken out of service e.g., during server shutdown. Used to
release resources like closing database connections, Directly compiled as a servlet Translated into a servlet,
stopping threads, etc. class. then compiled.
Signature: public void destroy()
Life Cycle Flow Summary:
Servlet is loaded → Servlet container loads the servlet class. b) Explain the architecture of Servlet
init() is called → Initializes the servlet. Servlet Architecture refers to the internal working and flow
service() is called for every request → Processes client of a servlet in a web application. A Servlet is a Java program
requests. that runs on a server and responds to client requests,
destroy() is called → Cleans up before servlet is removed usually over HTTP.
from memory. Servlets follow a request-response model and are managed
by a Servlet Container (like Apache Tomcat), which is part
b) Explain the architecture of JSP of a web server.
JSP (JavaServer Pages) is a server-side technology that Key Components of Servlet Architecture:
allows the creation of dynamic web pages using HTML and Client (Web Browser): Sends an HTTP request
Java code. The architecture of JSP defines how a JSP file is Web Server (Servlet Container): Receives the request from
processed and executed by the server. the client and forwards it to the appropriate servlet.
Key Components of JSP Architecture: Servlet Class: The core Java class that processes the
Client (Web Browser): Sends an HTTP request for a .jsp file request. Implemented by extending HttpServlet and
to the web server. overriding methods like doGet() or doPost().
Web Server / JSP Engine (Servlet Container): The JSP engine Servlet Request & Response Objects: HttpServletRequest
is part of a web server (like Apache Tomcat) that handles carries information from the client (headers, parameters).
JSP files. Servlet Life Cycle Methods:
Translation Phase: The JSP file is translated into a Java init() → Called once when the servlet is loaded.
servlet by the JSP engine. This servlet contains Java code service() → Called for each client request.
equivalent to the content and logic written in the JSP file. destroy() → Called when the servlet is removed from
Compilation Phase: The translated servlet is compiled into a memory.
.class file (bytecode) by the Java compiler. Architecture Flow (Step-by-Step):
Class Loading and Initialization: The servlet class is loaded Client sends request → via browser
into memory by the servlet container and initialized using Web server receives it and passes it to the Servlet
the init() method. Container.
Diagram :Client (Browser) Servlet Container checks if the servlet is already loaded:
v If not loaded: it loads the class, creates an instance, and
HTTP Request --> JSP Engine (Web Server) calls init().
| The container then calls the service() method, which
Translate JSP to Servlet -- Compile Servlet to Class internally calls:
| doGet() for GET requests or doPost() for POST requests.
Load and Execute Servlet Servlet processes the request, generates a response using
| HttpServletResponse.
Generate HTML Response The response is sent back to the client (e.g., HTML content).
| On server shutdown, destroy() is called to clean up
Client (Displays Output) resources.

You might also like