0% found this document useful (0 votes)
16 views90 pages

Java Notes

The document covers advanced Java programming concepts, including Java features, event handling, Java architecture, and threading. It details the different editions of Java, types of applications, and the significance of the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). Additionally, it explains event handling mechanisms and threading concepts in Java, emphasizing the importance of multi-threading for efficient program execution.

Uploaded by

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

Java Notes

The document covers advanced Java programming concepts, including Java features, event handling, Java architecture, and threading. It details the different editions of Java, types of applications, and the significance of the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). Additionally, it explains event handling mechanisms and threading concepts in Java, emphasizing the importance of multi-threading for efficient program execution.

Uploaded by

lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 90

ADVANCED JAVA PROGRAMMING

UNIT-1

1.1 Java - Features and Applications


1.2 Event and Listener (Event Handling)
1.3 Java Architecture (JVM, JRE, JDK)
1.4 Threading concepts
1.5 Networking features
1.6 Multimedia techniques

1.1 JAVA - Features and Applications


Java
Java is a high-level, general-purpose, object-oriented, and secure programming
language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally
known as OAK. In 1995, Sun Microsystem changed the name to Java. In 2009, Sun
Microsystem was taken over by Oracle Corporation.
Java was developed by James Gosling at Sun Microsystems and it was released in May
1995 as a core component of Sun Microsystems' Java platform.
EDITIONS OF JAVA
Each edition of Java has different capabilities. There are three editions of Java:
➔ Java Standard Edition (JSE): It is used to create programs for a desktop
computer.
➔ Java Enterprise Edition (JEE): It is used to create large programs that run on the
server and manage heavy traffic and complex transactions.
➔ Java Micro Edition (JME): It is used to develop applications for small devices
such as set-top boxes, phones, and appliances.
TYPES OF JAVA APPLICATIONS
There are four types of Java applications that can be created using Java programming:
➔ Standalone Applications: Java standalone applications use GUI components
such as AWT, Swing, and Java. These components contain buttons, list, menu,
scroll panel, etc.
➔ Enterprise Applications: An application which is distributed in nature is called
enterprise applications.
➔ Web Applications: An application that runs on the server is called web
applications. We use JSP, Servlet, spring, and Hibernate technologies for
1
creating web applications.
➔ Mobile Applications: Java ME is a cross-platform to develop mobile applications
which run across smartphones. Java is a platform for App Development in
Android.
JAVA PLATFORM
Java Platform is a collection of programs. It helps to develop and run a program written
in the Java programming language. Java Platform includes an execution engine, a
compiler and set of libraries. Java is a platform-independent language.
FEATURES OF JAVA
Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used in
Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has some
data and behavior. A program must have at least one class and object.
Robust: Java makes an effort to check errors at run time and compile time. It uses a
strong memory management system called garbage collector. Exception handling and
garbage collection features make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and
programs run in the virtual machine. Java contains a security manager that defines the
access of Java classes.
Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.
Portable: Java Byte code can be carried to any platform. No implementation-
dependent features. Everything related to storage is predefined, for example, the size
of primitive data types.
High Performance: Java is an interpreted language. Java enables high performance
with the use of the Just-In-Time compiler.
Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the
internet. EJB and RMI are used to create a distributed system.
Multi-threaded: Java also supports multi-threading. It means to handle more than one
job at a time.

2
Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Applications
There are many devices where Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
_____________________________________________________________________
1.2 EVENT AND LISTENER (JAVA EVENT HANDLING)
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
● Foreground Events

● Background Events

3
1. Foreground Events
Foreground events are the events that require user interaction to generate.
Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background
events. Examples are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occurs. To handle the events, Java follows the Delegation Event model.
Delegation Event Model

Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax: addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

4
Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred
ActionEvent ActionListener
like a button click or selecting an item
from the menu-item list.

The adjustment event is emitted by


AdjustmentEvent AdjustmentListener
an Adjustable object like Scrollbar.

Indicates that a component moved,


ComponentEvent ComponentListener the size changed or changed its
visibility.

When a component is added to a


ContainerEvent ContainerListener
container (or) removed from it

Focus-related events which include


FocusEvent FocusListener
focus, focusin, focusout, and blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on the
keyboard.

MouseListener & The events that occur due to the user


MouseEvent
MouseMotionListener interaction with the mouse.

MouseWheelEvent MouseWheelListener An event that specifies that the


mouse wheel was rotated in a

5
component.

An event that occurs when an object’s


TextEvent TextListener
text changes.

Indicates whether a window has


WindowEvent WindowListener
changed its status or not.

Different interfaces consist of different methods which are specified below.

Listener Interface Methods

ActionListener actionPerformed()

AdjustmentListener adjustmentValueChanged()

componentResized(), componentShown()
ComponentListener
componentMoved(), componentHidden()

ContainerListener componentAdded(), componentRemoved()

FocusListener focusGained(), focusLost()

ItemListener itemStateChanged()

KeyListener keyTyped(), keyPressed(), keyReleased()

mousePressed(), mouseClicked(), mouseEntered()


MouseListener
mouseExited(), mouseReleased()

MouseMotionListener mouseMoved(), mouseDragged()

MouseWheelListener mouseWheelMoved()

6
TextListener textChanged()

windowActivated(), windowDeactivated()
WindowListener windowOpened(), windowClosed()
windowClosing(), windowIconified()

Steps in Event Handling


1. User Interaction with a component is required to generate an event.

2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered
listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class

2. Other Class

3. Anonymous Class
Event Handling Within Class
In this approach, the event handling code is written within the same class that contains
the event source. The class implements the appropriate listener interface & provides the
implementation for the corresponding event-handling method.

7
// Event handling within the class
import java.awt.*;
import java.awt.event.*;
class GFGTop extends Frame implements ActionListener {
TextField textField;
GFGTop()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(this);
add(textField);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
textField.setText("GFG!");
}
public static void main(String[] args)
{
new GFGTop();
}
}

8
Output

After Clicking, the text field value is set to GFG!


Event Handling by Other Class
In this approach, the event handling code is written in a separate class from the event
source. The separate class implements the appropriate listener interface & provides
the implementation for the event handling method. An instance of this class is then
registered as a listener on the event source.

// Event handling by other class


import java.awt.*;
import java.awt.event.*;
class GFG2 extends Frame {
TextField textField;
GFG2()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
Other other = new Other(this);
button.addActionListener(other);
add(textField);
add(button);
setVisible(true);
}

public static void main(String[] args)

9
{
new GFG2();
}
}
import java.awt.event.*;
class Other implements ActionListener {
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
public void actionPerformed(ActionEvent e)
{
gfgObj.textField.setText("Using Different Classes");
}
}

Output:

Handling event from different class


Event Handling By Anonymous Class
In this approach, the event handling code is written using an anonymous inner class. An
anonymous class is a local class without a name that is defined & instantiated in a single
statement. It allows you to create a one-time implementation of a listener interface
without the need for a separate class.

10
// Event handling by Anonymous Class
import java.awt.*;
import java.awt.event.*;
class GFG3 extends Frame {
TextField textField;
GFG3()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
textField.setText("Anonymous");
}
});
add(textField);
add(button);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
new GFG3();
}
}

11
Output

Handling anonymously
____________________________________________________________________
1.3 Java Architecture (JVM, JRE, JDK)
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the
process of interpretation and compilation. It defines all the processes involved in
creating a Java program. Java Architecture explains each and every step of how a
program is compiled and executed.
Java Architecture can be explained by using the following steps:

○ There is a process of compilation and interpretation in Java.


○ Java compiler converts the Java code into bytecode.
○ After that, the JVM converts the byte code into machine code.
○ The machine code is then executed by the machine.

The following figure represents the Java Architecture in which each step is elaborate
graphically.

12
Components of Java Architecture
The Java architecture includes the three main components:

○ Java Virtual Machine (JVM)


○ Java Runtime Environment (JRE)
○ Java Development Kit (JDK)

Java Virtual Machine


The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The
feature states that we can write our code once and use it anywhere on any operating
system. Our Java program can run any of the platforms only because of the Java Virtual
Machine. It is a Java platform component that gives us an environment to execute java
programs. JVM's main task is to convert byte code into machine code.
JVM, first of all, loads the code into memory and verifies it. After that, it executes the
code and provides a runtime environment. Java Virtual Machine (JVM) has its own
architecture, which is given below:
JVM Architecture
JVM is an abstract machine that provides the environment in which Java bytecode is
executed. The falling figure represents the architecture of the JVM.

ClassLoader: ClassLoader is a subsystem used to load class files. ClassLoader first loads
the Java code whenever we run it.
Class Method Area: In the memory, there is an area where the class data is stored
during the code's execution. Class method area holds the information of static
variables, static methods, static blocks, and instance methods.
Heap: The heap area is a part of the JVM memory and is created when the JVM starts
up. Its size cannot be static because it increases or decreases during the application
runs.
13
Stack: It is also referred to as thread stack. It is created for a single execution thread.
The thread uses this area to store the elements like the partial result, local variable,
data used for calling method and returns etc.
Native Stack: It contains the information of all the native methods used in our
application.
Execution Engine: It is the central part of the JVM. Its main task is to execute the byte
code and execute the Java classes. The execution engine has three main components
used for executing Java classes.

○ Interpreter: It converts the byte code into native code and executes. It
sequentially executes the code. The interpreter interprets continuously and
even the same method multiple times. This reduces the performance of the
system, and to solve this, the JIT compiler is introduced.
○ JIT Compiler: JIT compiler is introduced to remove the drawback of the
interpreter. It increases the speed of execution and improves performance.
○ Garbage Collector: The garbage collector is used to manage the memory, and it
is a program written in Java. It works in two phases, i.e., Mark and Sweep. Mark
is an area where the garbage collector identifies the used and unused chunks of
memory. The Sweep removes the identified object from the Mark

Java Native Interface


Java Native Interface works as a mediator between Java method calls and native
libraries.
Java Runtime Environment
It provides an environment in which Java programs are executed. JRE takes our Java
code, integrates it with the required libraries, and then starts the JVM to execute it. To
learn more about the Java Runtime Environment, click here.
Java Development Kit
It is a software development environment used in the development of Java applications
and applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and
several development tools in it. To learn more about the Java Development Kit, click
here.
These are three main components of Java Architecture. The execution of a program is
done with all these three components.
_____________________________________________________________________

14
1.4 Thread Concept in Java
A Thread is a very light-weighted process, or the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept
in Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a
process is independent.

Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. When
multiple threads are executed in parallel at the same time, this process is known as
Multithreading.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run) : A thread is in New when it gets CPU time.


