Java Notes
Java Notes
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
frame or window. The BorderLayout provides five constants for each region:
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default
5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or
horizontally. For this purpose, the BoxLayout class provides four constants. They are as
follows:
1. public static final int X_AXIS: Alignment of the components are horizontal from
left to right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.
3. public static final int LINE_AXIS: Alignment of the components is similar to the
way words are aligned in a line, which is based on the ComponentOrientation
property of the container.
4. public static final int PAGE_AXIS: Alignment of the components is similar to the
way text lines are put on a page, which is based on the ComponentOrientation
property of the container.
1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.
Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of the same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as its
display area. Each component associates an instance of GridBagConstraints. With the help of
the constraints object, we arrange the component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine the component's size.
Constructor
GridBagLayout():
GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class.
Group is an abstract class, and two concrete classes which implement this Group class are
SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another whereas ParallelGroup
aligns its child on top of each other.
Constructors
Java SpringLayout
Each child of a SpringLayout container, as well as the container itself, has exactly one set of
constraints associated with them.
Constructor
SpringLayout(): The default constructor of the class is used to instantiate the SpringLayout
class.
Remote Method Invocation (RMI):-
It 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. RMI is used to build distributed applications; it provides remote communication
between Java programs. It is provided in the package java.rmi.
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:
Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.
RRL(Remote Reference Layer) − It is the layer which manages the references made
by the client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works −
When the client makes a call to the remote object, it is received by the stub
which eventually passes this request to the RRL.
When the client-side Remote Reference layer receives the request, it invokes a
method called invoke() of the object remoteRef. It passes the request to the
RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the
server) which finally invokes the required object on the server.
The result is passed all the way back to the client.
RMI registry is a namespace on which all server objects are placed. Each time the server
creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods).
SWING
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used
to create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing Supports a Pluggable look and feels And Swing provides more powerful
components such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
Further Swing Follows MVC.
Swing is a Set Of API ( API- Set Of Classes and Interfaces )
It Employs model/view design architecture
Swing is more portable and more flexible than AWT
Swing is Provided to Design Graphical User Interfaces
Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Hierarchy of Java Swing classes
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in the
tree. It inherits JComponent class.
Generics
means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is
possible to create classes that work with different data types. An entity such as class,
interface, or method that operates on a parameterized type is a generic entity.
Generics in Java are similar to templates in C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very well.
1) Type-safety:
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects
of a generic class, we use the following syntax.
Output
GfG
15
Generic Functions:
We can also write generic functions that can be called with different types of arguments
based on the type of arguments passed to the generic method. The compiler handles each
method.
// Java program to show working of user defined
// Generic functions
class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName()
+ " = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
When we declare an instance of a generic type, the type argument passed to the type
parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type wrappers to
encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are reference
types.
ArrayList<int[]> a = new ArrayList<>();
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.
Container
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components. Containers are integral part of AWT
GUI components. A container provides a space where a component can be located. A
Container in AWT is a component itself and it adds the capability to add component to itself.
Following are noticable points to be considered.
Sub classes of Container are called as Containter. For example Panel, Frame
and Window.
Container can add only Component to itself.
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
AWTExample1.java
A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
Example 1:
ButtonExample.java
1. import java.awt.*;
2. public class ButtonExample {
3. public static void main (String[] args) {
4.
5. // create instance of frame with the label
6. Frame f = new Frame("Button Example");
7.
8. // create instance of button with label
9. Button b = new Button("Click Here");
10.
11. // set the position for the button in frame
12. b.setBounds(50,100,80,30);
13.
14. // add button to the frame
15. f.add(b);
16. // set size, layout and visibility of frame
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }
Java AWT Label
The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a user
cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To create a
label, we need to create the object of Label class.
In the following example, we are creating two labels l1 and l2 using the Label(String text)
constructor and adding them into the frame.
LabelExample.java
1. import java.awt.*;
2.
3. public class LabelExample {
4. public static void main(String args[]){
5.
6. // creating the object of Frame class and Label class
7. Frame f = new Frame ("Label example");
8. Label l1, l2;
9.
10. // initializing the labels
11. l1 = new Label ("First Label.");
12. l2 = new Label ("Second Label.");
13.
14. // set the location of label
15. l1.setBounds(50, 100, 100, 30);
16. l2.setBounds(50, 150, 100, 30);
17.
18. // adding labels to the frame
19. f.add(l1);
20. f.add(l2);
21.
22. // setting size, layout and visibility of frame
23. f.setSize(400,400);
24. f.setLayout(null);
25. f.setVisible(true);
26. }
27. }
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.
AWT Canvas class Declaration
1. public class Canvas extends Component implements Accessible
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.
The object of a TextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps us to
scroll the text up and down, or right and left.
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An
executable jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.
To create manifest file, you need to write Main-Class, then colon, then space, then classname
then enter. For example:
myfile.mf
1. Main-Class: First
As you can see, the mf file starts with Main-Class colon space class name. Here, class name
is First.
The jar tool provides many switches, some of them are as follows:
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given below:
Now it will create the executable jar file. If you double click on it, it will call
the main method of the First class.
In Java, an applet is a special type of program embedded in the web page to generate dynamic
content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.
There are five methods of an applet life cycle, and they are
1.init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
2.start(): The start() method contains the actual code of the applet and starts the applet. It is
invoked immediately after the init() method is invoked. Every time the browser is loaded or
refreshed, the start() method is invoked. It is also invoked whenever the applet is maximized,
restored, or moving from one tab to another in the browser.
o 3. stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
o An applet is a Java application executed in any web browser and works on the client-
side. It doesn't have the main() method because it runs in the browser. It is thus
created to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet
class. And thus, we can use all the methods of that class.
These methods are invoked by the browser automatically. There is no need to call them
explicitly.
To pass the parameters to the Applet we need to use the param attribute
of <applet> tag. Parameters are passed to applets in NAME=VALUE pairs in
<param> tags between the opening and closing APPLET tags.
To retrieve a parameter's value, we need to use the getParameter() method
of Applet class.
Event Handling:-
It is a mechanism to control the events and to decide what should happen after an
event occur. The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an event that is
mapped to a code to respond to functionality to the user. This is known as event handling.To
handle the events, Java follows the Delegation Event model.
In this model, the listener must be connected with a source to receive the event notifications.
Thus, the events will only be received by the listeners who wish to receive them.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated as
a reaction of a user while interacting with GUI elements. Some of the event generation
activities are moving the mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many other user operations as
events.
Event Sources
A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several different
types of events.
A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all
the events will be notified to registered listeners and receive the event object. This process is
known as event multicasting. In few cases, the event notification will only be sent to listeners
that register to receive them.
Some listeners allow only one listener to register. The source provides the methods to add or
remove listeners that generate the events. Below is an example of the method that will
remove the event from the listener.
From the above syntax, the Type is an event name, and e2 is the reference of the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several
resources to receive notification about the events. Second, it must implement the methods to
receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces can
be found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse is
dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.
The classes that represent events are at the core of Java’s event handling
mechanism.
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.
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
ComponentListener componentShown()
componentMoved()
componentHidden()
ContainerListener componentAdded()
componentRemoved()
FocusListener focusGained()
focusLost()
ItemListener itemStateChanged()
Listener Interface Methods
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
MouseMotionListener mouseMoved()
mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
windowActivated()
windowDeactivated()
windowOpened()
WindowListener windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
JDBC
We can use JDBC API to handle database using Java program and can perform the following
activities:
Type-1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the
ODBC function calls. Type-1 driver is also called Universal driver because it can be
used to connect to any of the databases.
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Type-2 driver
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver.
Driver needs to be installed separately in individual client machines
The Vendor client library needs to be installed on client machine.
Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
It is a database dependent driver.
Type-3 driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.
Type-3 drivers are fully written in Java, hence they are portable drivers.
No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
Switch facility to switch over from one database to another database.
Type-4 driver
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as
Thin Driver.
Does not require any native library and Middleware server, so no client-side or
server-side installation.
It is fully written in Java language, hence they are portable driver
Socket overview:-
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point,
stream-based connections between hosts on the Internet.
The mechanism for Socket Programming
A client creates a socket at its end of transmission and strives to connect the socket to the
server. When a connection is established, the server creates a socket at its end and, the client
and server can now ready communicate through writing and reading methods. Following is the
listening mode. This method won’t resume until a client is connected to the server
4. An attempt is made, for connecting the client to the server using the specified IP
address and port number. If the attempt is successful, the client is provided with
a Socket that is capable of communicating to the respective server, with write and
client.
6. Once the communication is completed, terminate the sockets on both, the server
Client-Side Programming
To connect to another machine we need a socket connection. A socket connection means
the two machines have information about each other’s network location (IP Address) and
TCP port. The java.net.Socket class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
The first argument – IP address of Server. ( 127.0.0.1 is the IP address of
localhost, where code will run on the single stand-alone machine).
The second argument – TCP Port. (Just a number representing which
application to run on a server. For example, HTTP runs on port 80. Port
number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the
data.
Closing the connection
The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until
“Over” is typed.
Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new
Socket())
A plain old Socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as well as
input/output streams.
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
the java.net package of the Java programming language includes various classes and
interfaces that provide an easy-to-use means to access network resources. Other than
classes and interfaces, the java.net package also provides support for the two well-known
network protocols. These are:
1. Transmission Control Protocol (TCP) – TCP or Transmission Control
Protocol allows secure communication between different applications. TCP is a
connection-oriented protocol which means that once a connection is established,
data can be transmitted in two directions. This protocol is typically used over the
Internet Protocol. Therefore, TCP is also referred to as TCP/IP.
2.User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less
protocol that allows data packets to be transmitted between different applications. UDP is a
simpler Internet protocol in which error-checking and recovery services are not required. In
UDP, there is no overhead for opening a connection, maintaining a connection, or
terminating a connection
In Java Networking, many terminologies are used frequently. These widely used Java
Networking Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a device on
the internet or a local network. IP stands for “Internet Protocol.” It comprises a
set of rules governing the format of data sent via the internet or local network. IP
Address is referred to as a logical address that can be modified.
Port Number – A port number is a method to recognize a particular process connecting
internet or other network information when it reaches a server. The port number is used to
identify different applications uniquely. The port number behaves as a communication
endpoint among applications. The port number is correlated with the IP address for
transmission and communication among two applications
Protocol – A network protocol is an organized set of commands that define how data is
transmitted between different devices in the same network. Network protocols are the
reason through which a user can easily communicate with people all over the world and
thus play a critical role in modern digital communications. For Example – TCP, FTP, POP,
etc
Socket – A socket is one endpoint of a two-way communication connection between the
two applications running on the network. The socket mechanism presents a method of inter-
process communication (IPC) by setting named contact points between which the
communication occurs. A socket is tied to a port number so that the TCP layer can
recognize the application to which the data is intended to be sent.
1. Connection-oriented and connection-less protocol – In a connection-oriented
service, the user must establish a connection before starting the communication.
When the connection is established, the user can send the message or the
information, and after this, they can release the connection. However, In
connectionless protocol, the data is transported in one route from source to
destination without verifying that the destination is still there or not or if it is
ready to receive the message. Authentication is not needed in the connectionless
protocol.
Example of Connection-oriented Protocol – Transmission Control
Protocol (TCP)
Example of Connectionless Protocol – User Datagram Protocol
(UDP)
Creating Thread
A thread is created either by "creating or implementing" the Runnable
Interface or by 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.
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)
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.
ThreadExample1.java
17. t1.start();
18. }
19. }
Output:
Let's takes an example to understand how we can create, start and run
the thread using the runnable interface.
ThreadExample2.java
Output:
New: Whenever a new thread is created, it is always in the new state. For
a thread in the new state, the code has not been run yet and thus has not
begun its execution.
Active: When a thread invokes the start() method, it moves from the new
state to the active state. The active state contains two states within it:
one is runnable, and the other is running.
For example, a thread (let's say its name is A) may want to print some
data from the printer. However, at the same time, the other thread (let's
say its name is B) is using the printer to print some data. Therefore,
thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state. A thread in the blocked state is unable to perform any
execution and thus never consume any cycle of the Central Processing
Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.
The following diagram shows the different states involved in the life cycle
of a thread.
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple
threads to any shared resource.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another
while sharing data. It can be achieved by using the following three ways:
TestSynchronization1.java
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. class TestSynchronization1{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }
Output:
5
100
10
200
15
300
20
400
25
500
TestSynchronization2.java
Output:
5
10
15
20
25
100
200
300
400
500
If we put all the codes of the method in the synchronized block, it will
work same as the synchronized method.
Points to Remember
Syntax
TestSynchronizedBlock1.java
1. class Table
2. {
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16.Table t;
17. MyThread1(Table t){
18.this.t=t;
19. }
20.public void run(){
21. t.printTable(5);
22.}
23.
24.}
25. class MyThread2 extends Thread{
26.Table t;
27. MyThread2(Table t){
28.this.t=t;
29. }
30.public void run(){
31. t.printTable(100);
32.}
33. }
34.
35. public class TestSynchronizedBlock1{
36.public static void main(String[] args){
37. Table obj = new Table();//only one object
38.MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40.t1.start();
41. t2.start();
42.}
43. }
Output:
5
10
15
20
25
100
200
300
400
500
Static Synchronization
If you make any static method as synchronized, the lock will be on the
class not on object.
o wait()
o notify()
o notifyAll()
wait() method
The wait() method causes current thread to release the lock and wait until
either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
2) notify() method
The notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them is
chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. Public class Test{
24. public static void main(String[] args){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }
34. }
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
The producer-consumer problem in java can also be solved with the help of threads. A
thread is a sequential flow of control in a program. The thread allows a program to
operate more efficiently by doing multiple things simultaneously with the help of threads.
All Java programs have at least one thread known as the main thread.
The producer has the initial value of 0. We have a synchronized block so that only a
producer or a consumer thread runs at a time. The produce function also checks if the list
is full, if it is full it gives up the intrinsic lock and on goes on a waiting state.
If the list is empty, then the producer adds an item to the list.
We have the notify() method to notify the consumer to start consuming items from the list
The consume function has a loop to get items from the list. The function checks if the list
is empty, if it is empty then the thread gives up the lock and transfers the control to the
producer thread to produce the item and add it to the list.
If the list is not empty, we remove the item from the list. We have the notify method to
notify the producer to produce the item. We add a sleep method at the end of both
producer and consumer methods so that the output is not shown at once and we can see
what is happening in the code.
We can change the value of capacity to change the size of the list. In our case, the list size
is 1.
We have the main class in which we create threads t1 and t2 for producer and consumer
respectively and then run both the threads.
import java.util.LinkedList;
// producer thread
@Override
try {
pc.produce();
catch (InterruptedException e) {
e.printStackTrace();
});
// consumer thread
@Override
try {
pc.consume();
catch (InterruptedException e) {
e.printStackTrace();
});
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
int capacity = 1;
int value = 0;
while (true) {
synchronized (this)
wait();
list.add(value++);
// to understand
Thread.sleep(1000);
while (true) {
synchronized (this)
while (list.size() == 0)
wait();
notify();
//sleep
Thread.sleep(1000);
Producer produced: 0
Consumer consumed: 0
Producer produced: 1
Consumer consumed: 1
Producer produced: 2
Consumer consumed: 2
Producer produced: 3
Consumer consumed: 3
Producer produced: 4
Consumer consumed: 4
Producer produced: 5
Consumer consumed: 5
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.
UNIT2-
Advantages of Inheritance
Flexibility: Inheritance makes the code flexible to change, as you will adjust
only in one place, and the rest of the code will work smoothly.
Overriding: With the help of Inheritance, you can override the methods of
the base class.
Data Hiding: The base class in Inheritance decides which data to be kept
private, such that the derived class will not be able to alter it.
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could
access maxSpeed of base class in subclass using super keyword.
The differences between Method Overloading and Method Overriding in Java are as
follows:
inheritance relationships.
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading, more than
one method shares the same method name with a different signature in the class. In method
overloading, the return type can or can not be the same, but we have to change the
parameter because, in java, we can not achieve the method overloading by changing only
the return type of the method.
Example of Method Overloading:
import java.io.*;
class MethodOverloadingEx {
Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, the derived class
provides the specific implementation of the method that is already provided by the base
class or parent class. In method overriding, the return type must be the same or co-variant
(return type may vary in the same direction as the derived class).
Example: Method Overriding
import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}
void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
Output
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Output explanation: Here, we can see that a method eat() has overridden in the derived
class name Dog that is already provided by the base class name Animal. When we create
the instance of class Dog and call the eat() method, we see that only derived class eat()
method run instead of base class method eat(), and When we create the instance of class
Animal and call the eat() method, we see that only base class eat() method run instead of
derived class method eat().
Static binding focuses on the reference type and determines the method call
during compilation itself. On the contrary, dynamic binding focuses on the type of
object and the method call can be determined only during the runtime.
import java.io.*;
//Creating a parent class
class MobileOS{
//virtual method
void display()
{
System.out.println("Mobile Operating System");
}
}
//Main class
class Main {
//calling main method
public static void main (String[] args) {
Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.
// A simple interface
interface Player
{
final int id = 10;
int move();
}
In class, you can instantiate variables and In an interface, you can’t instantiate
1.
create an object. variables and create an object.
The access specifiers used with classes In Interface only one specifier is used-
3.
are private, protected, and public. Public.
import java.io.*;
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12.A7 obj = new A7();
13. obj.print();
14.obj.show();
15. }
16.}
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10.public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12.obj.print();
13. }
14.}
Output:
Hello
As you can see in the above example, Printable and Showable interface
have same methods but its implementation is provided by class
TestTnterface1, so there is no ambiguity.
Java Package
A java package is a group of similar types of classes, interfaces and sub-
packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
Advantage of Java Package
// Main Class
class GFG {
// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");
Input
Enter Your Name:
geeksforgeeks
Output
Your Name is : geeksforgeeks
Now in order to create a package in java follow the certain steps as described below:
1. First We Should Choose A Name For The Package We Are Going To Create
And Include. The package command In The first line in the java program source
code.
2. Further inclusion of classes, interfaces, annotation types, etc that is required in
the package can be made in the package. For example, the below single
statement creates a package name called “FirstPackage”.
Syntax: To declare the name of the package to be created. The package statement simply
defines in which package the classes defined belong.
package FirstPackage ;
Implementation: To Create a Class Inside A Package
1. First Declare The Package Name As The First Statement Of Our Program.
2. Then We Can Include A Class As A Part Of The Package.
So Inorder to generate the above-desired output first do use the commands as specified use
the following specified commands
Procedure:
1. To generate the output from the above program
Command: javac Welcome.java
2. The Above Command Will Give Us Welcome.class File.
Command: javac -d . Welcome.java
3. So This Command Will Create a New Folder Called FirstPackage.
Command: java FirstPackage.Welcome
Output: The Above Will Give The Final Output Of The Example Program
// Print message
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
If an exception occurs at the particular statement in the try block, the rest
of the block code will not execute. So, it is recommended not to keep the
code in try block that will not throw an exception.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the
parent class exception ( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
MultipleCatchBlock1.java
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:
TestThrow3.java
1. // class represents user-defined exception
2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-
defined exception");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }
Output:
Testthrows3.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//
declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of the code...");
18. }
19. }
Output:
Aim:- Create a user defined Exception class which throws Exception
when the user inputs the marks greater than 100.
Coding:-
import java.util.*;
class myexception extends Exception
{
myexception(String s)
{
super(s);
}
}
class Test
{
public static void main(String argv[])throws myexception
{
int marks=sc.nextInt();
else
{
System.out.println("Marks: "+marks);
}
}
Aim:- Write a program which throws Arithmetic Exception. Write
another class (in a different file) that handles the exception.
Coding:-
public class Test
{
public static void main(String args[])
{
int a =10, b = 0, c;
System.out.println("Welcome");
try
{
c = a/b;
System.out.println(c);
catch(ArithmeticException e)
{
}
Differences between Checked and Unchecked
Exceptions in Java
S.No
. Checked Exception Unchecked Exception
The checked exception is checked by the These types of exceptions are not
2. compiler. checked by the compiler.
3. Checked exceptions can be created manually. They can also be created manually.
Java Virtual Machine requires the exception to Java Virtual Machine does not need the
5. to be caught or handled. exception to be caught or handled.