Advanced Java Programming
Advanced Java Programming
IDENTIFIERS
Should begin with a letter and may contain additional letters and digits. Identifiers are the same as
variables.
Use descriptive names for all variables, function names, constants and other identifiers. Use single
letters only for the counter in loops.
Variable names start with lower-case
Multi-word identifiers are internally capitalized
Do not use hyphens or underscores to separate multi-word identifiers.
The following lists some of these conventions based on the type of identifier:
Class name
The first letter of each word is capitalized, examples:
Mammal, SeaMammal
Function name
The first letter of each, except the first, word is capitalized, examples:
getAge, setHeight
Variable name
The first letter of each, except the first, word is capitalized, examples:
age, brainSize
Constant names
Every letter is capitalized and underscores are used between words, examples:
MAX_HEIGHT, MAX_AGE
RESERVED WORDS
2
As you may have noticed, many of Java's keywords are borrowed from C/C++. Also, as in C/C++,
keywords are always written in lowercase. Generally speaking, Java's keywords can be categorized
according to their function as follows (examples are in parenthesis):
VARIABLE SCOPE
int (16-bit)
float (32-bit)
double (64-bit
boolean (true/false)
char (16-bit unicode)
OBJECTS
ARRAYS
3
int[] array = {1, 2, 3, 4, 5}; // it is initialized and declared at the same time.
Arrays can be of any primitive data type or object. Arrays have an instance variable "length" that we can
access to find out how big the array is. Remember that an Array can throw an
IndexOutOfBoundsException. Make use of it to make your code safe.
VECTORS
Unlike arrays, vectors can only hold objects, no primitive data types are allowed. Vectors can grow big and
unbounded. You may want to specify the capacity of the vector but you don�t need to. The default
capacity is 10 and it doubles in size every time the capacity is reached.
Just like arrays have the "length" instance variable, Vectors have a .size() method that returns the current
size of the vector.
ENUMERATION
This is an iterator and it is very important concept in data structures for ICS211. An Enumeration lets us
visit every element of a Vector one by one.
Arithmetic operators.
Incrementing and decrementing operators.
Good to know but not necessary the Assignment operators
Relational operators
Logical operators
4
for loops
while loops
if statements
switch � case statements
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 [Link] package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). 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 of
these events 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 occur. To
handle the events, Java follows the Delegation Event model.
Delegation Event model
It has Sources and Listeners.
5
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()
Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle
events.
Different interfaces consists of different methods which are specified below.
Java
7
import [Link].*;
import [Link].*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Output
8
Explanation
1. Firstly extend the class with the applet and implement the respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e. ActionEvent by addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class
Java
import [Link].*;
import [Link].*;
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Java
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
}
Output
10
Java
import [Link].*;
import [Link].*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
11
Output
Handling anonymously
Before introducing the thread concept, we were unable to run more than one task in parallel. It was a
drawback, and to remove that drawback, Thread Concept was introduced.
A Thread is a very light-weighted process, or we can say 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.
12
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. All the threads share a common memory and have their
own stack, local variables and program counter. When multiple threads are executed in parallel at the same
time, this process is known as Multithreading.
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
4) Blocked
13
5) Terminated
A thread comes in this state when at any given time, it halts its execution immediately.
Creating 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.
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)
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
callstack. 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.
Let's take an example to understand how we can create a Java thread by extending the Thread class:
[Link]
1. // Implementing runnable interface by extending Thread class
2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.
4. public void run()
14
5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. [Link]("Thread started running..");
10. [Link]("Sum of two numbers is: "+ result);
11. }
12. public static void main( String args[] )
13. {
14. // Creating instance of the class extend Thread class
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. [Link]();
18. }
19. }
Output:
In Java, we can also create a thread by implementing the runnable interface. The runnable interface
provides us both the run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread using the runnable
interface.
[Link]
Output:
16
Java Networking
When computing devices such as laptops, desktops, servers, smartphones,
and tablets and an eternally-expanding arrangement of IoT gadgets such as
cameras, door locks, doorbells, refrigerators, audio/visual systems,
thermostats, and various sensors are sharing information and data with each
other is known as networking.
All the Java program communications over the network are done at the
application layer. The [Link] package of the J2SE APIs comprises various
classes and interfaces that execute the low-level communication features,
enabling the user to formulate programs that focus on resolving the problem.
4. MAC Address – MAC address stands for Media Access Control address. It is
a bizarre identifier that is allocated to a NIC (Network Interface Controller/
Card). It contains a 48 bit or 64-bit address, which is combined with the
network adapter. MAC address can be in hexadecimal composition. In
simple words, a MAC address is a unique number that is used to track a
device in a network.
Cache Request – The CacheRequest class is used in java whenever there is a need to store
resources in ResponseCache. The objects of this class provide an edge for the OutputStream
object to store resource data into the cache.
InetAddress – The InetAddress class is used to provide methods to get the IP address of
any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each Socket
object built using [Link] class has been connected exactly with 1 remote host;
for connecting to another host, a user must create a new socket object.
URL – The URL class in Java is the entry point to any available sources on the internet. A
Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the
World Wide Web. A source can denote a simple file or directory, or it can indicate a more
difficult object, such as a query to a database or a search engine.
The [Link] package of the Java programming language includes various interfaces also that
provide an easy-to-use means to access network resources. The interfaces included in
the [Link] package are as follows:
1. CookiePolicy – The CookiePolicy interface in the [Link] package provides the classes for
implementing various networking applications. It decides which cookies should be accepted
and which should be rejected. In CookiePolicy, there are three pre-defined policy
implementations, namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.
4. SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows
the user to set various standard options.
Socket Programming
Java Socket programming is practiced for communication between the applications working on
different JRE. Sockets implement the communication tool between two computers using TCP.
Java Socket programming can either be connection-oriented or connection-less. In Socket
Programming, Socket and ServerSocket classes are managed for connection-oriented socket
programming. However, DatagramSocket and DatagramPacket classes are utilized for
connection-less socket programming.
A client application generates a socket on its end of the communication and strives to combine
that socket with a server. When the connection is established, the server generates an object of
socket class on its communication end. The client and the server can now communicate by
writing to and reading from the socket.
The [Link] class describes a socket, and the [Link] class implements a
tool for the server program to host clients and build connections with them.
Steps to establishing a TCP connection between two computing devices using Socket
Programming
The following are the steps that occur on establishing a TCP connection between two computers
using socket programming are given as follows:
Step 1 – The server instantiates a ServerSocket object, indicating at which port number
communication will occur.
Step 2 – After instantiating the ServerSocket object, the server requests the accept() method of
the ServerSocket class. This program pauses until a client connects to the server on the given
port.
Step 3 – After the server is idling, a client instantiates an object of Socket class, defining the
server name and the port number to connect to.
Step 4 – After the above step, the constructor of the Socket class strives to connect the client to
the designated server and the port number. If communication is authenticated, the client
forthwith has a Socket object proficient in interacting with the server.
Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server
connected to the client’s socket.
After the connections are stabilized, communication can happen using I/O streams. Each object
of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is
correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s
OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol.
Hence information can be transmitted over both streams at the corresponding time.
Socket Class
22
The Socket class is used to create socket objects that help the users in implementing all
fundamental socket operations. The users can implement various networking actions such as
sending, reading data, and closing connections. Each Socket object created
using [Link] class has been correlated specifically with 1 remote host. If a user wants to
connect to another host, then he must build a new socket object.
Methods of Socket Class
In Socket programming, both the client and the server have a Socket object, so all the methods
under the Socket class can be invoked by both the client and the server. There are many methods
in the Socket class.
ServerSocket Class
S
Method Description
No.
public void This method is used to connect the socket to the particularized
1 connect(SocketAddres host. This method is required only when the user instantiates the
s host, int timeout) Socket applying the no-argument constructor.
This method is used to return the port to which the socket is
2 public int getPort()
pinned on the remote machine.
public InetAddress This method is used to return the location of the other computer
3
getInetAddress() to which the socket is connected.
public int This method is used to return the port to which the socket is
4
getLocalPort() joined on the local machine.
public SocketAddress
5 getRemoteSocketAddr This method returns the location of the remote socket.
ess()
This method is used to return the input stream of the socket.
public InputStream
6 This input stream is combined with the output stream of the
getInputStream()
remote socket.
This method is used to return the output stream of the socket.
public OutputStream
7 The output stream is combined with the input stream of the
getOutputStream()
remote socket.
This method is used to close the socket, which causes the object
8 public void close() of the Socket class to no longer be able to connect again to any
server.
The ServerSocket class is used for providing system-independent implementation of the server-
side of a client/server Socket Connection. The constructor for ServerSocket class throws an
exception if it can’t listen on the specified port. For example – it will throw an exception if the
port is already being used.
Methods of ServerSocket Class:
23
There are many methods in the ServerSocket class which are very useful for the users. These
methods are:
S Method Description
no.
This method is used to return the port that the server socket is
monitoring on. This method is beneficial if a user passed 0 as the
public int port number in a constructor and lets the server find a port for
getLocalPort() him.
1
public void This method is used to set the time-out value for the time in
setSoTimeout( which the server socket pauses for a client during the accept()
int timeout) method.
2
public void This method is used to bind the socket to the particularized
bind(SocketAd server and port in the object of SocketAddress. The user should
dress host, int use this method if he has instantiated the ServerSocket using the
backlog) no-argument constructor.
4
Example of Socket Programming in Java:
The below example illustrates a pretty basic one-way Client and Server setup where a Client
connects, sends messages to the server and the server shows them using a socket connection.
Client-Side Java Implementation:
Java
// A Java program for a ClientSide
import [Link].*;
import [Link].*;
// establish a connection
try {
[Link]("Connected");
clientSide client
= new clientSide("[Link]", 5000);
}
}
[Link]("Server started");
[Link]("Waiting for a client ...");
socket = [Link]();
[Link]("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(
[Link]()));
String line = "";
// reads message from client until "End" is sent
while () {
try {
line = [Link]();
[Link](line);
}
catch (IOException i) {
[Link](i);
}
}
[Link]("Closing connection");
// close connection
[Link]();
[Link]();
}
catch (IOException i) {
[Link](i);
26
}
}
public static void main(String[] args)
{
serverSide server = new serverSide(5000);
}
}
InetAddress
The InetAddress class is used to provide methods to get the IP address of any hostname. An IP
address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes
the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6
addresses.
There are two different types of addresses:
Unicast – It is an identifier for a single interface.
Multicast – It is an identifier for a collection of interfaces.
Methods of InetAddress Class
Java InetAddress class represents an IP address. The following given are the important methods
of the InetAddress class –
Method Description
S No.
static InetAddress This method is used to return an object of the InetAddress class
1
getByAddress(byte[] addr) provided the raw IP address.
static InetAddress
This method is used to create an InetAddress based on the given
2 getByAddress(String host, byte[]
hostname and IP address.
addr)
static InetAddress This method is used to determine the IP address of a host when the
3
getByName(String host) host’s name is given.
static InetAddress InetAddress
4 This method is used to return the localhost.
getLocalHost()
27
5 String getHostName() This method is used to get the name of the IP address.
This method returns the IP address in the form of a string in a textual
6 String getHostAddress()
display.
7 String toString() This method is used to convert the IP address to a string.
Example 1:Java
import [Link].*;
throws UnknownHostException
"[Link]");
+ address1);
"[Link]");
[Link](arr[i]); } } }
Output
URL Class
The URL class in Java is the entry point to any available sources on the internet. A Class URL
describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide
Web. A source can denote a simple file or directory, or it can indicate a more difficult object,
such as a query to a database or a search engine. URL is a string of text that recognizes all the
sources on the Internet, showing us the address of the source, how to interact with it, and recover
something from it.
Components of a URL
A URL can have many forms. The most general however follows a three-components system-
29
1. Protocol – The protocol in a URL defines how information is transported among the host and
a client (or web browser).
2. Hostname – The hostname is the name of the device on which the resource exists.
3. File Name – The filename is the pathname to the file on the device.
4. Port Number – The port number is used to identify different applications uniquely. It is
typically optional.
Methods of Java URL Class
There are many methods in Java URL Class that are commonly used in Java Networking. These
methods are:
S.
No. Methods Description
public String
1 This method returns the protocol that is used by the URL.
getProtocol()
public String This method returns the hostname of the URL in IPv6
2
getHost() composition.
public int This method returns the port associated with the protocol
3
getPort() specified by the URL.
public String
4 This method returns the filename.
getFile()
public String
5 This method returns the path of the URL, or null if empty.
getPath()
public String This method is used to return the string representation of the
6
toString() provided URL object.
public int
7 This method returns the default port used.
getDefaultPort()
Examples of URL Class Methods
The Java implementation of the URL class to illustrate the usage of methods is shown below
Example 1:
Java
import [Link].*;
Output
URL :[Link]
Example 2:
Java
import [Link].*;
Output
Protocol : https
HostName : [Link]
File Name : /post/3038131
Example 3:
Java
import [Link].*;
throws MalformedURLException
{
Output
Default Port : 443
Path : /post/3038131
This was a brief introduction to Java Networking. In this article, many important topics like
Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java
Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL
Class were covered.
UNIT II
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
32
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
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:
Java
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.
34
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
// Java program for server application
import [Link].*;
import [Link].*;
public class SearchServer
{
public static void main(String args[])
{
try
{
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();
answer = [Link](value);
[Link]("Article on " + value +
" " + answer+" at GeeksforGeeks");
}
catch(Exception ae)
{
[Link](ae);
}
}
}
Important Observations:
1. RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to
create the distributed applications in java.
2. Stub and Skeleton objects are used for communication between the client
and server-side.
Distributed Architecture
In distributed architecture, components are presented on different platforms and
several components can cooperate with one another over a communication network in
order to achieve a specific objective or goal.
The following table lists the different forms of transparency in a distributed system −
Sr.N
Transparency & Description
o.
Access
1
Hides the way in which resources are accessed and the differences in data platform.
Location
2
Hides where resources are located.
Technology
3
Hides different technologies such as programming language and OS from user.
Migration / Relocation
4
Hide resources that may be moved to another location which are in use.
Replication
5
Hide resources that may be copied at several location.
Concurrency
6
Hide resources that may be shared with other users.
Failure
7
Hides failure and recovery of resources from user.
Persistence
8
Hides whether a resource ( software ) is in memory or disk.
Advantages
Resource sharing − Sharing of hardware and software resources.
Openness − Flexibility of using hardware and software of different vendors.
Concurrency − Concurrent processing to enhance performance.
37
Disadvantages
Complexity − They are more complex than centralized systems.
Security − More susceptible to external attack.
Manageability − More effort required for system management.
Unpredictability − Unpredictable responses depending on the system
organization and network load.
Client-Server Architecture
The client-server architecture is the most common distributed system architecture
which decomposes the system into two major subsystems or logical processes −
Client − This is the first process that issues a request to the second process
i.e. the server.
Server − This is the second process that receives the request, carries it out,
and sends a reply to the client.
In this architecture, the application is modelled as a set of services that are provided
by servers and a set of clients that use these services. The servers need not know
about clients, but the clients must know the identity of servers, and the mapping of
processors to processes is not necessarily 1 : 1
38
Client-server Architecture can be classified into two models based on the functionality
of the client −
Thin-client model
In thin-client model, all the application processing and data management is carried by
the server. The client is simply responsible for running the presentation software.
Used when legacy systems are migrated to client server architectures in which
legacy system acts as a server in its own right with a graphical interface
implemented on a client
A major disadvantage is that it places a heavy processing load on both the
server and the network.
Thick/Fat-client model
In thick-client model, the server is only in charge for data management. The software
on the client implements the application logic and the interactions with the system
user.
Most appropriate for new C/S systems where the capabilities of the client
system are known in advance
More complex than a thin client model especially for management. New versions
of the application have to be installed on all clients.
39
Advantages
Separation of responsibilities such as user interface presentation and business
logic processing.
Reusability of server components and potential for concurrency
Simplifies the design and the development of distributed applications
It makes it easy to migrate or integrate existing applications into a distributed
environment.
It also makes effective use of resources when a large number of clients are
accessing a high-performance server.
Disadvantages
Lack of heterogeneous infrastructure to deal with the requirement changes.
Security complications.
Limited server availability and reliability.
Limited testability and scalability.
Fat clients with presentation and business logic together.
The most general use of multi-tier architecture is the three-tier architecture. A three-
tier architecture is typically composed of a presentation tier, an application tier, and a
data storage tier and may execute on a separate processor.
Presentation Tier
Presentation layer is the topmost level of the application by which users can access
directly such as webpage or Operating System GUI (Graphical User interface). The
primary function of this layer is to translate the tasks and results to something that
user can understand. It communicates with other tiers so that it places the results to
the browser/client tier and all other tiers in the network.
Data Tier
In this layer, information is stored and retrieved from the database or file system. The
information is then passed back for processing and then back to the user. It includes
the data persistence mechanisms (database servers, file shares, etc.) and provides
API (Application Programming Interface) to the application tier which provides
methods of managing the stored data.
41
Advantages
Disadvantages
Client and the server do not interact with each other directly. Client and server
have a direct connection to its proxy which communicates with the mediator-
broker.
A server provides services by registering and publishing their interfaces with the
broker and clients can request the services from the broker statically or
dynamically by look-up.
42
Broker
Stub
Stubs are generated at the static compilation time and then deployed to the client side
which is used as a proxy for the client. Client-side proxy acts as a mediator between
the client and the broker and provides additional transparency between them and the
client; a remote object appears like a local one.
The proxy hides the IPC (inter-process communication) at protocol level and performs
marshaling of parameter values and un-marshaling of results from the server.
Skeleton
Skeleton is generated by the service interface compilation and then deployed to the
server side, which is used as a proxy for the server. Server-side proxy encapsulates
low-level system-specific networking functions and provides high-level APIs to mediate
between the server and the broker.
It receives the requests, unpacks the requests, unmarshals the method arguments,
calls the suitable service, and also marshals the result before sending it back to the
client.
Bridge
43
Bridges are optional component, which hides the implementation details when two
brokers interoperate and take requests and parameters in one format and translate
them to another format.
Features of SOA
A service-oriented architecture provides the following features −
SOA Operation
The following figure illustrates how does SOA operate −
Advantages
45