2) Running : A thread is in a Running state when it is under execution.
3) Suspended : A thread is in the Suspended state when it is temporarily inactive or
under execution.

15
4) Blocked : A thread is in the Blocked state when it is waiting for resources.
5) Terminated : A thread comes in a terminated state when at any given time, it halts
its execution immediately.
Creating Thread
A thread is created either by
● Creating or Implementing" the Runnable Interface (or)
● Extending the Thread class.
These are the only two ways through which we can create a thread.
Thread Class
A Thread class has several methods and constructors which allow us to perform various
operations on a thread. The Thread class extends the Object class. The Object class
implements the Runnable interface. The thread class has the following constructors
that are used to perform various operations.

○ Thread()
○ Thread(Runnable, String name)
○ Thread(Runnable target)
○ Thread(ThreadGroup group, Runnable target, String name)
○ Thread(ThreadGroup group, Runnable target)
○ Thread(ThreadGroup group, String name)
○ Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() Method)


The Runnable interface is required to be implemented by that class whose instances
are intended to be executed by a thread. The runnable interface gives us the run()
method to perform an action for the thread.
start() Method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new call stack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.
Creating thread by extending Thread class
Let's take an example to understand how we can create a Java thread by extending the
Thread class:
class ThreadExample2 extends Thread {
String name;

16
ThreadExample2(String name) {
this.name = name;
System.out.println("A New thread: " + this + " is created\n");
start(); // Start the thread
}

public void run() {


try {
for (int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}

public static void main(String[] args) {


new ThreadExample2("1st");
new ThreadExample2("2nd");
new ThreadExample2("3rd");

try {
Thread.sleep(8000);
} catch (InterruptedException exception) {
System.out.println("Interruption occurs in Main Thread");
}
System.out.println("We are exiting from Main Thread");
}
}

Output:

17
Creating thread by implementing the runnable interface
class NewThread implements Runnable {
String name;
Thread thread;
NewThread (String name)
{ this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread + "is created\n" );
thread.start();
}
public void run()
{
try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{ System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException exception) {
System.out.println("Interruption occurs in Main Thread");
}

18
System.out.println("We are exiting from Main Thread");
}
}
Output:

In the above example, we perform the Multithreading by implementing the runnable


interface.
Thread Synchronization
In multithreaded environments, it's essential to synchronize access to shared resources
to prevent data corruption and ensure consistency. Java provides synchronization
mechanisms such as the synchronized keyword and the java.util.concurrent package to
facilitate thread synchronization.
The synchronized keyword can be used to create synchronized methods or blocks
class Counter
{
private int count = 0;
public synchronized void increment()
{ count++;
}
}
The increment() method is marked as synchronized, which ensures thread safety. This
means that if multiple threads are calling increment(), only one thread can execute it at
a time. This prevents race conditions where multiple threads might try to increment

19
count simultaneously, leading to incorrect results.
Thread Pools
Creating and managing threads individually can be inefficient, especially in applications
with a large number of tasks. Thread pools provide a solution by reusing existing
threads to execute multiple tasks, thereby reducing the overhead associated with
thread creation and destruction.
Java's ExecutorService and ThreadPoolExecutor classes facilitate the creation and
management of thread pools:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new MyRunnable());
Thread Priorities
Java allows developers to assign priorities to threads, influencing the scheduling
decisions made by the JVM's thread scheduler. Threads with higher priorities are given
preference by the scheduler, but thread priorities are only hints and not strict
guarantees of execution order.
Thread thread1 = new Thread();
thread1.setPriority(Thread.MAX_PRIORITY);
Thread thread2 = new Thread();
thread2.setPriority(Thread.MIN_PRIORITY);
_____________________________________________________________________
1.5 Java Networking
Java networking refers to writing programs that execute across multiple devices n
which the devices are all connected to each other using a network.
Advantages of Java Networking
Creating server-client applications
Implementing networking protocols
Implement socket programming
Creating web services
Package Used in Networking
The java.net package of the J2SE APIs contains a collection of classes and interfaces
that provide the low-level communication details, allowing you to write programs that
focus on solving the problem at hand.
The java.net package provides support for the two common network protocols
● TCP − TCP stands for Transmission Control Protocol, which allows for reliable

20
communication between two applications. TCP is typically used over the
Internet Protocol, which is referred to as TCP/IP.
● UDP − UDP stands for User Datagram Protocol, a connectionless protocol that
allows for packets of data to be transmitted between applications.
Socket Programming in Java Networking
Sockets provide the communication mechanism between two computers using TCP. A
client program creates a socket on its end of the communication and attempts to
connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and
reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class
provides a mechanism for the server program to listen for clients and establish
connections with them.
The following steps occur when establishing a TCP connection between two computers
using sockets −
● The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
● The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
● After the server is waiting, a client instantiates a Socket object, specifying the
server name and the port number to connect to.
● The constructor of the Socket class attempts to connect the client to the
specified server and the port number. If communication is established, the
client now has a Socket object capable of communicating with the server.
● On the server side, the accept() method returns a reference to a new socket on
the server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams.
Each socket has both an OutputStream and an InputStream. The client's OutputStream
is connected to the server's InputStream, and the client's InputStream is connected to
the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams
at the same time. Following are the useful classes providing a complete set of methods
to implement sockets.

21
Example of Java Networking

Implementing Socket Client in Java


The following GreetingClient is a client program that connects to a server by
using a socket and sends a greeting, and then waits for a response.
Example: Socket Client
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " +
client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

22
Implementing Socket Server in Java
The following GreetingServer program is an example of a server application that uses
the Socket class to listen for clients on a port number specified by a command-line
argument −
Example: Socket Server
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();
}
catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;

23
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066


Waiting for client on port 6066…
Check the client program as follows −
Output
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
_____________________________________________________________________
1.6 Multimedia Techniques

Multimedia is an engaging kind of media that offers a variety of effective ways to


convey information to users. Users can interact with digital information through it. It
serves as a communication tool. Education, training, reference materials, corporate
presentations, marketing, and documentary are a few industries that heavily utilize
multimedia.
Multimedia, by definition, is the use of text, audio, video, graphics, and animation to
convey information in an engaging and dynamic way.

24
COMPONENTS OF MULTIMEDIA
The following are typical multimedia elements:
1) Text - Text appears in all multimedia projects to some extent. The text may be
presented in a variety of font styles and sizes.
2) Graphics - Graphics can be of two different types:
Bitmap - Bitmap images are authentic pictures that can be taken using
tools like digital cameras or scanners. Bitmap pictures are often not
modifiable. Memory use for bitmap pictures is high.
Vector Graphics - Computers can draw vector graphics because they just
need a little amount of memory. These images can be changed.
3) Animation - A static picture can be animated to appear to be in motion. A
continuous succession of static images shown in order is all that makes up an
animation.
4) Audio - Speech, music, and sound effects could all be necessary for a multimedia
application. They are referred to as the audio or sound component of multimedia.
Speaking is a fantastic educational tool.
5) Video - The term "video" describes a moving image that is supported by sound, such
as a television image. A multimedia application's video component conveys a lot of
information quickly. For displaying real-world items in multimedia applications,
digital video is helpful.

APPLICATIONS OF MULTIMEDIA
The typical areas where multimedia is applied are listed below.
1) For entertainment purposes - Multimedia marketing may significantly improve
the promotion of new items. Both advertising and marketing staff had their
doors opened by the economical communication boost provided by multimedia.
2) For education purposes - There are currently a lot of educational computer
games accessible. There are many more multimedia products on the market
that provide children with a wealth of in-depth knowledge and playing options.
3) For business purposes - There are several commercial uses for multimedia.
Today's team members can work remotely and for a variety of businesses. The
following facilities should be supported by the multimedia network:
Office needs

25
Records management
Employee training
Electronic mail
Voice mail
4) For marketing purposes - Multimedia marketing may significantly improve the
promotion of new items. Both advertising and promotion staff had their doors
opened by the economical communication boost provided by multimedia.
5) For banking purposes - Another public setting where multimedia is being used
more and more recently is banks. People visit banks to open savings and current
accounts, make deposits and withdrawals, learn about the bank's various
financial plans, apply for loans, and other things. Each bank wants to notify its
consumers with a wealth of information. nline and internet banking have grown
in popularity recently. These heavily rely on multimedia.
Media Techniques
There are several media techniques that can be used in Java programming:
Image Manipulation:
Java provides various libraries and classes for loading, manipulating, and saving images.
For example, the javax.imageio package allows developers to read and write images in
different formats, while java.awt.image package offers classes for performing
operations like scaling, cropping, and filtering on images.
Audio Playback:
Java Sound API enables developers to play audio files of different formats. It provides
classes like Clip and AudioInputStream to load and manipulate audio data. JavaFX also
provides media classes for playing audio files, along with advanced features such as
playback controls and volume management.
Video Playback:
JavaFX has built-in media capabilities, which allow developers to play video files in
different formats. The javafx.scene.media package provides classes like MediaPlayer
and MediaView for handling video playback. By using these classes, you can control
video playback, handle events, and even apply visual effects to the video.
Animation:
Java provides several libraries and frameworks that support animation. For example,
JavaFX provides a powerful animation framework with classes like Animation, Timeline,
and KeyFrame. These classes allow you to create smooth animations by specifying

26
time-based actions and transitions.

3D Graphics:
Java 3D API provides support for creating and manipulating 3D graphics in Java. With
Java 3D, you can create complex 3D objects, apply textures and lighting effects, and
even perform animations in three-dimensional space.
Web Content Integration:
JavaFX provides a WebView class that enables developers to embed web content in
Java applications. This allows you to integrate media elements like images, audio, and
video from web sources into your Java application.
Java Program to Play an Audio File
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class AudioPlayer {
public static void main(String[] args) {
File audioFile = new File("path_to_your_audio_file.wav");
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
Clip audioClip = AudioSystem.getClip();
audioClip.open(audioStream);
audioClip.start();
System.out.println("Playing audio...");
Thread.sleep(audioClip.getMicrosecondLength() / 1000);
audioClip.close();
System.out.println("Audio playback finished.");
}
catch (UnsupportedAudioFileException | IOException | LineUnavailableException |
InterruptedException e) {
e.printStackTrace();
}
}
}
_________________________________________________________________

