Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Notes

Uploaded by

aman sehgal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Notes

Uploaded by

aman sehgal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

LAYOUT MANAGERS:-

 The LayoutManagers are used to arrange components in a particular manner.


The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms. LayoutManager is an interface that is implemented by all
the classes of layout managers. There are the following classes that represent the
layout managers:

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Java GridLayout

The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class

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.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class

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:

Note: The BoxLayout class is found in javax.swing package.

Fields of BoxLayout Class

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.

Constructor of BoxLayout class

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.

Constructors of CardLayout Class

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.

Commonly Used Methods of CardLayout Class

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.

The GroupLayout class provides methods such as createParallelGroup() and


createSequentialGroup() to create groups.

Constructors

GroupLayout(Container host) It creates a GroupLayout for the specified Container.

Java SpringLayout

A SpringLayout arranges the children of its associated container according to a set of


constraints. Constraints are nothing but horizontal and vertical distance between two-
component edges. Every constraint is represented by a SpringLayout.Constraint object.

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:

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.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the server) and
a client program (resides on the client).
 Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
 The client program requests the remote objects on the server and tries to
invoke its methods.
The following diagram shows the architecture of an RMI application.

 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.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

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

Simple Java Swing Example

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

The hierarchy of java swing API is given below.

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.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible


Java JLabel

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.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible


Java JTextField

The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.

JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants


Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.

JScrollBar class declaration

Let's see the declaration for javax.swing.JScrollBar class.

1. public class JScrollBar extends JComponent implements Adjustable, Accessible


Java JComboBox

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.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListData


Listener, ActionListener, Accessible
Java JTabbedPane

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.

JTabbedPane class declaration

Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible,


SwingConstants
Java JScrollPane

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.

JTree class declaration

Let's see the declaration for javax.swing.JTree class.

1. public class JTree extends JComponent implements Scrollable, Accessible

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.

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety:

2) Type casting is not required: There is no need to typecast the object.


3) Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at compile
time than runtime. Suppose you want to create an ArrayList that store name of students, and
if by mistake the programmer adds an integer object instead of a string, the compiler allows
it. But, when we retrieve this data from ArrayList, it causes problems at runtime
4. Generics Promotes Code Reusability: With the help of generics in Java, we can write
code that will work with different types of data. We can write a method/class/interface once
and use it for any type we want.
5.Implementing Generic Algorithms: By using generics, we can implement algorithms
that work on different types of objects, and at the same, they are type-safe too.

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.

// To create an instance of generic class


BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
// Java program to show working of user defined
// Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

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);

// Calling generic method with String argument


genericDisplay("GeeksForGeeks");

// Calling generic method with double argument


genericDisplay(1.0);
}
}
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0

Generics Work Only with Reference Types:

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 (Abstract Window Toolkit)

is an API to develop Graphical User Interface (GUI) or windows-based applications in Java.

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.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Components

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.

There are four types of containers in Java AWT:

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

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // extending Frame class to our class AWTExample1
5. public class AWTExample1 extends Frame {
6.
7. // initializing using constructor
8. AWTExample1() {
9.
10. // creating a button
11. Button b = new Button("Click Me!!");
12.
13. // setting button position on screen
14. b.setBounds(30,100,80,30);
15.
16. // adding button into frame
17. add(b);
18.
19. // frame size 300 width and 300 height
20. setSize(300,300);
21.
22. // setting the title of Frame
23. setTitle("This is our basic AWT example");
24.
25. // no layout manager
26. setLayout(null);
27.
28. // now frame will be visible, by default it is not visible
29. setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[]) {
34.
35. // creating instance of Frame class
36. AWTExample1 f = new AWTExample1();
37.
38. }
39.
40. }
Java AWT Button

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.

AWT Button Class Declaration


1. public class Button extends Component implements Accessible
Java AWT Button Example

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.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible
Java AWT Label Example

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.

AWT TextField Class Declaration


1. public class TextField extends TextComponent

The AWT TextField class inherits the methods from below classes:

1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object

Java AWT Canvas

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.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible
Java AWT List

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.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible
Java AWT TextArea

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.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent

How to make an executable jar file in Java

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.

Creating 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.

In mf file, new line is must after the class name.


Creating executable jar file using jar tool

The jar tool provides many switches, some of them are as follows:

1. -c creates new archive file