27
28
S.
N Question a) Option b) Option c) Option d) Option
o
What does Java Desktop Mobile
Server Web
1 ME primarily application application
applications applications
develop? s s
Which of the
Desktop
applications Mobile Server Web
2 application
run on the applications applications applications
s
server?
Which feature
of Java allows Multithreadi Interoperabilit
3 Portability Object-oriented
it to run on any ng y
platform?
What type of
event requires Foreground Background
4 Action event Mouse event
user event event
interaction?
What type of
event does not Foregroun Background
5 Action event Mouse event
require user d event event
interaction?
What does
A keypress
KEYEVENT A mouse A background A change in
6 on the
represent in click task text
keyboard
Java?
Java Java Java
What does JDK
7 Developme Debugging Java Data Kit Documentatio
stand for?
nt Kit Kit n Kit
What does Write
Write Once Write Only Run Write Once
8 WORA stand Once Run
Run Around Anywhere Read Always
for in Java? Anywhere
What is the
function of a To compile To load To manage
9 To execute code
Class Loader in Java code class files memory
Java?
Which of the
A heavy- A light-
1 following best A system
weighted weighted A Java class
0 describes a event
process process
thread in Java?

29
UNIT-2

2.1 RMI (REMOTE METHOD INVOCATION)


2.2 DISTRIBUTED APPLICATION ARCHITECTURE
2.3 DEFINING REMOTE OBJECTS
2.4 REMOTE OBJECT ACTIVATION
2.5 SERIALIZATION AND DESERIALIZATION IN JAVA

2.1 RMI (Remote Method Invocation)

Remote Method Invocation (RMI) is an API that allows an object to invoke a method on
an object that exists in another address space, which could be on the same machine or
on a remote machine. Through RMI, an object running in a JVM present on a computer
(Client-side) can invoke methods on an object present in another JVM (Server-side).
RMI creates a public remote server object that enables client and server-side
communications through simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and
sends this information to the server.
The block consists of
● An identifier of the remote object to be used
● Method name which is to be invoked
● Parameters to the remote JVM
Skeleton Object: The skeleton object passes the request from the stub object to the
remote object. It performs the following tasks
● It calls the desired method on the real object present on the server.
● It forwards the parameters received from the stub object to the method.
Working of RMI
The communication between client and server is handled by using two intermediate
objects: Stub object (on client side) and Skeleton object (on server-side) as also can be
depicted from below media as follows:
These are the steps to be followed sequentially to implement Interface as defined
below as follows:
1. Defining a remote interface
2. Implementing the remote interface

30
3. Creating Stub and Skeleton objects from the implementation class using rmic
(RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
Step 1: Defining the remote interface
The first thing to do is to create an interface that will provide the description of the
methods that can be invoked by remote clients. This interface should extend the
Remote interface and the method prototype within the interface should throw the
RemoteException.
Example:
// Creating a Search interface
import java.rmi.*;
public interface Search extends Remote
{
// Declaring the method prototype
public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote
interface, the class should extend to UnicastRemoteObject class of java.rmi package.
Also, a default constructor needs to be created to throw the java.rmi.RemoteException
from its parent constructor in class.
// Java program to implement the Search interface
import java.rmi.*;
import java.rmi.server.*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();

31
}
// Implementation of the query interface
public String query(String search)
throws RemoteException
{
String result;
if (search.equals("Reflection in Java"))
result = "Found";
else
result = "Not Found";
return result;
}
}
Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton
objects. Its prototype is rmic classname. For above program the following command
need to be executed at the command prompt
rmic SearchQuery.
Step 4: Start the rmiregistry
Start the registry service by issuing the following command at the command prompt
start rmiregistry
Step 5: Create and execute the server application program
The next step is to create the server application program and execute it on a separate
command prompt.
The server program uses createRegistry method of LocateRegistry class to create
rmiregistry within the server JVM with the port number passed as an argument.
The rebind method of Naming class is used to bind the remote object to the new name.
// Java program for server application
import java.rmi.*;
import java.rmi.registry.*;
public class SearchServer
{
public static void main(String args[])
{

32
try
{
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();

// rmiregistry within the server JVM with


// port number 1900
LocateRegistry.createRegistry(1900);
// Binds the remote object by the name
// geeksforgeeks
Naming.rebind("rmi://localhost:1900"+
"/geeksforgeeks",obj);
}
catch(Exception ae)
{
System.out.println(ae);
}
}
}
Step 6: Create and execute the client application program
The last step is to create the client application program and execute it on a separate
command prompt . The lookup method of the Naming class is used to get the reference
of the Stub object.
// Java program for client application
import java.rmi.*;
public class ClientRequest
{
public static void main(String args[])
{
String answer,value="Reflection in Java";
try
{
// lookup method to find reference of remote object
Search access =
33
(Search)Naming.lookup("rmi://localhost:1900"+
"/geeksforgeeks");
answer = access.query(value);
System.out.println("Article on " + value +
" " + answer+" at GeeksforGeeks");
}
catch(Exception ae)
{
System.out.println(ae);
}
}
}
The above client and server program is executed on the same machine so localhost is
used. In order to access the remote object from another machine, localhost is to be
replaced with the IP address where the remote object is present.
Save the files respectively as per class name as Search.java , SearchQuery.java ,
SearchServer.java & ClientRequest.java

RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the
distributed applications in java.
Stub and Skeleton objects are used for communication between the client and server-
side.
_____________________________________________________________________
2.2 DISTRIBUTED APPLICATION ARCHITECTURE
Architecture styles in distributed systems define how components interact and are
structured to achieve scalability, reliability, and efficiency.
What are Distributed Systems?
Distributed Systems are networks of independent computers that work together to
present themselves as a unified system. These systems share resources and coordinate
tasks across multiple nodes, allowing them to work collectively to achieve common
goals.
Architecture Styles in Distributed Systems
To show different arrangement styles among computers, Architecture styles are
proposed.

34
1. Layered Architecture in Distributed Systems
● Layered Architecture in distributed systems organizes the system into
hierarchical layers, each with specific functions and responsibilities.
● This design pattern helps manage complexity and promotes separation of
concerns.
● This separation helps in managing and scaling the system more effectively.
Examples of Layered Architecture in Distributed System
Web Applications: A common example includes web applications with a presentation
layer (user interface), application layer (business logic), and data access layer (database
interactions).
Enterprise Systems: Large enterprise systems often use layered architecture to
separate user interfaces, business logic, and data management.
2. Peer-to-Peer (P2P) Architecture in Distributed Systems
● Peer-to-Peer (P2P) Architecture is a decentralized network design where each
node, or “peer,” acts as both a client and a server.
● In a P2P architecture, all nodes (peers) are equal participants in the network,
each capable of initiating and receiving requests.
● Peers collaborate to share resources, such as files or computational power,
without relying on a central server.
Examples of Peer-to-Peer (P2P) Architecture in Distributed Systems
File Sharing Networks: Systems like BitTorrent allow users to share and download files
from multiple peers, with each peer contributing to the upload and download
processes.
Decentralized Applications (DApps): Applications that run on decentralized networks,
leveraging P2P architecture for tasks like data storage and computation.
3. Data-Centric Architecture in Distributed Systems
● Data-Centric Architecture is an architectural style that focuses on the central
management and utilization of data.
● In this approach, data is treated as a critical asset, and the system is designed
around data management, storage, and retrieval processes.
● This system is used to support efficient data management and manipulation.
Examples of Data-Centric Architecture in Distributed Systems
Relational Databases: Systems like MySQL, PostgreSQL, and Oracle use Data-Centric
Architecture to manage and store structured data efficiently, providing consistent

35
access and integration across applications.
Data Warehouses: Platforms such as Amazon Redshift and Google BigQuery are
designed to centralize and analyze large volumes of data from various sources,
enabling complex queries and data analysis.
4. Service-Oriented Architecture (SOA) in Distributed Systems
● Service-Oriented Architecture (SOA) is a design paradigm in distributed systems
where software components, known as “services,” are provided and consumed
across a network.
● Each service is a discrete unit that performs a specific business function and
communicates with other services through standardized protocols.
Examples of Service-Oriented Architecture (SOA) in Distributed Systems
Enterprise Systems: SOA is commonly used to integrate various enterprise applications
such as ERP, CRM, and HR systems, allowing them to work together seamlessly.
Web Services: Many modern web applications leverage SOA principles to interact with
external services via APIs, enabling functionalities such as payment processing, data
retrieval, and authentication.
5. Event-Based Architecture in Distributed Systems
● Event-Driven Architecture (EDA) is an architectural pattern where the flow of
data and control in a system is driven by events.
● Components in an EDA system communicate by producing and consuming
events, which represent state changes or actions within the system.
Examples of Event-Based Architecture in Distributed Systems
Real-Time Analytics: Systems like stock trading platforms use EDA to process and
respond to market events in real time.
IoT Systems: Internet of Things (IoT) applications use EDA to manage and respond to
data from various sensors and devices.
Fraud Detection: Financial institutions use EDA to detect and respond to suspicious
activities or anomalies in real time.
6. Microservices Architecture for Distributed Systems
● Microservices Architecture is a design pattern where an application is composed
of small, independent services that each perform a specific function.
● These services are loosely coupled and interact with each other through
lightweight communication protocols, often over HTTP or messaging queues.
Examples of Microservices Architecture for Distributed Systems

36
E-Commerce Platforms: Platforms like Amazon use microservices to handle different
aspects of their operations, such as user authentication, payment processing, and order
management.
Financial Services: Banks and financial institutions use microservices to manage various
functions, including transaction processing, customer management, and compliance.

7. Client Server Architecture in Distributed Systems


● Client-Server Architecture is a foundational model in distributed systems where
the system is divided into two main components: clients and servers.
● In Client-Server Architecture, clients request services or resources, while servers
provide those services or resources.
● The client initiates a request to the server, which processes the request and
returns the appropriate response.
Examples of Client Server Architecture in Distributed Systems
Web Applications: In a typical web application, web browsers (clients) request web
pages or data from web servers.
Email Systems: Email clients connect to email servers to send, receive, and manage
email messages.
_____________________________________________________________________
2.3 DEFINING REMOTE OBJECTS
Introduction to RMI
● Remote Method Invocation (RMI) is a Java API that allows invoking methods on
an object located in a different Java Virtual Machine (JVM).
● It enables seamless communication between distributed applications.
● Key features:
○ Location Transparency: Clients interact with remote objects as if they
are local.
○ Object Serialization: Transfers objects over the network.
○ Security: RMI uses Java's security manager for access control.
Key Components of RMI
1. Remote Interface: Declares the methods that can be called remotely.
2. Remote Object: Implements the remote interface.
3. RMI Registry: Acts as a naming service for binding and looking up remote
objects.

37
4. Stub and Skeleton:
○ Stub: Proxy on the client-side.
○ Skeleton (pre-Java 5): Dispatches calls on the server-side (replaced by
reflection in newer versions).
Steps to Define a Remote RMI Object
Step 1: Define the Remote Interface
● A remote interface extends the java.rmi.Remote interface.
● All methods must throw java.rmi.RemoteException.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote {
// Method to add two numbers
int add(int a, int b) throws RemoteException;
// Method to subtract two numbers
int subtract(int a, int b) throws RemoteException;
}
Step 2: Implement the Remote Interface
● The implementation class must extend java.rmi.server.UnicastRemoteObject.
● Implement all methods defined in the remote interface.
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CalculatorImpl extends UnicastRemoteObject implements
Calculator {
// Constructor
protected CalculatorImpl() throws RemoteException {
super();
}
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;

38
}
}
Step 3: Create and Register the Remote Object
● Use the java.rmi.registry.LocateRegistry class to create and bind the object to
the RMI Registry.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
// Create remote object
Calculator calculator = new CalculatorImpl();
// Bind the remote object to the RMI registry
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("CalculatorService", calculator);

System.out.println("Server is ready.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Testing the RMI Object
Client Code
● Lookup the remote object in the RMI registry and invoke its methods.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
// Lookup the registry for the remote object
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Calculator calculator = (Calculator) registry.lookup("CalculatorService");
// Invoke methods on the remote object

39
System.out.println("Addition:"+ calculator.add(10, 5));
System.out.println("Subtraction:"+ calculator.subtract(10, 5));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Compiling and Running RMI Applications
1. Compile Classes: Use javac to compile all classes.
2. Generate Stubs (Pre-Java 5): Use the rmic tool to generate stub classes.
3. Start RMI Registry: Run rmiregistry from the command line.
4. Run Server: Start the server application.
5. Run Client: Execute the client application.
Advantages of RMI
● Easy to use and integrates seamlessly with Java.
● Abstracts underlying complexities of network communication.
● Supports object-oriented distributed programming.
_____________________________________________________________________
2.4 REMOTE OBJECT ACTIVATION
Introduction
● Remote Object Activation is a feature in Java's RMI that enables creating
remote objects on demand.
● It allows an object to be activated only when a client requests it, reducing
resource usage compared to keeping objects always in memory.
● Activation provides scalability by managing object lifecycle dynamically.
Key Concepts
1. Persistent Naming:
○ Activated objects are registered with a persistent naming service to
enable lookup even after they are deactivated.
2. Object State:
○ Objects retain their state across activations, allowing seamless
interaction for clients.
3. Activation Daemon:
○ The rmid daemon manages the activation of objects when they are

40
needed.
Components of Remote Object Activation
1. Activation Group:
○ A container for activated objects.
○ Manages the shared resources for objects in the same group.
○ Implements java.rmi.activation.ActivationGroup.
2. Activation Descriptor:
○ Provides the information needed to activate an object, such as its class
name, location, and initialization parameters.
○ Implements java.rmi.activation.ActivationDesc.
3. Activation System:
○ A central registry to manage activation groups and descriptors.
○ Implemented by the java.rmi.activation.ActivationSystem interface.
Steps to Implement Remote Object Activation
Step 1: Define the Remote Interface
● Similar to a regular RMI object, the remote interface defines the methods
accessible to clients.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyService extends Remote {
String getMessage() throws RemoteException;
}
Step 2: Implement the Remote Object
● The implementation class extends Activatable instead of UnicastRemoteObject.
● Use a constructor that accepts ActivationID and MarshalledObject.
import java.rmi.activation.Activatable;
import java.rmi.activation.ActivationID;
import java.rmi.RemoteException;
import java.rmi.MarshalledObject;
public class MyServiceImpl extends Activatable implements MyService {
public MyServiceImpl(ActivationID id, MarshalledObject<?> data)
throws RemoteException {
super(id, 0); // Call to superclass constructor
}

41
@Override
public String getMessage() throws RemoteException {
return "Hello, activated world!";
}
}
Step 3: Create an Activation Group
● Activation groups are required to manage the lifecycle of activated objects.
● Set up a group descriptor and register it.
import java.rmi.activation.*;
public class ActivationSetup {
public static void main(String[] args) {
try {
ActivationGroupDesc groupDesc = new ActivationGroupDesc(null, null);
ActivationGroupID groupID =
ActivationGroup.getSystem().registerGroup(groupDesc);
ActivationDesc objectDesc = new ActivationDesc(
groupID,
"MyServiceImpl",
"file://path/to/class/files",
null
);
MyService stub = (MyService) Activatable.register(objectDesc);
System.out.println("Stub registered: " + stub);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 4: Start the Activation System
Run the rmid activation daemon:
bash
rmid -J-Djava.security.policy=policyfile
Start the RMI registry:
bash

42
rmiregistry
Start the server application.
Step 5: Client Code
The client looks up the remote object as usual and invokes methods on it.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost");
MyService service = (MyService) registry.lookup("MyService");
System.out.println(service.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advantages of Activation
● Resource Efficiency: Objects are created only when needed, conserving
memory and processing power.
● Scalability: Simplifies the development of large-scale distributed systems by
dynamically managing remote objects.
● Fault Tolerance: Allows recovery and reactivation of objects in case of server
failures.
_____________________________________________________________________
2.5 SERIALIZATION AND DESERIALIZATION IN JAVA
Introduction
● Serialization: The process of converting an object into a byte stream to store it
in a file, database, or transmit it over a network.
● Deserialization: The process of reconstructing the object from the byte stream.
Key Features
● Provides persistence for objects.
● Facilitates communication between systems by transferring objects as byte
streams.

43
● Ensures state consistency when objects are passed between applications.
Classes and Interfaces for Serialization
● java.io.Serializable:
○ A marker interface (does not contain methods).
○ Any class implementing this interface is eligible for serialization.
● ObjectOutputStream:
○ Used to write objects to an output stream.
● ObjectInputStream:
○ Used to read objects from an input stream.
Serialization Example
Step 1: Define a Serializable Class
● Implement Serializable in the class.
● All fields of the class should be serializable (primitives and serializable objects).
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for
version control
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", salary=" +
salary + "}";
}
}
Step 2: Serialize the Object
● Use ObjectOutputStream to write the object to a file.
import java.io.FileOutputStream;

44
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
Employee emp = new Employee("John Doe", 101, 50000.0);
try (FileOutputStream fos = new FileOutputStream("employee.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(emp); // Serialize the object
System.out.println("Object has been serialized.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Step 3: Deserialize the Object
● Use ObjectInputStream to read the object from the file.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeDemo {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("employee.ser");
ObjectInputStream ois = new ObjectInputStream(fis)) {
Employee emp = (Employee) ois.readObject(); // Deserialize the object
System.out.println("Object has been deserialized.");
System.out.println(emp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advantages
● Simplifies object persistence.
● Facilitates communication in distributed systems (e.g., RMI, sockets).
__________*____________*______________* _____________*_____________

45
S.
N Question a) Option b) Option c) Option d) Option
o
Which object
builds an
1 information block Skeleton Object Stub Object Server Object Client Object
and sends it to the
server?
Which object
passes the
Client
2 request from the Server Object Skeleton Object Remote Object
Object
Stub object to the
server?
Which tool is used
3 to invoke the RMI javac javadoc rmiregistry rmic
compiler?
When starting the
RMI registry
start rmiregistry
4 service, which java rmiregistry registry start
rmiregistry start
command should
be issued?
Which method is
createRegi
5 used to create an startRegistry newRegistry locateRegistry
stry
RMI registry?
Which method is
used to bind a
6 remote object to a register lookup rebind find
new name in the
RMI registry?
Which method is
used to get the
7 bind rebind register lookup
reference of the
Stub object?
Remote
What does RPC Random Related Process Relational
8 Procedure
stand for? Procedure Call Call Process Call
Call
Which type of
system consists of
a network of Client-Server Distributed Peer-to-Peer
9 Cloud System
independent System System System
computers that
work together?
Which component
1 provides services Both the client
The client The server The network
0 or resources to and the server
clients?

46
UNIT-3
3.1 JDBC Principles
3.2 Database Access
3.3 Database Search
3.4 Creating Multimedia Databases
3.5 Database Support in Web Applications
_______________________________________________________________________
3.1 JDBC Principles
Introduction to JDBC
● Java Database Connectivity (JDBC) is a Java API used for connecting to
relational databases, executing SQL statements, and retrieving results.
● JDBC acts as a bridge between a Java application and a database, enabling
interaction with various database systems.
JDBC Architecture
1. Application Layer:
○ Java application interacts with the database through the JDBC API.
2. JDBC API:
○ Defines interfaces and classes for database access.
○ Works with any database using specific drivers.
3. JDBC Driver Manager:
○ Manages the communication between the application and the database
driver.
4. Database:
○ The actual data storage system.
JDBC Drivers
JDBC supports four types of drivers:
1. Type 1: JDBC-ODBC Bridge Driver:
○ Connects to databases via ODBC.
○ Simple but requires ODBC installation.
2. Type 2: Native API Driver:
○ Converts JDBC calls to native database API.
○ Faster than Type 1 but platform-dependent.
3. Type 3: Network Protocol Driver:
○ Uses a middleware server to translate JDBC requests into database calls.
47
○ Platform-independent.
4. Type 4: Thin Driver:
○ Directly converts JDBC calls into database-specific protocol.
○ Most commonly used, fast, and platform-independent.
Key Components of JDBC
DriverManager
● Manages the JDBC drivers.
● Establishes connections to databases.
Connection
● Represents the session between the Java application and the database.
● Methods:
○ createStatement(): Creates a Statement object.
○ prepareStatement(String sql): Creates a PreparedStatement object.
Statement
● Used to execute SQL queries.
● Types:
○ Statement: For basic SQL queries.
○ PreparedStatement: Precompiled queries with placeholders.
○ CallableStatement: Executes stored procedures.
ResultSet
● Represents the result of a query.
● Provides methods to navigate and retrieve data:
○ next(): Moves to the next row.
○ getString(columnIndex), getInt(columnIndex): Retrieves data from
columns.
Steps to Connect to a Database Using JDBC
1. Load the Driver: Explicit loading is required for older JDBC versions.
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection: Use DriverManager to connect to the database.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
3. Create a Statement: Use Statement, PreparedStatement, or CallableStatement.
Statement stmt = con.createStatement();
4. Execute Queries: Use executeQuery() for SELECT or executeUpdate() for

48
INSERT, UPDATE, DELETE.
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
5. Process Results: Use the ResultSet to fetch query results.
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
6. Close Resources: Close the ResultSet, Statement, and Connection objects to
release resources.
rs.close();
stmt.close();
con.close();
Advanced Features
PreparedStatement : Prevents SQL injection by parameterizing queries.
Example:
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, 10);
ResultSet rs = ps.executeQuery();
CallableStatement - Executes stored procedures in the database.
Example:
CallableStatement cs = con.prepareCall("{call my_procedure(?, ?)}");
cs.setInt(1, 10);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
Batch Processing - Executes multiple queries in a single batch for efficiency.
Example:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees VALUES (1, 'John')");
stmt.addBatch("INSERT INTO employees VALUES (2, 'Jane')");
stmt.executeBatch();
Transactions - Ensures data consistency using commit and rollback.
Example:
con.setAutoCommit(false);
stmt.executeUpdate("INSERT INTO employees VALUES (1, 'John')");
con.commit();

49
Advantages of JDBC
● Platform-independent API.
● Works with multiple database systems.
● Flexible and customizable query execution.
Limitations of JDBC
● Requires writing SQL queries manually.
● Debugging can be challenging for complex queries.
● High-level abstractions like ORM frameworks (e.g., Hibernate) are often
preferred for large applications.

3.2 Database Access in Java


Introduction to Database Access
● Database access refers to the process of connecting to, querying, and
interacting with a database from a Java application.
● Java provides built-in tools like JDBC (Java Database Connectivity) and
frameworks like Hibernate to simplify database operations.
● Common use cases include CRUD operations (Create, Read, Update, Delete),
data retrieval, and transaction management.
Tools and APIs for Database Access
1. JDBC (Java Database Connectivity):
○ A low-level API for direct interaction with relational databases.
○ Executes SQL statements and handles database communication.
2. Java Persistence API (JPA):
○ A high-level API for managing relational data using object-relational
mapping (ORM).
○ Popular implementations: Hibernate, EclipseLink.
3. Spring Framework:
○ Provides simplified database access using JdbcTemplate and integrates
seamlessly with JPA.
Steps to Access a Database Using JDBC
Step 1: Load the Database Driver
Required for older JDBC versions (1.x–3.x):
Class.forName("com.mysql.cj.jdbc.Driver");
50
● Not required for JDBC 4.0+ if the driver is in the classpath.
Step 2: Establish a Connection
Use DriverManager.getConnection() to establish a connection.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
Step 3: Create a Statement
Use Statement, PreparedStatement, or CallableStatement to execute queries.
Statement stmt = con.createStatement();
Step 4: Execute SQL Queries
Execute SELECT queries using executeQuery():
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
Execute INSERT/UPDATE/DELETE using executeUpdate():
int rowsAffected = stmt.executeUpdate("INSERT INTO employees VALUES (1, 'John')");
Step 5: Process Results
Use ResultSet to fetch query results:
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
Step 6: Close Resources
Close the ResultSet, Statement, and Connection objects to free resources:
rs.close();
stmt.close();
con.close();
Advantages of Java Database Access
● Platform-independent APIs for relational databases.
● Flexible query execution using SQL.
● Rich ecosystem of frameworks and libraries for simplified access.

3.3 Interacting - Database Search in Java


Introduction to Database Search
● Database search involves querying a database to retrieve specific data based on
conditions or patterns.
● In Java, JDBC (Java Database Connectivity) provides a standard API for
executing database searches.
● Database search is commonly used for:
51
○ Fetching records that match certain criteria.
○ Retrieving related data using JOINs.
○ Implementing full-text search for text-based content.
SQL Basics for Database Search
Common SQL Clauses for Searching
SELECT: Used to retrieve data.
SELECT * FROM employees;
WHERE: Filters results based on conditions.
SELECT * FROM employees WHERE department = 'Sales';
LIKE: Searches for patterns.
SELECT * FROM employees WHERE name LIKE 'J%';
ORDER BY: Sorts results.
SELECT * FROM employees ORDER BY salary DESC;
JOIN: Combines data from multiple tables.
SELECT e.name, d.name
FROM employees e
JOIN departments d ON e.dept_id = d.id;
Implementing Database Search in Java Using JDBC
Steps for Database Search
1. Load the Driver: Load the JDBC driver.
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection: Use DriverManager to connect to the database.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb","username", "password");
3. Prepare a Query: Use Statement or PreparedStatement to write and execute
the search query.
4. Execute the Query: For SELECT queries, use executeQuery().
5. Process the Results: Iterate through the ResultSet to retrieve data.
6. Close Resources: Close the ResultSet, Statement, and Connection to free
resources.
Example: Simple Database Search
import java.sql.*;
public class DatabaseSearchExample {
public static void main(String[] args) {

52
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
try (Connection con = DriverManager.getConnection(url, username, password)) {
String query = "SELECT * FROM employees WHERE department = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, "Sales");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Best Practices for Database Search
1. Use Indexing:
○ Ensure columns used in search conditions are indexed for faster
performance.
2. Validate Inputs:
○ Prevent injection attacks by validating user inputs.
3. Batch Results:
○ Use pagination for large datasets to avoid memory issues.
4. Optimize Queries:
○ Use explain plans to optimize query performance.

3.4 Creating Multimedia Databases


Introduction to Multimedia Databases
● A multimedia database is designed to store and retrieve multimedia content
like images, audio, video, graphics, and text.
● Traditional relational databases (RDBMS) are not optimized for multimedia
data, leading to the development of specialized databases or extensions.
Characteristics of Multimedia Data
● Large Size: Multimedia files can be significantly larger than text-based data.
53
● Complex Structure: Files like videos may include metadata (e.g., resolution,
frame rate).
● Varied Formats: Multiple formats (e.g., JPEG, MP4, MP3) must be supported.
● Rich Metadata: Metadata is crucial for indexing and searching multimedia
content.
Database Types for Multimedia
1. Relational Databases with BLOB/CLOB:
○ Binary Large Objects (BLOB) for binary data like images and videos.
○ Character Large Objects (CLOB) for large text data.
○ Example: MySQL, PostgreSQL.
2. Object-Oriented Databases:
○ Better suited for handling complex multimedia objects.
○ Example: db4o, ObjectDB.
3. NoSQL Databases:
○ Ideal for unstructured or semi-structured data.
○ Example: MongoDB, Cassandra.
Steps to Create a Multimedia Database
1. Choose the Database: Select an appropriate database system based on data
type and usage.
2. Define Schema: Plan tables to store multimedia and metadata.
Example:
CREATE TABLE multimedia (
id INT PRIMARY KEY,
name VARCHAR(255),
type VARCHAR(50),
data BLOB,
metadata JSON
);
3. Insert Multimedia Data:Use JDBC or database-specific APIs to upload
multimedia files.
Example in Java:
PreparedStatement ps = con.prepareStatement("INSERT INTO multimedia (name, type,
data) VALUES (?, ?, ?)");
ps.setString(1, "sample_image");

54
ps.setString(2, "image/png");
FileInputStream fis = new FileInputStream("path/to/image.png");
ps.setBinaryStream(3, fis);
ps.executeUpdate();
4. Retrieve Data: Retrieve and process multimedia files using JDBC or APIs.
Example:
ResultSet rs = stmt.executeQuery("SELECT data FROM multimedia WHERE id = 1");
if (rs.next()) {
InputStream is = rs.getBinaryStream("data");
FileOutputStream fos = new FileOutputStream("output.png");
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) fos.write(buffer);
}
Indexing and Searching Multimedia Data
● Use metadata for efficient indexing (e.g., tags, timestamps).
● Full-text search for associated text data (e.g., descriptions).
Example Query:
SELECT * FROM multimedia WHERE metadata->>'$.author' = 'John Doe';
Challenges in Multimedia Databases
● Large storage requirements.
● Complex indexing and searching.
● Performance issues with unoptimized queries.
Applications
● Digital Libraries.
● Online Media Streaming (e.g., YouTube, Spotify).
● Image and Video Storage Systems.

3.5 Database Support in Web Applications


Introduction
● Web applications rely on databases for dynamic content management, user
authentication, and transactional operations.
● Databases store and retrieve data that is dynamically rendered on web pages.
Role of Databases in Web Applications
● User Management: Store user details, credentials, and roles.
● Dynamic Content: Enable real-time updates and customization.
55
● Transactions: Support e-commerce operations like inventory and payment
management.
Database Connectivity in Web Applications
1. Using JDBC: Direct database connectivity through Java.
Example Servlet:
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webapp", "user", "password");
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, "john_doe");
ResultSet rs = ps.executeQuery();
2. Using Frameworks: Spring Boot, Hibernate, and JPA provide abstraction layers
for database access.
3. RESTful APIs: Use APIs to connect frontends with backend databases.
Designing Databases for Web Applications
1. Schema Design: Identify entities (e.g., users, products) and their relationships.
Example Schema:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50),
password_hash VARCHAR(255)
);
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10, 2)
);
2. Normalization: Avoid redundancy and improve data consistency.
3. Indexing: Use indexes for faster retrieval of frequently searched data.
Database Operations in Web Applications
● CRUD Operations: Create, Read, Update, and Delete operations are the
backbone of web apps.
Example for CRUD with PreparedStatement:
String insertQuery = "INSERT INTO users (username, password_hash) VALUES (?, ?)";