2. -v generates verbose output. It displays the included or extracted resource on the
standard output.
3. -m includes manifest information from the given mf file.
4. -f specifies the archive file name
5. -x extracts files from the archive file

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:

1. jar -cvmf myfile.mf myjar.jar First.class

Now it will create the executable jar file. If you double click on it, it will call
the main method of the First class.

Applet Life Cycle in Java

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.

Methods of Applet Life Cycle

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.

Flow of Applet Life Cycle:

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:-

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.

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.

Basically, an Event Model is based on the following three components:

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:

1. public void addTypeListener (TypeListener e1)

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.

1. public void removeTypeListener(TypeListener e2?)

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 design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.
Event Classes in Java

The classes that represent events are at the core of Java’s event handling
mechanism.

Following is the list of commonly used event classes.

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 an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size changed
or changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a container
object.

These are focus-related events, which


FocusEvent FocusListener include 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.
Event Class Listener Interface Description

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

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.

Listener Interface Methods

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:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

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

elaborated procedure of what happens when a TCP connection is established:

1. An object of ServerSocket is instantiated, and desired port number is specified, on

which connection is going to take place.

2. The accept method of ServerSocket is invoked, in order to hold the server in

listening mode. This method won’t resume until a client is connected to the server

through the given port number.

3. Now, on the client-side, an object of Socket is instantiated, and desired port

number and IP address is specified for the connection.

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

read methods. If unsuccessful, the desired exception is raised.

5. Since a client is connected to the server, accept method on the server-side


resumes, providing a Socket that is capable of communicating to the connected

client.

6. Once the communication is completed, terminate the sockets on both, the server

and the client-side.

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.

// A Java program for a Client


import java.io.*;
import java.net.*;

public class Client {


// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to put ip address and port


public Client(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");

// takes input from terminal


input = new DataInputStream(System.in);

// sends output to the socket


out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}

// string to read message from input


String line = "";

// keep reading until "Over" is input


while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}

// close the connection


try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}

public static void main(String args[])


{
Client client = new Client("127.0.0.1", 5000);
}
}

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.

// A Java program for a Server


import java.net.*;
import java.io.*;

public class Server


{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");

System.out.println("Waiting for a client ...");


socket = server.accept();
System.out.println("Client accepted");

// takes input from the client socket


in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent


while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);

}
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);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

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

Java Networking Terminology

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)

Java Networking classes


The java.net package of the Java programming language includes various classes that
provide an easy-to-use means to access network resources. The classes covered in
the java.net package are given as follows –

1. CacheRequest – The CacheRequest class is used in java whenever there is a


need to store resources in ResponseCache.

2. CookieHandler – The CookieHandler class is used in Java to implement a callback


mechanism for securing up an HTTP state management policy implementation
inside the HTTP protocol handler.
3. The CookieManager class is used to provide a precise implementation of
CookieHandler. This class separates the storage of cookies from the policy
surrounding accepting and rejecting cookies.
4. The DatagramPacket class is used to provide a facility for the connectionless
transfer of messages from one system to another. This class provides tools for the
production of datagram packets for connectionless transmission by applying the
datagram socket class.
5. The InetAddress class is used to provide methods to get the IP address of any
hostname.
6. The ServerSocket class is used for implementing 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
7. 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 java.net.Socket class
8. The DatagramSocket class is a network socket that provides a connection-less point
for sending and receiving packets. Every packet sent from a datagram socket is
individually routed and delivered. It can further be practiced for transmitting and
accepting broadcast information
9. A proxy is a changeless object and a kind of tool or method or program or system,
which serves to preserve the data of its users and computers. It behaves like a wall
between computers and internet users. A Proxy Object represents the Proxy settings
to be applied with a connection.
10. 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.
11. The URLConnection class in Java is an abstract class describing a connection of a
resource as defined by a similar URL. The URLConnection class is used for
assisting two distinct yet interrelated purposes. Firstly it provides control on
interaction with a server(especially an HTTP server) than a URL class. Furthermore,
with a URLConnection, a user can verify the header transferred by the server and
can react consequently

Java Networking Interfaces


The java.net 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 java.net package are as follows:
1. CookiePolicy – The CookiePolicy interface in the java.net package provides the
classes for implementing various networking applications. It decides which
cookies should be accepted and which should be rejected
2.A CookieStore is an interface that describes a storage space for cookies.
CookieManager combines the cookies to the CookieStore for each HTTP response and
recovers cookies from the CookieStore for each HTTP request.
3.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.

4.SocketImplFactory – The SocketImplFactory interface defines a factory for


SocketImpl instances. It is used by the socket class to create socket implementations
that implement various policies.

5.ProtocolFamily – This interface represents a family of communication protocols. The


ProtocolFamily interface contains a method known as name(), which returns the name
of the protocol family.

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.

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.

Let's dive into details of both these way of creating 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)

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 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:

ThreadExample1.java

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()
5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. System.out.println("Thread started running..");
10. System.out.println("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. t1.start();
18. }
19. }

Output:

Creating thread by implementing the runnable interface


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.

ThreadExample2.java

1. class NewThread implements Runnable {


2. String name;
3. Thread thread;
4. NewThread (String name){
5. this.name = name;
6. thread = new Thread(this, name);
7. System.out.println( "A New thread: " + thread+ "is created\n" )
;
8. thread.start();
9. }
10. public void run() {
11. try {
12. for(int j = 5; j > 0; j--) {
13. System.out.println(name + ": " + j);
14. Thread.sleep(1000);
15. }
16. }catch (InterruptedException e) {
17. System.out.println(name + " thread Interrupted");
18. }
19. System.out.println(name + " thread exiting.");
20. }
21. }
22.class ThreadExample2 {
23. public static void main(String args[]) {
24. new NewThread("1st");
25. new NewThread("2nd");
26. new NewThread("3rd");
27. try {
28. Thread.sleep(8000);
29. } catch (InterruptedException excetion) {
30. System.out.println("Inturruption occurs in Main Thread");
31. }
32. System.out.println("We are exiting from Main Thread");
33. }
34.}

Output:

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These
states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

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.

o Runnable: A thread, that is ready to run is then moved to the


runnable state. In the runnable state, the thread may be running or
may be ready to run at any at any given instant of time. It is the
duty of the thread scheduler to provide the thread time to run, i.e.,
moving the thread the running state.
A program implementing multithreading acquires a fixed slice of
time to each individual thread. Each and every thread runs for a
short span of time and when that allocated time slice is over, the
thread voluntarily gives up the CPU to the other thread, so that the
other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the
runnable to the running state. Generally, the most common change
in the state of a thread is from runnable to running and again back
to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time


(not permanently) then, either the thread is in the blocked state or is in
the waiting state.

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.

Timed Waiting: Sometimes, waiting for leads to starvation. For example,


a thread (its name is A) has entered the critical section of a code and is
not willing to leave that critical section. In such a scenario, another thread
(its name is B) has to wait forever, which leads to starvation. To avoid
such scenario, a timed waiting state is given to thread B. Thus, thread lies
in the waiting state for a specific span of time, and not forever. A real
example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and start its execution
from when it has left earlier.

Terminated: A thread reaches the termination state because of the


following reasons:

o When a thread has finished its job, then it exists or terminates


normally.
o Abnormal termination: It occurs when some unusual events such
as an unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other


words, the thread is dead, and there is no way one can respawn (active
after kill) the dead thread.

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.

Java Synchronization is better option where we want to allow only one


thread to access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

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:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or
monitor. Every object has a lock associated with it. By convention, a
thread that needs consistent access to an object's fields has to acquire
the object's lock before accessing them, and then release the lock when
it's done with them.

In this example, there is no synchronization, so output is inconsistent.


Let's see the example:

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

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized
method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires


the lock for that object and releases it when the thread completes its task.