56
PreparedStatement ps = con.prepareStatement(insertQuery);
ps.setString(1, "jane_doe");
ps.setString(2, "hashed_password");
ps.executeUpdate();

Security in Database Access


1. Prevent SQL Injection:
○ Use PreparedStatement instead of concatenating SQL queries.
2. Encryption:
○ Encrypt sensitive data like passwords and payment details.
3. Access Control:
○ Use role-based access to restrict unauthorized database operations.
Performance Optimization
● Use caching mechanisms like Redis or Memcached for frequently accessed data.
● Optimize queries and database schema.
● Use connection pooling for efficient resource management.
Example Web Application Flow with Database
1. Frontend:
○ Sends an HTTP request with user input.
2. Backend (Java Servlet):
○ Processes the request and interacts with the database.
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, request.getParameter("username"));
ResultSet rs = ps.executeQuery();
if (rs.next()) {
response.getWriter().write("Welcome, " + rs.getString("username"));
}
3. Database:
○ Returns data to the backend, which is rendered on the frontend.
Popular Databases for Web Applications
● Relational: MySQL, PostgreSQL, Oracle Database.
● NoSQL: MongoDB, Firebase, Cassandra.
Challenges in Database Support for Web Applications

57
● Scalability: Handling increased traffic.
● Consistency: Ensuring data accuracy during concurrent operations.
● Security: Protecting sensitive data.