TestSynchronization2.java

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String[] args){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output:

5
10
15
20
25
100
200
300
400
500

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any
specific resource of the method.

Suppose we have 50 lines of code in our method, but we want to


synchronize only 5 lines, in such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will
work same as the synchronized method.

Points to Remember

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.
o A Java synchronized block doesn't allow more than one JVM, to provide
access control to a shared resource.
o The system performance may degrade because of the slower working of
synchronized keyword.
o Java synchronized block is more efficient than Java synchronized method.

Syntax

1. synchronized (object reference expression) {


2. //code block
3. }

Example of Synchronized Block


Let's see the simple example of synchronized block.

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.

Problem without static synchronization


Suppose there are two objects of a shared class (e.g. Table) named
object1 and object2. In case of synchronized method and synchronized
block there cannot be interference between t1 and t2 or t3 and t4
because t1 and t2 both refers to a common object that have a single lock.
But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock. We don't want
interference between t1 and t3 or t2 and t4. Static synchronization solves
this problem.

Example of Static Synchronization


In this example we have used synchronized keyword on the static
method to perform static synchronization.

Inter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a


thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:

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:

1. public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. public final void notifyAll()

Let's see the simple example of inter thread communication.

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

Producer-Consumer Solution using Threads in Java

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.

The full java code will look like this:


// Java program to implement the solution of producer consumer problem.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) throws InterruptedException

// Object of a class that has both produce()

// and consume() methods

final PC pc = new PC();

// producer thread

Thread t1 = new Thread(new Runnable() {

@Override

public void run()

try {

pc.produce();

catch (InterruptedException e) {

e.printStackTrace();

});
// consumer thread

Thread t2 = new Thread(new Runnable() {

@Override

public void run()

try {

pc.consume();

catch (InterruptedException e) {

e.printStackTrace();

});

// Start both threads

t1.start();

t2.start();

// t1 finishes before t2

t1.join();

t2.join();

// This class has a list, producer, and consumer.


public static class PC {

// list shared by producer and consumer

// Size of the list is 1.

LinkedList<Integer> list = new LinkedList<>();

int capacity = 1;

// Function called by producer thread

public void produce() throws InterruptedException

int value = 0;

while (true) {

synchronized (this)

// producer thread waits while list is full

while (list.size() == capacity)

wait();

System.out.println("Producer produced: "+ value);

// to insert the jobs in the list

list.add(value++);

// notifies the consumer thread that

// now it can start consuming


notify();

// makes the working of program easier

// to understand

Thread.sleep(1000);

// Function called by consumer thread

public void consume() throws InterruptedException

while (true) {

synchronized (this)

// consumer thread waits while list is empty

while (list.size() == 0)

wait();

// to retrieve the first job in the list

int val = list.removeFirst();

System.out.println("Consumer consumed: "+ val);

// Wake up producer thread

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

Thread Class Methods

Thread class also defines many methods for managing


threads. Some of them are,
There are several ways to read a plain text file in Java e.g. you can
use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides
something special e.g. BufferedReader provides buffering of data for fast reading, and
Scanner provides parsing ability.
Methods:
1. Using BufferedReader class
2. Using Scanner class
3. Using File Reader class
we will see different ways of writing into a File using Java Programming language.
Java FileWriter class in java is used to write character-oriented data to a file as this class is
character-oriented class because of what it is used in file handling in java.
There are many ways to write into a file in Java as there are many classes and methods
which can fulfill the goal as follows:
1. Using writeString() method
2. Using FileWriter Class
3. Using BufferedWriter Class
4. Using FileOutputStream Class
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String
objects. The StringBuffer class in Java is the same as String class except it
is mutable i.e. it can be changed.It is synchronized.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously

Important methods of StringBuffer class


StringBufferExample.java

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. }

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive
into object and object into primitive.

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.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc.
Let us see the different scenarios, where we need to use the wrapper
classes.
o Change the value in Method: Java supports only call by value. So, if we
pass a primitive value, it will not change the original value. But, if we
convert the primitive value in an object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility classes to
deal with objects.
o Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList, Vector,
HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal
with objects only.

UNIT2-

Advantages of Inheritance

Minimizing duplicate code: Key benefits of Inheritance include minimizing


the identical code as it allows sharing of the common code among other
subclasses.

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.

 In Java, the super keyword is used to refer to the parent class


of a subclass. Overall, the super keyword is a powerful tool for
subclassing in Java, allowing subclasses to inherit and build
upon the functionality of their parent classes.
The super keyword in java is a reference variable that is used
to refer to parent class objects

// Java code to show use of super keyword with variables


// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

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:

Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

It is used to grant the specific


It helps to increase the readability of the implementation of the method which is
program. already provided by its parent class or
superclass.

It occurs within the class. It is performed in two classes with


Method Overloading Method Overriding

inheritance relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods must


In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return type


In method overriding, the return type must be
can or can not be the same, but we just
the same or co-variant.
have to change the parameter.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The reason


Poor Performance due to compile time
behind this is that the binding of overridden
polymorphism.
methods is being done at runtime.

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 {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

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.");
}
}

class Dog extends Animal {

void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}

class MethodOverridingEx {

public static void main(String args[])


{
Dog d1 = new Dog();
Animal a1 = new Animal();
d1.eat();
a1.eat();

Animal animal = new Dog();


// eat() method of animal class is overridden by
// base class eat()
animal.eat();
}
}

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().

 Dynamic Method Dispatch or Runtime Polymorphism in Java is a way by


which Java Virtual Machine (JVM) determines which version of the same method
in the inherited classes should be called ruing the runtime.
 It follows dynamic or late binding where the method call will be done according
to the type of object being referred to and not the reference variable.

 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");
}
}

//Creating a child class for parent 'MobileOS'


class Android extends MobileOS{

//overriding display method


void display()
{
System.out.println("Android is a MobileOS.");
}
}

//Creating a child class for parent 'MobileOS'


class iOS extends MobileOS{

//overriding display method


void display()
{
System.out.println("iOS is a MobileOS.");
}
}

//Main class
class Main {
//calling main method
public static void main (String[] args) {

//Create an object of parent class


MobileOS os = new MobileOS();
os.display();

//Create an object of child class


os=new Android(); //Upcasting
os.display();

//Create an object of child class


os=new iOS(); //Upcasting
os.display();
}
}

Mobile Operating System


Android is a MobileOS.
iOS is a MobileOS.

An Interface in Java programming language is defined as an abstract type used to specify


the behavior of a class. An interface in Java is a blueprint of a behaviour. A Java interface
contains static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritance in Java . In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method body. Java Interface
also represents the IS-A relationship.
When we decide a type of entity by its behaviour and not via attribute we should define it
as an interface.
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

 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();
}

Difference Between Class and Interface

The major differences between a class and an interface are:


S.
No. Class Interface

In class, you can instantiate variables and In an interface, you can’t instantiate
1.
create an object. variables and create an object.

The interface cannot contain


Class can contain concrete(with
2. concrete(with implementation)
implementation) methods
methods

The access specifiers used with classes In Interface only one specifier is used-
3.
are private, protected, and public. Public.

Implementation: To implement an interface we use the keyword implements

// Java program to demonstrate working of


// interface

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// 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

Q) Multiple inheritance is not supported through class in


java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is
not supported in the case of class because of ambiguity. However, it is
supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class. For
example:

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 is a mechanism to encapsulate a group of classes, sub-packages, and


interfaces.

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

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Syntax: To import a package


import package.name.*;
Example: To import a package
// Java Program to Import a package

// Importing java utility package


import java.util.*;

// Main Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Scanner to take input from the user object


Scanner myObj = new Scanner(System.in);
String userName;

// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");

// Reading the integer age entered using


// nextInt() method
userName = myObj.nextLine();

// Print and display


System.out.println("Your Name is : " + userName);
}
}

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.