S.
Question a) Option b) Option c) Option d) Option
No
What does Java Java
Java Database Java Data
1 JDBC stand Database Development
Compiler Connection
for? Connectivity Class
Which JDBC
driver
Native API JDBC-ODBC Database- Network Protocol
2 connects to
Driver Bridge Driver specific Driver Driver
databases via
ODBC?
Which of the
following
3 converts JDBC ODBC Driver Native API Driver JDBC Driver Protocol Driver
calls to native
database API?
Which of the
following
Create, Read, Create, Remove, Connect,
represents the Create, Retrieve,
4 Update, Upload, Read, Update,
four basic Undo, Delete
Delete Download Delete
CRUD
operations?
Which object
stores the
Connection ResultSet DriverManager
5 result of a Statement object
object object object
query in
JDBC?
Which
mechanism
executes
Batch Connection Transaction ResultSet
6 multiple
Processing Pooling Management Handling
queries in a
single batch
for efficiency?
Which
method is
used to DriverManage
ResultSet.getCo Connection.c Statement.execu
7 establish a r.getConnecti
nnection() onnect() teQuery()
connection to on()
a database in
JDBC?
8 Which executeUpdat executeQuery() execute() executedb()
method is e()
used to
execute
SELECT
queries in

58
JDBC?
Which of the
following is an
9 example of a MySQL PostgreSQL MongoDB Oracle Database
NoSQL
database?
Which type of
database is
ideal for
Relational Object-Oriented NoSQL
10 unstructured SQL Databases
Databases Databases Databases
or semi-
structured
data?

59
UNIT - IV

4.1 Java Servlet and CGI programming - A simple java Servlet


4.2 Anatomy of a java Servlet
4.3 Reading data from a client - Reading http request header-sending data to a client
and writing the http response header
4.4 working with cookies
4.5 Java Server Pages - JSP Overview, Installation
4.6 Components of a JSP page
4.7 Expressions Scriptlets-Directives-Declarations-A complete example

4.1 Java Servlet and CGI programming - A simple java Servlet


Introduction
● CGI (Common Gateway Interface):
A standard protocol for web servers to execute programs (scripts) to generate
dynamic web pages.
○ Written in languages like Python, Perl, or C.
○ Pros: Language flexibility, simple architecture.
○ Cons: Resource-intensive, slower response time (process-based).
● Java Servlets:
Java classes that run on a web server or application server to handle client
requests and generate responses dynamically.
○ Part of Java EE (now Jakarta EE).
○ A replacement for CGI programming, offering better performance and
scalability.
Java Servlets vs. CGI

Feature CGI Servlets

Process-based (one process per Thread-based (one


Execution Model
request) thread per request)

Faster (lightweight,
Performance Slower (higher resource usage)
shared JVM)

Platform Platform-independent
Language-dependent
Dependency (Java)

Scalability Limited Highly scalable


Simple Java Servlet Example

60
Steps to Create and Deploy a Servlet:
1. Setup Environment:
○ Install a servlet container (e.g., Apache Tomcat).
○ Configure Java Development Kit (JDK).
2. Write the Servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
3. Compile the Servlet:
○ Compile using javac to generate the .class file.
4. Deploy to Web Server:
○ Place the .class file in the WEB-INF/classes directory.
○ Update the web.xml deployment descriptor (optional in modern servlet
containers).
xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

61
5. Access via Browser:
○ Run the server and access http://localhost:8080/appname/hello.
Servlet Lifecycle
1. Initialization:
○ init() method called once when the servlet is loaded.
2. Handling Requests:
○ service() method routes requests to doGet() or doPost().
3. Termination:
○ destroy() method called before unloading the servlet.
Advantages of Java Servlets
1. High performance due to thread-based processing.
2. Platform independence and extensive API support.
3. Easy integration with other Java EE components (e.g., JSP, EJB).
4. Enhanced security features and session management.

4.2 Anatomy of a Servlet


A servlet typically consists of:
1. Package Declaration:
Indicates the package containing the servlet.
package com.example;
2. Imports:
Necessary classes from javax.servlet and javax.servlet.http.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
3. Class Declaration:
Extends HttpServlet (or GenericServlet for non-HTTP use).
public class MyServlet extends HttpServlet {
4. HTTP Methods:
○ Implements methods to handle requests.
■ doGet(HttpServletRequest, HttpServletResponse): For HTTP GET
requests.
■ doPost(HttpServletRequest, HttpServletResponse): For HTTP
POST requests.
Example:
62
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello from Servlet</h1>");
out.println("</body></html>");
}
5. Response Handling:
Uses the HttpServletResponse object to send data back to the client.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>...</body></html>");
6. Deployment Descriptor:
○ Maps the servlet to a URL in the web.xml file.
Important Servlet Methods

Method Purpose

init() Initializes the servlet.

service() Dispatches requests to doGet() or doPost().

doGet() Handles GET requests (e.g., fetch data).

doPost() Handles POST requests (e.g., form submission).

destroy() Cleans up resources before the servlet is unloaded.

getServletConfig() Retrieves configuration details.

getServletInfo() Returns information about the servlet (e.g., author,


version).

Key Objects in a Servlet


1. HttpServletRequest:
○ Contains data sent by the client (e.g., form data, URL parameters).
○ Key Methods:
■ getParameter(String name) – Retrieves parameter values.
■ getMethod() – Returns the HTTP method (GET/POST).

63
2. HttpServletResponse:
○ Used to send the response back to the client.
○ Key Methods:
■ setContentType(String type) – Sets MIME type of the response.
■ getWriter() – Writes text responses.
3. ServletConfig:
○ Provides configuration information for the servlet.
4. ServletContext:
○ Shared among all servlets in the application for global information.
Example Structure of a Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ExampleServlet extends HttpServlet {
@Override
public void init() throws ServletException {
// Initialization code
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Welcome to Servlets</h1>");
out.println("</body></html>");
}
@Override
public void destroy() {
// Cleanup code
}
}
Benefits of Servlets
1. Platform-independent and secure.
2. Thread-based, ensuring efficient use of resources.
3. Scalable, robust, and integrates well with Java EE components.
4. Enables session management and application-specific logic.

4.3 Reading data from a client - Reading http request header-sending data to a client

64
and writing the http response header
1. Reading Data from a Client
Data sent by a client can be read using the HttpServletRequest object provided by the
servlet container. Common methods include:
Reading Form Data
Form data sent via GET or POST can be retrieved using getParameter().
String name = request.getParameter("name");
String age = request.getParameter("age");
Reading Request Body
For POST data, the request body can be read using getReader().
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Example Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Welcome, " + username + "</h1>");
}
2. Reading HTTP Request Headers
HTTP headers provide metadata about the request. They can be accessed using
HttpServletRequest methods:
Common Methods
1. String userAgent = request.getHeader("User-Agent");
2. Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);

65
}
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> headers = request.getHeaderNames();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
while (headers.hasMoreElements()) {
String headerName = headers.nextElement();
out.println(headerName + ": " + request.getHeader(headerName));
}
}
3. Sending Data to a Client
The HttpServletResponse object is used to send data to the client. Key methods
include:
Setting Content Type
Specifies the MIME type of the response.
response.setContentType("text/html");
Writing Response Data
Use getWriter() for text data and getOutputStream() for binary data.
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Dynamic Content</h1>");
out.println("<p>This page was generated using Java Servlets.</p>");
out.println("</body></html>");
}

66
4. Writing HTTP Response Headers
HTTP response headers provide metadata about the response. The
HttpServletResponse object offers methods to manipulate these headers:
Common Methods
1. setHeader(String name, String value)
○ Sets a response header.
response.setHeader("Cache-Control", "no-cache");
2. addHeader(String name, String value)
○ Adds a response header without overwriting existing values.
response.addHeader("Set-Cookie", "userId=12345");
3. setStatus(int statusCode)
○ Sets the HTTP status code.
response.setStatus(HttpServletResponse.SC_OK);
4. sendError(int statusCode, String message)
○ Sends an error response with a custom message.
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request data");
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Custom-Header", "MyValue");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>HTTP Headers Example</h1>");
out.println("</body></html>");
}

4.4 Working with Cookies


What are Cookies?
Cookies are small pieces of data stored on the client-side and sent with every HTTP
request to the server. Cookies are name-value pairs sent by a server to a client and
stored on the client’s browser. They are used to maintain session state and track user
activities.
Types of Cookies:
67
● Session Cookies: Temporary cookies deleted when the browser is closed.
● Persistent Cookies: Stored on the client for a specified duration.
Adding Cookies to a Response
A server sends cookies to a client using the HttpServletResponse object.
Steps to Add a Cookie:
1. Create a Cookie Object:
○ Use the Cookie class.
Cookie cookie = new Cookie("username", "JohnDoe");
2. Set Cookie Properties:
○ setMaxAge(int seconds): Specifies the cookie's lifespan.
cookie.setMaxAge(60 * 60 * 24); // 1 day
3. Add the Cookie to the Response:
○ Use addCookie() on the HttpServletResponse object.
response.addCookie(cookie);
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = new Cookie("username", "JohnDoe");
cookie.setMaxAge(60 * 60 * 24); // 1 day
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Cookie Created Successfully</h1>");
}
Retrieving Cookies from a Request
The client sends cookies back to the server with each request. These cookies can be
accessed using the HttpServletRequest object.
Steps to Retrieve Cookies:
1. Get the Cookies Array:
○ Use getCookies() on the HttpServletRequest object.
Cookie[] cookies = request.getCookies();
2. Iterate and Read Cookies:
○ Loop through the array and check cookie names and values.
if (cookies != null) {

68
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
String username = cookie.getValue();
System.out.println("Username: " + username);
}
}
}
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (cookies != null) {
for (Cookie cookie : cookies) {
out.println("<p>Cookie Name: " + cookie.getName() + "</p>");
out.println("<p>Cookie Value: " + cookie.getValue() + "</p>");
}
} else {
out.println("<h1>No Cookies Found</h1>");
}
}
Deleting Cookies
To delete a cookie, set its maximum age to 0 and add it to the response.
Steps to Delete a Cookie:
1. Retrieve the existing cookie.
2. Set its MaxAge to 0.
3. Add it back to the response.
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {

69
if (cookie.getName().equals("username")) {
cookie.setMaxAge(0); // Delete the cookie
response.addCookie(cookie);
} } }
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Cookie Deleted Successfully</h1>");
}

4.5 Java Server Pages - JSP Overview, Installation


Overview of JSP
What is JSP?
● JSP is a server-side technology built on top of Java Servlets.
● It enables the creation of dynamic web content by embedding Java code into
HTML or XML pages.
● The .jsp files are compiled into Servlets by the web server before execution.
Key Features of JSP:
1. Dynamic Content:
JSP supports Java code for creating interactive and dynamic web pages.
2. Tag-Based Programming:
Provides custom tags and JSTL (JavaServer Pages Standard Tag Library) to
simplify coding.
3. Separation of Concerns:
○ JSP handles the view layer, separating it from business logic (typically in
JavaBeans or Servlets).
○ Promotes the Model-View-Controller (MVC) design pattern.
4. Integration with Java EE:
JSP integrates seamlessly with other Java EE technologies, like Servlets, EJBs,
and JDBC.
5. Built-in Objects:
Predefined objects (e.g., request, response, session, out) make coding simpler.
Advantages of JSP:
● Easier to write than Servlets due to its tag-based approach.
● Reduces the need for extensive Java code within the presentation layer.
● Reusable components with custom tags and JavaBeans.
70
Disadvantages of JSP:
● Slower initial execution as .jsp files are compiled into Servlets.
● Debugging can be challenging compared to Servlets.
● Not suitable for heavy business logic (handled better in Servlets or backend
services).
Installation of JSP
Step 1: Install Java Development Kit (JDK)
1. Download the latest JDK from the Oracle website or OpenJDK.
2. Install and configure the JAVA_HOME environment variable.
bash
export JAVA_HOME=/path/to/jdk
export PATH=$JAVA_HOME/bin:$PATH
Step 2: Install a Web Server with JSP Support
● JSP requires a Servlet container like Apache Tomcat, Jetty, or WildFly.
● Recommended Option: Apache Tomcat.
Download and Setup Apache Tomcat:
i) Download Tomcat from the Tomcat website.
ii) Extract the downloaded file.
tar -xvzf apache-tomcat-x.x.x.tar.gz
cd apache-tomcat-x.x.x
iii) Start the Tomcat server:
bash
./bin/startup.sh # For Linux/Mac
./bin/startup.bat # For Windows
iv) Access the server at http://localhost:8080.
Step 3: Deploy a JSP File
i) Create a JSP file (e.g., hello.jsp):
<html>
<body>
<h1>Hello, JSP!</h1>
<p>The current date and time is: <%= new java.util.Date() %></p>
</body>
</html>
ii) Place the file in the webapps/ROOT directory of the Tomcat installation.
iii) Access the JSP page in a browser:

71
http://localhost:8080/hello.jsp
Step 4: Configure Environment (Optional)
● Configure additional settings in conf/server.xml or deploy specific web
applications in the webapps folder.

4.6 Components of a JSP Page


1. Directives
2. Scripting Elements
3. Action Elements
4. Implicit Objects
5. Static Content
6. Custom Tags and Tag Libraries
1. Directives
Directives provide instructions to the JSP container on how to process the page. These
instructions are not directly visible in the output.
Types of Directives:
i)
Syntax:
<%@ page attribute="value" %>
Example:
<%@ page language="java" contentType="text/html" %>
ii)
Syntax:
<%@ include file="filename" %>
Example:
<%@ include file="header.jsp" %>
iii)
Syntax:
<%@ taglib uri="URI" prefix="prefix" %>
Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2. Scripting Elements
These elements embed Java code directly in a JSP page.
Types of Scripting Elements:
i) Declarations (<%! ... %>)

72
Declare variables or methods for use throughout the page.
Example:
<%! int counter = 0; %>
<%! public String greet() { return "Hello!"; } %>
ii) Scriptlets (<% ... %>)
Embed blocks of Java code.
Example:
<%
String user = "John";
out.println("Welcome, " + user);
%>
iii) Expressions (<%= ... %>)
Outputs the result of a Java expression directly to the page.
Example:
<p>The current time is: <%= new java.util.Date() %></p>
3. Action Elements
Action elements perform predefined actions and interact with server-side components.
i) <jsp:include>: Dynamically includes another resource.
Example:
<jsp:include page="footer.jsp" />
ii) <jsp:forward>: Forwards the request to another resource.
Example:
<jsp:forward page="nextPage.jsp" />
iii) <jsp:useBean>: Instantiates or references a JavaBean.
Example:
<jsp:useBean id="user" class="com.example.User" />
iv) <jsp:setProperty> and <jsp:getProperty>:
Sets and retrieves properties of JavaBeans.
Example:
<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:getProperty name="user" property="name" />
4. Implicit Objects
JSP provides pre-defined objects that are available in every JSP page without explicit
declaration.

73
Common Implicit Objects:
● request: Represents the HTTP request and contains client data.
● response: Represents the HTTP response sent to the client.
● session: Represents the session object for the client.
● out: Used to send content to the client.
● application: Represents the ServletContext shared by all servlets and JSPs.
● config: Provides servlet configuration data.
● pageContext: Facilitates interaction between JSP components.
● exception: Represents exceptions, available in error pages.
5. Static Content
JSP pages can include HTML, CSS, JavaScript, and other static content alongside
dynamic Java code.
Example of Static Content:
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome to the Website</h1>
</body>
</html>
6. Custom Tags and Tag Libraries
Custom tags and tag libraries allow the reuse of functionality and simplify the JSP code.
Taglib Example:
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${user != null}">
<p>Welcome, ${user.name}</p>
</c:if>
A Complete JSP Page
Here’s an example of a complete JSP page with all components:
<%@ page language="java" contentType="text/html" %>
<%@ include file="header.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

74
<html>
<head>
<title>My JSP Page</title>
</head>
<body>
<%
String name = "Alice";
int visits = 5;
%>
<h1>Welcome, <%= name %>!</h1>
<p>This is your <%= visits %> visit.</p>
<c:if test="${visits > 1}">
<p>We’re glad to see you again!</p>
</c:if>
<jsp:include page="footer.jsp" />
</body>
</html>

4.7 Directives, , Scriptlets, Expressions and Declarations - A complete example


JSP Directives
Directives provide instructions to the JSP container and affect the overall structure of
the page.
Types of Directives:
i) Page Directive:
Defines page-level settings like scripting language, error handling, and buffer size.
Syntax:
<%@ page attribute="value" %>
Example:
<%@ page language="java" contentType="text/html" %>
ii) Include Directive:
Includes the content of another file at page translation time.
Syntax:
<%@ include file="filename" %>
Example:
<%@ include file="header.jsp" %>
75
iii) Taglib Directive:
Declares a library of custom tags.
Syntax:
<%@ taglib uri="URI" prefix="prefix" %>
Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Scriptlets
Scriptlets (<% ... %>):
Embed Java code inside JSP pages.
Example:
<%
int x = 10;
out.println("Value of x: " + x);
%>
Expressions
Expressions (<%= ... %>):
Outputs the result of a Java expression directly to the page.
Example:
<p>The current time is: <%= new java.util.Date() %></p>
Declarations
Declarations (<%! ... %>):
Declare variables or methods that can be reused.
Example:
<%! int counter = 0; %>
<%! public String greet() { return "Hello, World!"; } %>

76
S.
N Question a) Option b) Option c) Option d) Option
o
Which of the following
1 methods in a servlet is used to doPost() service() doGet() init()
handle GET requests?
What is the purpose of the init() Dispatches Handles POST Initializes Cleans up
2
method in a servlet? requests requests the servlet resources
Which method is used to clean
getServletC
3 up resources before a servlet destroy() doGet() service()
onfig()
is unloaded?
Which method retrieves the
getServletCo
4 configuration details of a getServ() service() destroy()
nfig()
servlet?
Which of the following is a Apache Apache
5 Apache Kafka Java Cat
servlet container? Tomcat Java
Which method handles
6 init() destroy() service() doGet()
requests in a servlet?
Which directive in JSP declares Taglib Include UseBean
7 Page Directive
a library of custom tags? Directive Directive Directive
Which JSP tag is used to
<jsp:useBe <jsp:scriptl
8 forward a request to another <jsp:include> jsp:forward
an> et>
resource?
Which JSP tag is used to
jsp:useBea <jsp:forwar <jsp:scriptl
9 instantiate or reference a <jsp:include>
n d> et>
JavaBean?
Which of the following JSP tags
1 <jsp:useBe <jsp:scriptl
dynamically includes another <jsp:forward> jsp:include
0 an> et>
resource?

77
UNIT - V

5.1 JAR file format creation


5.2 Internationalization
5.3 Swing Programming
5.4 Advanced java Techniques

5.1 JAR file format creation


A JAR (Java Archive) file is a compressed file format used to package Java classes,
resources, and metadata into a single file. It simplifies the distribution and deployment
of Java applications, libraries, and components.
1. Structure of a JAR File
A JAR file is essentially a ZIP file with a specific structure and a mandatory file named
META-INF/MANIFEST.MF. Here's what a typical JAR file contains:
1. Compiled Class Files: .class files generated from Java source code.
2. Resource Files: Images, text files, configuration files, etc.
3. Manifest File: A special file (META-INF/MANIFEST.MF) that contains metadata
about the JAR, such as the main class for execution.
2. Advantages of JAR Files
● Portability: A single file for distribution.
● Compression: Saves disk space and reduces transfer time.
● Classpath Configuration: Simplifies loading classes and resources.
● Digital Signing: Ensures the integrity and authenticity of contents.
3. Creating a JAR File
The jar tool, provided with the Java Development Kit (JDK), is used to create JAR files.
The basic syntax is:
bash
jar cf jar-file input-files
● c: Create a new JAR file.
● f: Specify the name of the output JAR file.
Step-by-Step Process to Create a JAR File
i) Compile Java Classes:
Use the javac command to compile your .java files into .class files.
Example:
bash

78
javac HelloWorld.java
ii) Create the JAR File:
Use the jar command to bundle the compiled files.
Example:
bash
jar cf HelloWorld.jar HelloWorld.class
iii) Verify the JAR File:
Use the jar command to view the contents of the JAR file.
Example:
bash
jar tf HelloWorld.jar
4. Adding a Manifest File
A manifest file (META-INF/MANIFEST.MF) provides metadata about the JAR file, such as
the main class for execution.
Example Manifest File (manifest.txt):
plaintext
Manifest-Version: 1.0
Main-Class: HelloWorld
Create a JAR File with a Manifest:
bash
jar cfm HelloWorld.jar manifest.txt HelloWorld.class
● m: Include a manifest file.
Run the JAR File:
If the Main-Class is specified in the manifest, you can run the JAR file directly:
bash
java -jar HelloWorld.jar
5. Adding Multiple Files and Directories
You can include multiple files and directories in a JAR file. For example:
bash
jar cf MyApp.jar *.class images/ config/
This command packages all .class files, the images directory, and the config directory
into MyApp.jar.
6. Updating an Existing JAR File
To add new files to an existing JAR, use the u option:

79
bash
jar uf HelloWorld.jar NewClass.class
7. Extracting Files from a JAR File
To extract files from a JAR, use the x option:
bash
jar xf HelloWorld.jar
8. Signing a JAR File
To ensure the integrity of the JAR file, you can sign it using the jarsigner tool:
bash
jarsigner -keystore myKeystore -signedjar SignedHelloWorld.jar HelloWorld.jar myAlias
9. Example Workflow
Source Code (HelloWorld.java):
java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compile the Code:
javac HelloWorld.java
Create a Manifest (manifest.txt):
Manifest-Version: 1.0
Main-Class: HelloWorld
Create the JAR File:
jar cfm HelloWorld.jar manifest.txt HelloWorld.class
Run the JAR File:
java -jar HelloWorld.jar

5.2 Internationalization (i18n) in Java


Internationalization (i18n) refers to the process of designing and developing software
applications so that they can be adapted to different languages, regions, and cultures
without requiring engineering changes. This makes it easier to localize the application
for different markets. Java provides built-in support for internationalization, allowing
developers to create applications that are flexible enough to support different locales,
languages, and cultural preferences.
80
Java supports internationalization through several mechanisms, such as localization
(the adaptation of software to a specific language and region), resource bundles, and
locale-specific formatting for dates, numbers, and currencies.
Key Concepts in Internationalization
1. Locale:
A Locale is an object that represents a specific geographical, political, or cultural
region. It is characterized by:
○ Language code (e.g., "en" for English, "fr" for French).
○ Country code (e.g., "US" for United States, "FR" for France).
Example of Locale usage:
Locale locale = new Locale("fr", "FR"); // French in France
System.out.println("Language: " + locale.getLanguage()); // Output: fr
System.out.println("Country: " + locale.getCountry()); // Output: FR
2. Resource Bundles:
Resource bundles are used to store locale-specific objects, such as messages,
labels, and other text, in properties files. They allow the application to load the
appropriate resources depending on the user's locale.
○ Resource files are typically named with the pattern
baseName_locale.properties.
■ For example, Messages_en.properties for English,
Messages_fr.properties for French.
Example of Resource Bundle:
Messages_en.properties
greeting=Hello
farewell=Goodbye
Messages_fr.properties
greeting=Bonjour
farewell=Au revoir
Java code to load Resource Bundle:
import java.util.Locale;
import java.util.ResourceBundle;
public class ResourceBundleExample {
public static void main(String[] args) {
Locale locale = new Locale("fr", "FR");

81
ResourceBundle bundle = ResourceBundle.getBundle("Messages", locale);
System.out.println(bundle.getString("greeting")); // Output: Bonjour
System.out.println(bundle.getString("farewell")); // Output: Au revoir
}
}

5.3 Swing Components


Swing provides a wide variety of components for building GUIs. These include:
1. Top-Level Containers
● JFrame: The main window for a Swing application.
● JDialog: A pop-up dialog box.
● JWindow: A non-decorated window (without borders or buttons).
● JApplet: For creating applets (though applets are now deprecated in most
modern browsers).
Example (JFrame):
import javax.swing.JFrame;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My Swing Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
2. Components for Displaying Data
● JLabel: Displays text or images.
● JTextField: Allows user input as a single line of text.
● JTextArea: Allows multi-line text input or display.
● JButton: A button that triggers an action.
● JList: Displays a list of items.
● JComboBox: A drop-down list.
● JTable: Displays data in a tabular format.
Example (JLabel and JButton):
import javax.swing.JButton;
import javax.swing.JFrame;
82
import javax.swing.JLabel;
public class SimpleSwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
JLabel label = new JLabel("Click the button!");
JButton button = new JButton("Click Me");
button.addActionListener(e -> label.setText("Button clicked!"));
frame.add(label);
frame.add(button);
frame.setLayout(null);
label.setBounds(50, 50, 200, 30);
button.setBounds(50, 100, 100, 30);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. Layout Managers
Swing uses layout managers to organize components in containers, making them
responsive to changes in size.
● FlowLayout: Default layout manager for JPanel, arranges components in a left-
to-right flow.
● BorderLayout: Divides the container into five areas: North, South, East, West,
and Center.
● GridLayout: Divides the container into rows and columns of equal-sized cells.
● BoxLayout: Arranges components either vertically or horizontally.
● GridBagLayout: A flexible and complex layout manager that allows fine-grained
control.
Example (FlowLayout):
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");

83
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. Event Handling in Swing
Swing uses an event-driven model, meaning that an application responds to events
(like mouse clicks, key presses, etc.) generated by user actions.
● Event Sources: Objects that generate events (e.g., buttons, text fields).
● Event Listeners: Objects that handle events (e.g., ActionListener,
MouseListener).
Example (Button Click Listener):
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonClickExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

84
In this example, when the button is clicked, a message dialog is shown using
JOptionPane.

5. Common Swing Components and Their Usage

Component Description Example Use

JFrame Main window for the Main GUI window.


application.

JLabel Displays a short string or an Displaying text.


image.

JButton A button that performs an Form submission or


action when clicked. triggering events.

JTextField A single-line text input field. User entering a single


value.

JTextArea A multi-line text area for user For entering comments or


input or displaying text. descriptions.

JComboBox A drop-down list for selecting Choosing from predefined


from multiple options. options.

JCheckBox A box that can be either For true/false options.


checked or unchecked.

JRadioButton A button in a set of radio Choosing one option from


buttons where only one can be a group.
selected.

JList Displays a list of items. Selecting from a list of


items.

JTable Displays tabular data (rows and Displaying structured data.


columns).

85
6. Advanced Features in Swing
Look and Feel (L&F): Swing supports different look and feels, allowing you to customize
the appearance of the GUI. The default look and feel is "Metal," but other L&F like
"Windows" and "Motif" can be applied.
Example:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
● JProgressBar: Used to show the progress of a task.
● JTabbedPane: Allows the creation of tabbed panes for organizing content into
separate tabs.
● JToolBar: A panel with buttons or controls that provide quick access to
frequently used operations.

5.4 Advanced Java Techniques

i) Concurrency and Multithreading

Concurrency in Java refers to the ability to execute multiple tasks at the same time.
Java provides built-in support for multithreading, allowing developers to take full
advantage of multi-core processors.

Thread Basics

 Thread is a basic unit of execution in Java. Java supports multi-threading to


perform multiple operations simultaneously.
 A thread can be created by:
o Extending the Thread class:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}

o Implementing the Runnable interface:

86
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}

Thread Lifecycle

The lifecycle of a thread includes the following states:

 New: The thread is created but not yet started.


 Runnable: The thread is ready to run but waiting for CPU time.
 Blocked: The thread is waiting for resources (e.g., I/O operations).
 Waiting: The thread is in a waiting state due to specific conditions.
 Terminated: The thread has completed execution.

Synchronization

When multiple threads access shared resources, synchronization is necessary to avoid


data corruption.

 Synchronized methods:

synchronized void method() {


// thread-safe code
}

 Synchronized blocks:

synchronized(this) {
// thread-safe block of code
}

 Locks: ReentrantLock provides advanced locking capabilities compared to the


synchronized keyword.

Executor Framework

The Executor framework provides a higher-level replacement for manually managing


threads.

 ExecutorService: Used to manage and control the execution of asynchronous


tasks.

ExecutorService executor = Executors.newFixedThreadPool(4);


executor.submit(() -> System.out.println("Task executed"));
executor.shutdown();

ii) Java Design Patterns

Design patterns provide reusable solutions to common design problems in software


development.

87
Singleton Pattern

Ensures that a class has only one instance and provides a global point of access.

Example:

public class Singleton {


private static Singleton instance;
private Singleton() {}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Factory Pattern

Defines an interface for creating objects, but lets subclasses decide which class to
instantiate.

Example:

interface Product {
void doSomething();
}
class ConcreteProductA implements Product {
public void doSomething() {
System.out.println("Product A");
}
}
class ProductFactory {
public Product createProduct(String type) {
if (type.equals("A")) {
return new ConcreteProductA();
}
// return other products
return null;
}
}

iii) Java 8 Features

Lambda Expressions

Lambda expressions allow you to define anonymous methods (implementations of


functional interfaces) concisely.

Syntax:

88
(parameters) -> expression

Example:

(a, b) -> a + b

Streams API

Streams provide a functional approach to processing sequences of elements (like


collections) in a declarative manner.

Example:

List<String> list = Arrays.asList("a", "b", "c");


list.stream().filter(s -> s.equals("a")).forEach(System.out::println);

Functional Interfaces

Functional interfaces have a single abstract method and may contain default or static
methods.

Example:

@FunctionalInterface
interface MyInterface {
void myMethod();
}

iv) Advanced Java Concepts

Java Reflection

Reflection allows inspection and manipulation of classes, methods, and fields at


runtime.

Example:

Class<?> clazz = Class.forName("com.example.MyClass");


Method method = clazz.getMethod("myMethod");
method.invoke(clazz.newInstance());

Garbage Collection

Java automatically handles memory management through garbage collection. The


garbage collector identifies and removes objects that are no longer referenced.

 Types of Garbage Collectors:


o Serial GC: For single-threaded environments.
o Parallel GC: For multi-threaded environments.
o G1 GC: Low-latency garbage collection for large applications.

-------------------------------------------------------------------------------

89
S. c) d)
Question a) Option b) Option
No Option Option
Java
Java Accessibl
What does JAR stand for in Java Access Java
1 Application e
Java? Resource Archive
Runtime Repositor
y
What type of file is a JAR file Executabl
2 Text file ZIP file Audio file
essentially? e file
Which file contains metadata Resource
3 Class file Manifest file ZIP file
about the JAR file? file
Which command is used to
4 compile .java files into java javac jar javadoc
bytecode?
Which object represents a
Resource Event
5 specific geographical, Locale JFrame
bundle listener
political, or cultural region?
To
To store compile To display
What are resource bundles To store Java
6 locale-specific Java error
used for in Java? bytecode
objects source messages
code
Which of the following is used
7 for building graphical user JDBC Swing JAR Threads
interfaces (GUIs)?
Identify the component used
8 to represent the main window JDialog JFrame JList JTextField
of the application.
Identify the Swing component
JProgressBa
9 used to create a pop-up dialog JDialog JTextField JWindow
r
box.
Identify the component used
JPasswor
10 to enter text as a single line of JTextArea JTextField JLabel
dField
input.

90

You might also like