// Name of package to be created


package FirstPackage;

// Class in which the above created package belong to


class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
System.out.println(
"This Is The First Program Geeks For Geeks..");
}
}

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

// Name of package to be created


package data;

// Class to which the above package belongs


public class Demo {

// Member functions of the class- 'Demo'


// Method 1 - To show()
public void show()
{

// Print message
System.out.println("Hi Everyone");
}

// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}

Java try block


Java try block is used to enclose the code that might throw an exception.
It must be used within the method.

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.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

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

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16.}

Output:

java.lang.ArithmeticException: / by zero
rest of the code

Java Multi-catch block


A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
catch block.

Let's see a simple example of java multi-catch block.

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:

Arithmetic Exception occurs

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has


some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.

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:

Java throws keyword


Syntax of Java throws

1. return_type method_name() throws exception_class_name{


2. //method code
3. }

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:

device operation performed


normal flow...

Java finally block


Java finally block is a block used to execute important code such as
closing the connection, etc.

Java finally block is always executed whether an exception is handled or


not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.

The finally block follows the try-catch block.


o finally block in Java can be used to put "cleanup" code such as
closing a file, closing connection, etc.
o The important statements to be printed can be placed in the finally
block.

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
{

System.out.print("Enter marks: ");

Scanner sc = new Scanner(System.in);

int marks=sc.nextInt();

if( marks > 100 )


{
throw new myexception ("Input marks greater than 100 ");
}

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)
{

System.out.println("Cannot divide by zero!" + e );

}
Differences between Checked and Unchecked
Exceptions in Java
S.No
. Checked Exception Unchecked Exception

Checked exceptions happen at compile time Unchecked exceptions happen at


when the source code is transformed into an runtime when the executable program
1. executable code. starts running.

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.

This exception happens in runtime,


This exception is counted as a sub-class of the and hence it is not included in the
4. class. exception class.

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.

You might also like