0% found this document useful (0 votes)
9 views

Notes Advance java -

The document outlines a course on Advanced Java, specifically focusing on the Abstract Window Toolkit (AWT) for developing graphical user interfaces. It details various AWT components, containers, and classes, explaining their functionalities and how they interact within a Java application. Additionally, it provides examples of creating AWT applications using inheritance and association with the Frame class.

Uploaded by

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

Notes Advance java -

The document outlines a course on Advanced Java, specifically focusing on the Abstract Window Toolkit (AWT) for developing graphical user interfaces. It details various AWT components, containers, and classes, explaining their functionalities and how they interact within a Java application. Additionally, it provides examples of creating AWT applications using inheritance and association with the Frame class.

Uploaded by

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

Course Title:- Advance Java

Course Code: U-ADJ-482

Lab- Course-XIV (Advance Java)

Course code: U-LAC-486

Unit I

1. Introduction to AWT: Working with windows, Graphics Text:

1. AWT Classes:

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. The AWT tutorial will help the user to understand Java GUI
programming in simple and easy steps.
Why AWT is platform dependent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.For example, an AWT GUI with components like
TextField, label and button will have different look and feel for the different platforms like Windows,
MAC OS, and Unix. The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components. In simple words, an AWT
application will look like a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.

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

The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
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.

Types of containers:

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.

AWT Classes

The AWT classes are contained in the java.awt package.

It is one of Java’s largest packages. Fortunately, because it is logically organized in a

top-down, hierarchical fashion, it is easier to understand and use.

Class : Description
AWTEvent :

Encapsulates AWT events.

BorderLayout :

The border layout manager. Border layouts use five componentsNorth, South, East, West,

and Center.

Button :

Creates a push button control.

Canvas :

A blank, semantics-free window.

Checkbox :

Creates a check box control.

CheckboxGroup :

Creates a group of check box controls.

Choice :

Creates a pop-up list.

Color :
Manages colors in a portable, platform-independent fashion.

Component :

An abstract superclass for various AWT components.

Container :

A subclass of Component that can hold other components.

Dialog : kkk

Creates a dialog window.

FileDialog :

Creates a window from which a file can be selected.

Font :

Encapsulates a type font.

Frame :

Creates a standard window that has a title bar, resize corners, and a menu bar.

Graphics :

Encapsulates the graphics context. This context is used by the various output methods to

display output in a window.


Image : Encapsulates graphical images.

Label : Creates a label that displays a string.

List : Creates a list from which the user can choose. Similar to the standard Windows list box.

Menu : Creates a pull-down menu.

MenuBar : Creates a menu bar.

MenuComponent : An abstract class implemented by various menu classes.

MenuItem : Creates a menu item.

Panel : The simplest concrete subclass of Container.

PopupMenu : Encapsulates a pop-up menu.

Rectangle : Encapsulates a rectangle.

Scrollbar : Creates a scroll bar control.

ScrollPane : A container that provides horizontal and/or vertical scroll bars for anothe
component.

SystemColor : Contains the colors of GUI widgets such as windows, scroll bars, text, and others.

TextArea : Creates a multiline edit control.

TextComponent : A superclass for TextArea and TextField.

TextField : Creates a single-line edit control.


Toolkit : Abstract class implemented by the AWT.

Window : Creates a window with no frame, no menu bar, and no title.

Component

At the top of the AWT hierarchy is the Component class. Component is an abstract class

that encapsulates all of the attributes of a visual component. Except for menus, all user
interface elements that are displayed on the screen and that interact with the user are

subclasses of Component. It defines over a hundred public methods that are responsible

for managing events, such as mouse and keyboard input, positioning and sizing the window,

and repainting.A Component object is responsible for remembering the current foreground

and background colors and the currently selected text font.

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels

etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.

The Container class is a subclass of Component. It has additional methods that allow
other Component objects to be nested within it. Other Container objects can be stored inside

of a Container (since they are themselves instances of Component). This makes for a

multileveledcontainment system. A container is responsible for laying out

(that is, positioning) any components that it contains.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have

other components like button, textfield etc.

The Panel class is a concrete subclass of Container. A Panel may be thought of as a

recursively nestable, concrete screen component. Panel is the superclass for Applet. When

screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence,

a Panel is a window that does not contain a title bar, menu bar, or border. This is why you

don’t see these items when an applet is run inside a browser. When you run an applet using

an applet viewer, the applet viewer provides the title and border.

Other components can be added to a Panel object by its add( ) method (inherited from

Container). Once these components have been added, you can position and resize them
manually using the setLocation( ), setSize( ), setPreferredSize( ), or setBounds( )

methods defined by Component.

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.

The Window class creates a top-level window. A top-level window is not contained within

any other object; it sits directly on the desktop. Generally, you won’t create Window

objects directly. Instead, you will use a subclass of Window called Frame.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have

other components like button, textfield etc.


Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window

and has a title bar, menu bar, borders, and resizing corners. The precise look of a Frame will

differ among environments.

Canvas

Although it is not part of the hierarchy for applet or frame windows, there is one
other type of window that you will find valuable: Canvas. Derived from
Component, Canvas encapsulates a blank window upon which you can draw.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Graphics Class

In GUI applications, we can use Graphics class of java.awt


package to create various graphics like lines, rectangles, circles,
polygons etc. Let’s look at some of the methods available in the
Graphics class:
1.void drawLine(int startX, startY, endX, endY):
– Used to draw a line between two points.

void drawRect(int startX, int startY, int width, int height) :


Used to draw a rectangle starting from the top left corner with
the given width and height. The coordinates of the top left
corner of the rectangle are startX and startY.

void fillRect(int startX, int startY, int width, int height) – Used to
draw a solid (colored) rectangle with the given parameters.

void drawRoundRect(int startX, int startY, int width, int height,


int xDiam, int yDiam) – Used to draw a rounded rectangle
whose x-diameter and y-diameter of the corners is given by
xDiam and yDiam respectively.

void fillRoundRect(int startX, int startY, int width, int height, int
xDiam, int yDiam) – Used to draw a solid (colored) rounded
rectangle whose x-diameter and y-diameter of the corners is
given by xDiam and yDiam respectively.

void drawOval(int startX, int startY, int width, int height) – Used
to draw an ellipse inside an imaginary rectangle whose
dimensions are specified by the given parameters. We can get a
circle by giving the same value for both width and height.

void fillOval(int startX, int startY, int width, int height) – Used
to draw a solid (colored) ellipse inside an imaginary rectangle
whose dimensions are specified by the given parameters. We
can get a circle by giving the same value for both width and
height.

void drawArc(int startX, int startY, int width, int height, int
startAngle, int sweepAngle) – Used to draw an arc inside an
imaginary rectangle. The start angle and the sweep angle are
specified by using startAngle and sweepAngle respectively.

void fillArc(int startX, int startY, int width, int height, int
startAngle, int sweepAngle) – Used to draw a solid (colored) arc
inside an imaginary rectangle. The start angle and the sweep
angle are specified by using startAngle and sweepAngle
respectively.

void drawPolygon(int x[], int y[], int numPoints) – Used to draw


a polygon whose x coordinates and y coordinates of the points
are specified using the x array and y array respectively. Number
of points are specified using numPoints.
void fillPolygon(int x[], int y[], int numPoints) – Used to draw a
solid (colored) polygon whose x coordinates and y coordinates
of the points are specified using the x array and y array
respectively. Number of points are specified using numPoints.

Working with Color:


AWT provides java.awt.Color class that enables to specify and work
with different colors.
Color class defines some constant to specify a number of common colors
(for example - Color.RED/Color.red, Color.GREEN/ Color.green,
Color.PINK/Color.pink etc).
Note - Color class supports both uppercase and lowercase color
constants.
Color class also have several constructors to specify your own colors.
Some popular one is as follows -

1- public Color(int r, int g, int b ) -

where r, g, b indicates the red, green and blue colors whose values must
be between 0 and 255.
if r, g or b are outside of the range 0 to 255 it will throw an
IllegalArgumentException.

Example -
Color c1 = new Color(0, 0, 0); // Black color
Color c2 = new Color(255, 255, 255); //White
Color
Color c3 = new Color(100, 0 ,0); // Light red
color
2- public Color(float r, float g, float b) -

where r, g, b indicates the red, green and blue colors whose values must
be between 0.0 and 1.0.
if r, g or b are outside of the range 0.0 to 1.0, it will throw an
IllegalArgumentException .

Example -
Color c1 = new Color(0.0f, 0.0f, 0.0f); // Black
color
Color c2 = new Color(1.0f, 1.0f, 1.0f); // White
color
Color c3 = new Color(0.5f, 0.0f, 0.0f);//Light
red color

3- public Color(int rgb) -

It will creates a color with the specified combined RGB value consisting
of the red component in bits 16-23, the green component in bits 8-15,
and the blue component in bits 0-7.

Example -
Color c = new Color(0xff0000); // Red color
Color c = new Color(0x00ff00); //Green color
Color c = new Color(0x0000ff); // Blue color

Setting the current graphics color -

You can change the color of graphics you are drawing by using Graphics
class setColor() method. It has the following syntax -
public abstract void setColor(Color c)

Where c is new rendering color.


Working with Fonts -

You can select the font style of your choice by using Font class of
java.awt package.

Font class support the following constructor to create a new font -


public Font(String name, int style, int size)
Where -
name specifies the font name. The font name can be a font face name
or a font family name.

Font style can have one of the following three values ? Font.BOLD,
Font.PLAIN, Font.ITALIC. We can also combine these styles.

For example if we want bold and italic then we can combine Font.BOLD
+ Font.ITALIC.
size specifies the font size.

Using Fonts -
After creating new font, you can use it by using setFont() method.

It has the following syntax -


public abstract void setFont(Font fontObj)

Where fontObj specifies the new font you created.

Font f1 = new Font("Dialog",Font.BOLD +


Font.ITALIC, 35);
g.setFont(f1);
g.drawString("This is juat a demo", 100,
100);

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in
AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.

import java.awt.*;

class Simple

Simple()

Frame f1=new Frame();

f1.setSize(500,1500);

f1.setTitle("my frame");

f1.setVisible(true);

f1.setLayout(null);

public static void main(String aks[])

new Simple();
}

AWTExample1.java

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

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

// creating instance of Frame class


AWTExample1 f = new AWTExample1();
}

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.

AWTExample2.java

// importing Java AWT class


import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

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

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Steps to perform Event Handling
Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class


import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class

import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

2. Windows Fundamentals:

Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality
and specificity with each level. The two most common windows are those derived
from Panel, which is used by applets, and those derived from Frame, which creates
a standard application window. Much of the functionality of these windows is
derived from their parent classes. Thus, a description of the class hierarchies
relating to these two classes is fundamental to their understanding. Figure shows the

class hierarchy for Panel and Frame. Component

At the top of the AWT hierarchy is the Component class. Component is an


abstract class that encapsulates all of the attributes of a visual component. Except
for menus, all user interface elements that are displayed on the screen and that
interact with the user are
subclasses of Component. It defines over a hundred public methods that are
responsible for managing events, such as mouse and keyboard input, positioning
and sizing the window, and repainting. A Component object is responsible for
remembering the current foreground and background colors and the currently
selected text font.

Container

The Container class is a subclass of Component. It has additional methods that


allow other Component objects to be nested within it. Other Container objects can
be stored inside of a Container (since they are themselves instances of
Component). This makes for a multileveledcontainment system. A container is
responsible for laying out (that is, positioning) any components that it contains.

Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as
a recursively nestable, concrete screen component. Panel is the superclass for
Applet. When screen output is directed to an applet, it is drawn on the surface of a
Panel object. In essence, a Panel is a window that does not contain a title bar, menu
bar, or border. This is why you don’t see these items when an applet is run inside a
browser. When you run an applet using an applet viewer, the applet viewer provides
the title and border.

Other components can be added to a Panel object by its add( ) method (inherited
from Container). Once these components have been added, you can position and
resize themmanually using the setLocation( ), setSize( ), setPreferredSize( ), or
setBounds( ) methods defined by Component.

Window

The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called
Frame, described next.

Frame

Frame encapsulates what is commonly thought of as a “window.” It is a subclass of


Window and has a title bar, menu bar, borders, and resizing corners. The precise
look of a Frame will differ among environments. A number of environments are
reflected in the screen captures shown throughout this book.

Canvas

Although it is not part of the hierarchy for applet or frame windows, there is one
other type of window that you will find valuable: Canvas. Derived from
Component, Canvas encapsulates a blank window upon which you can draw.

Working with Frame Window:

There are two ways to create a Frame. They are,

1. By Instantiating Frame class(association)


2. By extending Frame class(inheritance)

Here are two of Frame’s constructors:

I) Frame()
II) Frame(String title)
- The first form creates a standard window that does not contain a title.
- The second form creates a window with the title specified by title.

There are several methods you will use when working with
Framewindows.Following are the useful methods of Component Class.

1. setSize( ) method:

The setSize( ) method is used to set the dimensions of the window.Its syntax
as follows.

public void setSize(intwidth,int height)

-The size of Frame is specified by the width and height .

-width and height value specified in terms of pixel.

2.DimensiongetSize( ) method:
This method returns the current size of the window contained within the
width and height fields of a Dimension object.

2. setVisible( ):
- After a frame window has been created, it will not be visible until you call
setVisible( ).
- By default frame is not visible,The Frame is visible if the argument to this
method is true. Otherwise, it is hidden.

public void setVisible(boolean status)

setTitle( ):

Chapter 02 Swing Components:

Swing in java is part of Java foundation class which is lightweight and platform
independent. It is used for creating window based applications. It includes components
like button, scroll bar, text field etc. Putting together all these components makes a
graphical user interface. In this article, we will go through the concepts involved in the
process of building applications using swing in Java.

What is Swing In Java?


Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for
building optimized window based applications. It is a part of the JFC( Java Foundation
Classes). It is build on top of the AWT API and entirely written in java. It is platform
independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like
button, checkbox etc. This is helpful because we do not have to start from the scratch.

Container Class
Any class which has other components in it is called as a container class. For building
GUI applications at least one container class is necessary.

Following are the three types of container classes:

1. Panel – It is used to organize components on to a window


2. Frame – A fully functioning window with icons and titles

3. Dialog – It is like a pop up window but not fully functional like the frame

Difference Between AWT and Swing


AWT SWING

 Platform Dependent  Platform Independent


 Does not follow MVC  Follows MVC
 Lesser Components  More powerful components
 Does not support pluggable look and
 Supports pluggable look and feel
feel
 Heavyweight  Lightweight

Java Swing Class Hierarchy

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are
inherited from the JComponent class which can be added to the container classes.
Containers are the windows like frame and dialog boxes. Basic swing components are
the building blocks of any gui application. Methods like setLayout override the default
layout in each container. Containers like JFrame and JDialog can only add a component
to itself. Following are a few components with examples to understand how we can use
them.

MVC(Model-View-Controller )Architecture
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program
or application shall consist of data model, presentation information and
control information. The MVC pattern needs all these components to be
separated as different objects.

The model designs based on the MVC architecture follow MVC design
pattern. The application logic is separated from the user interface while
designing the software using model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to


carry the data that can also contain the logic to update controller if
data is changed.
o View: It represents the presentation layer of application. It is used to
visualize the data that the model contains.
o Controller: It works on both the model and view. It is used to manage
the flow of application, i.e. data flow in the model object and to update
the view whenever data is changed.

In Java Programming, the Model contains the simple Java classes, the View
used to display the data and the Controller contains the servlets. Due to this
separation the user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side,
for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other
method.

What is a Container Class?


Container classes are classes that can have other components on it. So for
creating a Java Swing GUI, we need at least one container object. There are
3 types of Java Swing containers.

1. Panel: It is a pure container and is not a window in itself. The sole


purpose of a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a
message has to be displayed. It is not a fully functioning window like the
Frame.

Example of Swing by Association inside constructor


mport javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}

public static void main(String[] args) {


new Simple();
}
}
Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the
instance of JFrame class explicitly.

import javax.swing.*;

public class Simple2 extends JFrame{//inheriting JFrame

JFrame f;
Simple2()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}

Java Swing 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 is a Java Foundation Classes [JFC] library and an extension of the


Abstract Window Toolkit [AWT]. Swing offers much-improved functionality over
AWT, new components, expanded components features, and excellent event
handling with drag-and-drop support.

Icons
Swing introduces the concept of an icon for use in a variety of components.
The Icon interface and ImageIcon class make dealing with simple images
extremely easy.

The Icon Interface


The Icon interface is very simple, specifying just three methods used to
determine the size of the Icon and to display it. Implementors of this interface
are free to store and display the image in any way, providing a great deal of
flexibility. In other words, icons don’t have to be bitmaps or GIF images, but
are free to render themselves any way they choose; as we’ll see later, an icon
can simply draw on the component if that’s more efficient. The examples at
the end of this section show a couple of different ways the interface might be
implemented.
Properties
The Icon interface defines the properties listed in Table 4.3.
The iconHeight and iconWidth properties specify the size of the Icon in pixels.

Method
public abstract void paintIcon(Component c, Graphics g, int x, int y)

Paints the Icon at the specified location on the given Graphics.


The Component is provided to allow its properties (such as foreground or
background color) to be used when painting, or to allow the component
to be used as an image observer

import javax.swing.*;
import java.awt.*;

// A simple Icon implementation that draws ovals


public class OvalIcon implements Icon {

public OvalIcon(int w, int h) {


width = w;
height = h;
}

public void paintIcon(Component c, Graphics g, int x, int y) {


g.drawOval(x, y, width-1, height-1);
}
public int getIconWidth() { return width; }
public int getIconHeight() { return height; }
private int width, height;
}
JTextField:
JTextField is a lightweight component that allows the editing of a single line
of text. For information on and examples of using text fields.
The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits JTextComponent class.
JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.

The class JButton is an implementation of a push button. This component has a label
and generates an event when pressed.
JLabel is of the many Java classes from the Java Swing package. The JLabel
class from the swing package is able to display a text or a picture or both. Similar to
other classes in the Swing package, the label and label’s contents displayed by JLabel
are aligned using horizontal and vertical alignments. The programmer can specify
where the label’s contents will be displayed on the label’s display area by setting the
alignments.
By default, the text or more specifically, label text is aligned vertically and is displayed at
the center of their display area whereas an image or picture displayed is horizontally
centered by default.
JLabel is a class of java Swing . JLabel is used to display a short string or an
image icon. JLabel can display text, image or both . JLabel is only a display of
text or image and it cannot get focus . JLabel is inactive to input events such a
mouse focus or keyboard focus. By default labels are vertically centered but the
user can change the alignment of label.

JCheckBoxes:
The class JCheckBox is an implementation of a check box - an item that can be
selected or deselected, and which displays its state to the user.The JCheckBox class
in JAVA can be used as a toggle to switch off or on any functionality. This class
basically created a checkbox that provides two options which are: on and off.
Here on and off are denoted as true or false internally by the system. Then on
“on” state is arrived at by clicking on the checkbox. Clicking on it again changes
the state of the checkbox from “on” to “off”. This class inherits its characteristics
from the JToggleButton class.
JRadioButton:
We use the JRadioButton class to create a radio button. Radio button is use to
select one option from multiple options. It is used in filling forms, online
objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio
button at a time. We use “ButtonGroup” class to create a ButtonGroup and add
radio button in a group.
The JRadioButton class is used to create a radio button. It is used to choose
one option from multiple options. It is widely used in exam systems or quiz.
Combo Box:
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 is a part of Java Swing package. JComboBox inherits JComponent


class . JComboBox shows a popup menu that shows a list and the user can
select a option from that specified list . JComboBox can be editable or read-
only depending on the choice of the programmer .

Scroll panes:

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.

The layout manager used by JScrollPane. JScrollPaneLayout is based on nine


components: a viewport, two scrollbars, a row header, a column header, and
four “corner” components.
The layout manager used by JScrollPane. JScrollPaneLayout is based on nine
components: a viewport, two scrollbars, a row header, a column header, and
four “corner” components.

JMenuBar

The JTable class is used to display data in tabular form. It is composed of rows
and columns.The JMenuBar class is used to display menubar on the window
or frame. It may have several menus.The object of JMenu class is a pull down
menu component which is displayed from the menu bar. It inherits the
JMenuItem class.The object of JMenuItem class adds a simple labeled menu
item. The items used in a menu must belong to the JMenuItem or any of its
subclass.

JMenuBar, JMenu and JMenuItems are a part of Java Swing package.


JMenuBar is an implementation of menu bar . the JMenuBar contains one or
more JMenu objects, when the JMenu objects are selected they display a
popup showing one or more JMenuItems . JMenu basically represents a menu .
It contains several JMenuItem Object . It may also contain JMenu Objects (or
submenu). Constructors :
1. JMenuBar() : Creates a new MenuBar.
2. JMenu() : Creates a new Menu with no text.
3. JMenu(String name) : Creates a new Menu with a specified name.
4. JMenu(String name, boolean b) : Creates a new Menu with a specified
name and boolean value specifies it as a tear-off menu or not. A tear-off
menu can be opened and dragged away from its parent menu bar or menu.
Chapter 03. Networking:

The java.net package:

Definition of java.net Package


Java.net is a package that provides a set of classes as well as interfaces for
networking in Java.
Some of the classes are:

1)URL class.
2)URLConnection class.
3)Socket class.
4)ServerSocket classes.
5)DatagramSocket.
6)MulticastSocket etc.

The java.net package contains classes and interfaces that provide a


powerful infrastructure for networking in Java. Many of the classes in this
package provide support for working with sockets in Java. For example,
the Socket and ServerSocket classes make it possible to implement client
and server programs that communicate using a reliable, connection-oriented
protocol.

The DatagramSocket, DatagramPacket,

A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any
order.

Datagram packets are used to implement a connectionless packet delivery service.


Each message is routed from one machine to another based only on information contained
within that packet. Multiple packets sent from one machine to another might be routed
differently, and might arrive in any order.

ServerSocket Class is used for providing system-independent implementation of the


server-side of a client/server Socket Connection. The constructor for ServerSocket
throws an exception if it can't listen on the specified port (for example, the port is already
being used). It is widely used so the applications of java.

and
MulticastSocket classes, on the other hand, all provide support for
communication over a connectionless protocol. The MulticastSocket class is
new in Java.

The URL and URLConnection classes define methods for working with
uniform resource locators (URLs). The URL class supports basic access to
data stored at a URL, while URLConnection offers complete control over all
aspects of working with a URL.
The InetAddress class represents network addresses,
so InetAddress objects are used by a number of the methods in other
classes in java.net.

The java.net package provides two basic mechanisms for accessing data and
other resources over a network. The fundamental mechanism is called a socket. A
socket allows programs to exchange groups of bytes called packets. There are a
number of classes in java.net that support sockets,
including Socket, ServerSocket, DatagramSocket, DatagramPacket,
and MulticastSocket. The java.net package also includes a URL class that provides
a higher-level mechanism for accessing and processing data over a network.

A socket is a mechanism that allows programs to send packets of bytes to each other.
The programs do not need to be running on the same machine, but if they are running
on different machines, they do need to be connected to a network that allows the
machines to exchange data. Java's socket implementation is based on the socket
library that was originally part of BSD UNIX. Programmers who are familiar with
UNIX sockets or the Microsoft WinSock library should be able to see the similarities
in the Java implementation.

When a program creates a socket, an identifying number called a port number is


associated with the socket. Depending on how the socket is used, the port number is
either specified by the program or assigned by the operating system. When a socket
sends a packet, the packet is accompanied by two pieces of information that specify
the destination of the packet:

 A network address that specifies the system that should receive the packet.
 A port number that tells the receiving system to which socket to deliver the
data.
Working of java.net Package
The java.net package is helpful in Java networking. It supports two protocols

such as:

 TCP(Transmission Control Protocol): Permits reliable communication

between 2 applications. It is denoted as TCP/IP.

 UDP(User Datagram Protocol): It is a connection-less protocol.

Permits data packets to transfer between applications. In order to perform several


operations on these protocols, classes of java.net packages are used. It will be
discussed in the next section.

Java Networking:

When computing devices such as laptops, desktops, servers, smartphones, and


tablets and an eternally-expanding arrangement of IoT gadgets such as
cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats,
and various sensors are sharing information and data with each other is known
as networking.

In simple words, the term network programming or networking associates with


writing programs that can be executed over various computer devices, in which
all the devices are connected to each other to share resources using a network.

What is Java Networking?

Networking supplements a lot of power to simple programs. With networks, a


single program can regain information stored in millions of computers
positioned anywhere in the world. Java is the leading programming language
composed from scratch with networking in mind. Java Networking is a concept
of combining two or more computing devices together to share resources.
All the Java program communications over the network are done at the
application layer. The java.net package of the J2SE APIs comprises various
classes and interfaces that execute the low-level communication features,
enabling the user to formulate programs that focus on resolving the problem.
Common Network Protocols

As stated earlier, 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.
TCP has built-in methods to examine for errors and ensure the delivery of data
in the order it was sent, making it a complete protocol for transporting
information like still images, data files, and web pages.
2.User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a
connection-less protocol that allows data packets to be transmitted between
different applications. UDP is a simpler Internet protocol in which error-checking
and recovery services are not required. In UDP, there is no overhead for
opening a connection, maintaining a connection, or terminating a connection. In
UDP, the data is continuously sent to the recipient, whether they receive it or
not.

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. It is composed of octets. The range of each octet varies from 0 to
255.
 Range of the IP Address – 0.0.0.0 to 255.255.255.255
 For Example – 192.168.0.1

2. 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. There are
65,535 port numbers, but not all are used every day.

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

4. MAC Address – MAC address stands for Media Access Control address.
It is a bizarre identifier that is allocated to a NIC (Network Interface
Controller/ Card). It contains a 48 bit or 64-bit address, which is combined
with the network adapter. MAC address can be in hexadecimal
composition. In simple words, a MAC address is a unique number that is
used to track a device in a network.

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

6. 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. The objects of this
class provide an edge for the OutputStream object to store resource data
into the cache.

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. The HTTP state
management mechanism specifies the mechanism of how to make HTTP
requests and responses.

3. CookieManager – 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. A
CookieManager comprises a CookieStore and a CookiePolicy.

4. DatagramPacket – 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. InetAddress – The InetAddress class is used to provide methods to get


the IP address of any hostname. An IP address is expressed by a 32-bit or
128-bit unsigned number. InetAddress can handle both IPv4 and IPv6
addresses.

6. Server Socket – 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. For example – it will throw an
exception if the port is already being used.

7. Socket – The Socket class is used to create socket objects that help the
users in implementing all fundamental socket operations. The users can
implement various networking actions such as sending, reading data, and
closing connections. Each Socket object built
using java.net.Socket class has been connected exactly with 1 remote
host; for connecting to another host, a user must create a new socket
object.

8. DatagramSocket – 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. Datagram Sockets is Java’s mechanism for providing network
communication via UDP instead of TCP.

9. Proxy – 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. URL – The URL class in Java is the entry point to any available sources
on the internet. A Class URL describes a Uniform Resource Locator, which
is a signal to a “resource” on the World Wide Web. A source can denote a
simple file or directory, or it can indicate a more difficult object, such as a
query to a database or a search engine.

11. URLConnection – 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. A user can also configure header fields used
in client requests using URLConnection.

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. In
CookiePolicy, there are three pre-defined policy implementations, namely
ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.

2. CookieStore – 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. FileNameMap – The FileNameMap interface is an uncomplicated


interface that implements a tool to outline a file name and a MIME type
string. FileNameMap charges a filename map ( known as a mimetable) from
a data file.

4. SocketOption – The SocketOption interface helps the users to control


the behavior of sockets. Often, it is essential to develop necessary features
in Sockets. SocketOptions allows the user to set various standard options.

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

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

Socket Programming:

Java Socket programming is practiced for communication between the


applications working on different JRE. Sockets implement the communication
tool between two computers using TCP. Java Socket programming can either
be connection-oriented or connection-less. In Socket Programming, Socket and
ServerSocket classes are managed for connection-oriented socket
programming. However, DatagramSocket and DatagramPacket classes are
utilized for connection-less socket programming.
A client application generates a socket on its end of the communication and
strives to combine that socket with a server. When the connection is
established, the server generates an object of socket class on its
communication end. The client and the server can now communicate by writing
to and reading from the socket.
The java.net.Socket class describes a socket, and
the java.net.ServerSocket class implements a tool for the server program to
host clients and build connections with them.

Steps to establishing a TCP connection between two computing devices


using Socket Programming
The following are the steps that occur on establishing a TCP connection
between two computers using socket programming are given as follows:

Step 1 – The server instantiates a ServerSocket object, indicating at which port


number communication will occur.
Step 2 – After instantiating the ServerSocket object, the server requests the
accept() method of the ServerSocket class. This program pauses until a client
connects to the server on the given port.
Step 3 – After the server is idling, a client instantiates an object of Socket class,
defining the server name and the port number to connect to.
Step 4 – After the above step, the constructor of the Socket class strives to
connect the client to the designated server and the port number. If
communication is authenticated, the client forthwith has a Socket object
proficient in interacting with the server.
Step 5 – On the server-side, the accept() method returns a reference to a new
socket on the server connected to the client’s socket.
After the connections are stabilized, communication can happen using I/O
streams. Each object of a socket class has both an OutputStream and an
InputStream. The client’s OutputStream is correlated to the server’s
InputStream, and the client’s InputStream is combined with the server’s
OutputStream. Transmission Control Protocol (TCP) is a two-way
communication protocol. Hence information can be transmitted over both
streams at the corresponding time.
Socket Class
The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement
various networking actions such as sending, reading data, and closing
connections. Each Socket object created using java.net.Socket class has been
correlated specifically with 1 remote host. If a user wants to connect to another
host, then he must build a new socket object.
Methods of Socket Class
In Socket programming, both the client and the server have a Socket object, so all the methods
under the Socket class can be invoked by both the client and the server. There are many methods
in the Socket class.

S
Method Description
No.

This method is used to connect the


socket to the particularized host. This
public void method is required only when the
connect(SocketAddress host, user instantiates the Socket applying
1 int timeout) the no-argument constructor.

This method is used to return the port


to which the socket is pinned on the
2 public int getPort() remote machine.

This method is used to return the


public InetAddress location of the other computer to
3 getInetAddress() which the socket is connected.

This method is used to return the port


to which the socket is joined on the
4 public int getLocalPort() local machine.

public SocketAddress This method returns the location of


5 getRemoteSocketAddress() the remote socket.

This method is used to return the


input stream of the socket. This input
public InputStream stream is combined with the output
6 getInputStream() stream of the remote socket.

This method is used to return the


output stream of the socket. The
public OutputStream output stream is combined with the
7 getOutputStream() input stream of the remote socket.

8 public void close() This method is used to close the


socket, which causes the object of
S
Method Description
No.

the Socket class to no longer be able


to connect again to any server.

ServerSocket Class

The ServerSocket class is used for providing system-independent


implementation of the server-side of a client/server Socket Connection. The
constructor for ServerSocket class throws an exception if it can’t listen on the
specified port. For example – it will throw an exception if the port is already
being used.
Methods of ServerSocket Class:
There are many methods in the ServerSocket class which are very useful for the users. These
methods are:

S
no. Method Description

This method is used to return the port that the server


socket is monitoring on. This method is beneficial if a
user passed 0 as the port number in a constructor and
1 public int getLocalPort() lets the server find a port for him.

public void This method is used to set the time-out value for the
setSoTimeout(int time in which the server socket pauses for a client
2 timeout) during the accept() method.

3 public Socket accept() This method waits for an incoming client. This method is
blocked till either a client combines to the server on the
specified port or the socket times out, considering that
the time-out value has been set using the
S
no. Method Description

setSoTimeout() method. Otherwise, this method will be


blocked indefinitely.

This method is used to bind the socket to the


particularized server and port in the object of
public void SocketAddress. The user should use this method if he
bind(SocketAddress has instantiated the ServerSocket using the no-
4 host, int backlog) argument constructor.

Example of Socket Programming in Java:


The below example illustrates a pretty basic one-way Client and Server setup
where a Client connects, sends messages to the server and the server shows
them using a socket connection.

Client-Side Java Implementation:


 Java

// A Java program for a ClientSide

import java.io.*;

import java.net.*;

public class clientSide {


// 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 clientSide(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);

catch (IOException i) {

System.out.println(i);

// string to read message from input

String line = "";


// keep reading until "End" is input

while (!line.equals("End")) {

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)

clientSide client

= new clientSide("127.0.0.1", 5000);

}
}

Server Side Java Implementation:


 Java

// A Java program for a serverSide

import java.io.*;

import java.net.*;

public class serverSide {

// initialize socket and input stream

private Socket socket = null;

private ServerSocket server = null;

private DataInputStream in = null;

// constructor with port

public serverSide(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 "End" is sent

while (!line.equals("End")) {

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)

serverSide server = new serverSide(5000);

To run on Terminal or Command Prompt


Open two windows one for Server and another for Client.
1. First run the Server application. It will show –
Server started
Waiting for a client …
2. Then run the Client application on another terminal. It will show:
Connected
and the server accepts the client and shows,
Client accepted.
3. Then you can start typing messages in the Client window. Here is the sample
video of the output.

Connection oriented transmission:

For the connection oriented service, the user has to follow the sequence operations
given below −
 Connection is established
 Information is sent
 Connection is released
We have to establish a connection before starting the communication in connection
oriented service. Whenever the connection is established we can send the message
and after that we can release the connection.
Connection oriented service is more reliable than connectionless service. In connection
oriented service we can also send the message if there is an error at the receiver’s end.
For example: connection oriented is TCP protocol.
In connection-oriented services, the devices at both the endpoints use a protocol to
establish an end-to-end connection before sending any data.
Stream Socket Class:

The java.net.Socket class allows us to create socket objects that help us in


implementing all fundamental socket operations. We can perform various
networking operations such as
1.Sending.
2.Reading Data
3. Closing connections.
Each Socket object that has been created using with java.net.Socket class has
been associated exactly with 1 remote host, for connecting to another different
host, we must create a new socket object.
The syntax for importing Socket class from java.net package :
import java.net.Socket;

Establish a Socket Connection:

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:
The Socket class acts as an endpoint for communication between two machines. It
implements client sockets.
Creating a Socket to a remote host on a port (creating TCP client and server):

A socket is one end-point of a two-way communication link between two


programs running on the network. Socket classes are used to represent the
connection between a client program and a server program. Socket
Programming, us basically client-server programming where a socket is used as
a link between them. We need to import the ‘java.net package in our program
which provides two classes namely Socket class and ServerSocket class.
Socket Class implements the client-side of the connection and ServerSocket
class implements the server-side of the connection.
Procedure:
In order to create a socket, the ‘java.net‘ package needs to be imported
thereafter using the Socket and ServerSocket class, we create the object of that
class.
1. The Server opens a ServerSocket on a well-known port and waits for
input.
2. Meanwhile, the Client opens a (client) Socket with the server’s hostname
and this well-known port address.
3. It sends a request message to the server to initialize a communication
session.
The readUTF() and writeUTF() methods in Java:

Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode
Consortium. If you want to create documents that use characters from multiple character sets,
you will be able to do so using the single Unicode character encodings. It provides 3 types of
encodings.

 UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4


bytes long, making UTF8 variable width.
 UTF-16-8 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making
UTF16 variable width.
 UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always
1 "long" in length.

 The readUTF() method of the java.io.DataOutputStream reads data that is in


modified UTF-8 encoding, into a String and returns it. Therefore to read UTF-8
data to a file

Java DataOutputStream Class


Java DataOutputStream class allows an application to write primitive Java data
types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can
later be read by a data input stream (Basically it is use by client side).

Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data from
the input stream in a machine-independent way.

Java application generally uses the data output stream to write data that can
later be read by a data input stream. (Basically it is use by client side).

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-based
input stream. It can be used to read data line by line by readLine() method. It
makes the performance fast. It inherits Reader class.
Java BufferedReader is a public Java class that reads text, using buffering to enable large reads at
a time for efficiency, storing what is not needed immediately in memory for later use.

Buffered readers are preferable for more demanding tasks, such as file and streamed readers.
Buffering the reads allows large volumes to be read from disk and copied to much faster RAM to
increase performance over the multiple network communications or disk reads done with each
read command otherwise. Java BufferedReader is preferable anywhere costly reads are likely to
be an issue, such as FileReaders and InputStreamReaders,

Java System Class


The System class of java contains several useful class fields and methods. It
also provides facilities like standard input, standard output, and error output
Streams. It can't be instantiated.

The Java System class comes in the module of "java.base" & in the package
of "java.lang".

4. JDBC

The design of JDBC:

Design of JDBC
Java Database Connectivity (JDBC) is an Application Programming
Interface (API), from Sun microsystem that is used by the Java application to
communicate with the relational databases from different vendors. JDBC and
database drivers work in tandem to access spreadsheets and
databases. Design of JDBC defines the components of JDBC, which is used
for connecting to the database.

Performing Database Operations in Java using the JDBC API (SQL CREATE,
INSERT, UPDATE, DELETE, and SELECT).

JDBC or Java Database Connectivity is a Java API to connect and execute the
query with the database. It is used to write programs required to access
databases. JDBC, along with the database driver, can access databases and
spreadsheets. The enterprise data stored in a relational database(RDB) can be
accessed with the help of JDBC APIs.
JDBC has four major components that are used for the interaction with the
database.

1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver

1) JDBC API: JDBC API provides various interfaces and methods to


establish easy connection with different databases.

2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the
various operations such as deletion, updation, insertion that are being
executed by the JDBC Drivers.
3) 3) JDBC Driver manager: JDBC Driver manager loads the database-
specific driver into an application in order to establish the connection
with the database. The JDBC Driver manager is also used to make the
database-specific call to the database in order to do the processing of
a user request.

4) 4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used


to connect the database drivers to the database. The bridge does the
translation of the JDBC method calls into the ODBC method call. It
makes the usage of the sun.jdbc.odbc package that encompasses the
native library in order to access the ODBC (Open Database
Connectivity) characteristics.

Architecture of JDBC
1) Application: It is the Java servlet or an applet that communicates with
the data source.

2) The JDBC API: It allows the Java programs to perform the execution of
the SQL statements and then get the results.

A few of the crucial interfaces and classes defined in the JDBC API are the
following:

o Drivers
o DriverManager
o Statement
o Connection
o CallableStatement
o PreparedStatement
o ResultSet
o SQL data

3) DriverManager: DriverManager plays a crucial role in the architecture


of JDBC.

o It uses database-specific drivers to connect the enterprise applications


to various databases.

4) JDBC drivers: To interact with a data source with the help of the JDBC,
one needs a JDBC driver which conveniently interacts with the respective
data source.
Metadata:

Metadata in Java defined as the data about the data is called “Metadata”.
Metadata is also said to be documentation about the information which is
required by the users. This is one of the essential aspects in the case of data
warehousing.

Metadata is data about the data or documentation about the information


which is required by the users. In data warehousing, metadata is one of the
essential aspects.

For Example: Suppose we say that a data item about a person is 80. This
must be defined by noting that it is the person's weight and the unit is
kilograms. Therefore, (weight, kilograms) is the metadata about the data is
80.

Reasons to use:

o First, it acts as the glue (Paste) that links all parts of the data
warehouses.
o Next, it provides information about the contents and structures to the
developers.
o Finally, it opens the doors to the end-users and makes the contents
recognizable in their terms.

Types of Metadata
o Operational Metadata
o Extraction and Transformation Metadata
o End-User Metadata

Operational Metadata
As we know, data for the data warehouse comes from various operational
systems of the enterprise. These source systems include different data
structures. The data elements selected for the data warehouse have various
fields lengths and data types.
In selecting information from the source systems for the data warehouses,
we divide records, combine factor of documents from different source files,
and deal with multiple coding schemes and field lengths. When we deliver
information to the end-users, we must be able to tie that back to the source
data sets. Operational metadata contains all of this information about the
operational data sources.

Extraction and Transformation Metadata


Extraction and transformation metadata include data about the removal of
data from the source systems, namely, the extraction frequencies, extraction
methods, and business rules for the data extraction. Also, this category of
metadata contains information about all the data transformation that takes
place in the data staging area.

End-User Metadata
The end-user metadata is the navigational map of the data warehouses. It
enables the end-users to find data from the data warehouses. The end-user
metadata allows the end-users to use their business terminology and look for
the information in those ways in which they usually think of the business.

Transactions:

Transactions enable you to control if, and when, changes are applied to the database. It
treats a single SQL statement or a group of SQL statements as one logical unit, and if
any statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC
driver uses by default, use the Connection object's setAutoCommit() method. If you
pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a
boolean true to turn it back on again.

Transaction represents a single unit of work.

The ACID properties describes the transaction management well. ACID


stands for Atomicity, Consistency, isolation and durability.

Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to


another consistent state.

Isolation ensures that transaction is isolated from other transaction.


Durability means once a transaction has been committed, it will remain so,
even in the event of errors, power loss etc.

5. Servlet:

Introduction of Servlet:

Servlet technology is used to create a web application (resides at server


side and generates a dynamic web page).

Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the
webserver, process the request, produce the response, then send a response
back to the webserver.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any
Servlet.
o Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page.
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in comparison
with the CGI.

Servlet technology is robust and scalable because of java language. Before


Servlet, CGI (Common Gateway Interface) scripting language was common
as a server-side programming language. However, there were many
disadvantages to this technology. We have discussed these disadvantages
below.

There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

Servlets can be created using the javax.servlet and javax.servlet.http packages,


which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.

Life cycle of Servlet:

The entire life cycle of a Servlet is managed by the Servlet container which
uses the javax.servlet.Servlet interface to understand the Servlet object and
manage it. So, before creating a Servlet object, let’s first understand the life
cycle of the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through
four stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.
1.Loading a Servlet: The first stage of the Servlet lifecycle involves loading
and initializing the Servlet by the Servlet container. The Web container or
Servlet Container can load the Servlet at either of the following two stages :
 Initializing the context, on configuring the Servlet with a zero or positive
integer value.
 If the Servlet is not preceding stage, it may delay the loading process until
the Web container determines that this Servlet is needed to service a
request.

The Servlet container performs two operations in this stage :

 Loading : Loads the Servlet class.


 Instantiation : Creates an instance of the Servlet. To create a new
instance of the Servlet, the container uses the no-argument constructor.
2.Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet
container initializes the instantiated Servlet object. The container initializes the
Servlet object by invoking the Servlet.init(ServletConfig) method which
accepts ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only
once, immediately after the Servlet.init(ServletConfig) object is instantiated
successfully. This method is used to initialize the resources, such as JDBC
datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.

3.Handling request: After initialization, the Servlet instance is ready to serve


the client requests. The Servlet container performs the following operations
when the Servlet instance is located to service a request :
 It creates the ServletRequest and ServletResponse objects. In
this case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which
are subtypes of the ServletRequest and ServletResponse objects
respectively.
 After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.

4.Destroying a Servlet: When a Servlet container decides to destroy the


Servlet, it performs the following operations,
 It allows all the threads currently running in the service method of
the Servlet instance to complete their jobs and get released.
 After currently running threads have completed their jobs, the
Servlet container calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the
references of this Servlet instance so that it becomes eligible for garbage
collection.

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Handling HTTP Get and Post Request:


GET Asks to get the resource at the requested URL.

POS Asks the server to accept the body info attached. It is like GET request with extra
T info sent with the request.

6. Introduction to JSP:

Getting Familiar with JSP Server:

Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.

 It stands for Java Server Pages.


 It is a server side technology.
 It is used for creating web application.
 It is used to create dynamic web content.
 In this JSP tags are used to insert JAVA code into HTML pages.
 It is an advanced version of Servlet Technology.
 It is a Web based technology helps us to create dynamic and platform
independent web pages.
 In this, Java code can be inserted in HTML/ XML pages or both.
 JSP is first converted into servlet by JSP container before processing the
client’s request.
JSP pages are more advantageous than Servlet:
 They are easy to maintain.
 No recompilation or redeployment is required.
 JSP has access to entire API of JAVA .
 JSP are extended version of Servlet.

Features of JSP
 Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
 Reduction in the length of Code :- In JSP we use action tags, custom
tags etc.
 Connection to Database is easier :-It is easier to connect website to
database and allows to read or write data easily to the database.
 Make Interactive websites :- In this we can create dynamic web pages
which helps user to interact in real time environment.
 Portable, Powerful, flexible and easy to maintain :- as these are
browser and server independent.
 No Redeployment and No Re-Compilation :- It is dynamic, secure and
platform independent so no need to re-compilation.
 Extension to Servlet :- as it has all features of servlets, implicit objects
and custom tags

Advantages of using JSP


 It does not require advanced knowledge of JAVA
 It is capable of handling exceptions
 Easy to use and learn
 It contains tags which are easy to use and understand
 Implicit objects are there which reduces the length of code
 It is suitable for both JAVA and non JAVA programmer
Disadvantages of using JSP
 Difficult to debug for errors.
 First time access leads to wastage of time
 It’s output is HTML which lacks features.

First JSP:

Let's begin with a simple JSP example. We shall use the webapp called "hello" that we
have created in our earlier exercise. Use a programming text editor to enter the
following HTML/JSP codes and save as "first.jsp" (the file type of ".jsp" is
mandatory) in your webapp (web context) home directory (i.e., "webapps\hello".

<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>

To execute the JSP script: Simply start your Tomcat server and use a browser to issue
an URL to browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).
From your browser, choose the "View Source" option to check the response message. It
should be either of the followings depending on the random number generated.

<html>
<body>
<% out.print(2*5); %>
</body>
</html>

Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL

Adding Dynamic contents via expressions:

Creating Dynamic Content


You create dynamic content by accessing Java programming language objects from
within scripting elements.
Using Objects within JSP Pages

You can access a variety of objects, including enterprise beans and JavaBeans
components, within a JSP page. JSP technology automatically makes some objects
available, and you can also create and access application-specific objects.

Implicit Objects

Implicit objects are created by the Web container and contain information related to a
particular request, page, or application. Many of the objects are defined by the Java
Servlet technology underlying JSP technology.

Scriptlets:

Scripting elements in JSP must be written within the <% %> tags. The JSP
engine will process any code you write within the pair of the <% and
%> tags, and any other texts within the JSP page will be treated as HTML
code or plain text while translating the JSP page.

Example:

<!DOCTYPE html>

<html>

<head>

<title>w3schools JSP Tutorial</title>

</head>

<% int cnt = 6; %>

<body>

Calculated page count is <% out.println(cnt); %>

</body>

</html>
Mixing Scriptlets and HTML

 You can mix scriptlets with HTML to make part of the HTML conditional, or
looping.
 All you have to do is keep the Java within the <% %> tags, and the HTML out.
The compiler will take care of the rest.
 The following example illustrates mixing HTML with JSP code. For
starters, typically some of the JSP programs look weird and confusing
because both the HTML and JSP code is mixed. But if you can carefully
understand what tag is what, you can write even more complex JSP
programs than you see.
 One key point you need to know that, you can end a scriptlet tag
anywhere you want. For example

<%
if(true){
%>
<p>This is in the if-block. </p>
<%
out.println("This is that's it.");
}
%>

As you can see the first tag <% %> was ended unexpectedly to write the
message This is in the if-block. This is a html line executed only if the if-
condition is met. Isn’t this simple?
Now let us write a program.

Directives:

The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.

There are three types of directives:


o page directive
o include directive
o taglib directive

Syntax of JSP page directive


<%@ page attribute="value" %>

<html>
<body>

<%@ page import="java.util.Date" %>


Today is: <%= new Date() %>

</body>
</html>
A JSP declaration is used to declare variables and methods in a page’s scripting language

Tags

JSP Tags
JSP scripting language include several tags or scripting elements that performs various tasks such
as declaring variables and methods, writing expressions, and calling other JSP pages. These are
known as JSP scripting elements. The different types of scripting elements are summarized in
the Table 1:
Table 1. JSP Tags
JSP Tag Brief Description Tag Syntax

Specifies translation time instructions to the JSP


engine.
Directive <%@ directives %>

Declaration Declares and defines methods and


variables.
<%! variable dceclaration & method
Declaration definition %>

Allows the developer to write free-form Java code in


a JSP page.
Scriptlet <% some Java code %>

Expression Used as a shortcut to print values in the output <%= an Expression %>
HTML of a JSP page.

Provides request-time instructions to the JSP


engine.
Action <jsp:actionName />

Used for documentation and for commenting out


parts of JSP code.
Comment <%– any Text –%>

Session:

A session can be defined as an object associated with each user with a


unique session ID, and the user's data is based on the account they have
registered. Different forms of data can be set in a session; These data
related to each user of the site help the user and the website owner in
different ways. As you know, HTTP is a "stateless" protocol; Whenever a user
visits a web page, the user opens a separate connection with the webserver,
and the server does not keep a record of preceding client requests.

7. Introduction to Java Beans & Hibernate:

What is bean: JavaBean

JavaBeans is a portable, platform-independent model written in Java


Programming Language. Its components are referred to as beans. In simple
terms, JavaBeans are classes which encapsulate several objects into a single
object. It helps in accessing these object from multiple places. JavaBeans
contains several elements like Constructors, Getter/Setter Methods and much
more.
JavaBeans has several conventions that should be followed:

Beans should have a default constructor (no arguments)


Beans should provide getter and setter methods.
1. A getter method is used to read the value of a readable property
2. To update the value, a setter method should be called.
3. Beans should implement java.io.serializable, as it allows to save, store
and restore the state of a JavaBean you are working on.

In simple terms, JavaBeans are classes which encapsulate several objects into a single
object. It helps in accessing these object from multiple places. JavaBeans contains
several elements like Constructors, Getter/Setter Methods and much more.

A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
JavaBeans are classes that encapsulate many objects into a single object (the
bean).Serialization is a mechanism of converting the state of an object into a
byte stream. Deserialization is the reverse process where the byte stream is
used to recreate the actual Java object in memory. This mechanism is used to
persist the object.

JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties
are accessed through two methods in the JavaBean's implementation class −

S.No. Method & Description

getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
The byte stream created is platform independent. So, the object serialized on
one platform can be deserialized on a different platform. To make a Java object
serializable we implement the java.io.Serializable interface.
Reusability is the main concept in any programming language. A JavaBean is a
software component that has been designed to be reusable in a variety of
environments.

It is a java class that should follow following conventions:


1. Must implement Serializable.
2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and setter
methods.

Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
 It provides a default, no-argument constructor.
 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.
Syntax for setter methods:

1. It should be public in nature.


2. The return-type should be void.
3. The setter method should be prefixed with set.
4. It should take some argument i.e. it should not be no-arg method.

Syntax for getter methods:

1. It should be public in nature.


2. The return-type should not be void i.e. according to our requirement we
have to give return-type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or
“is”. But recommended to use “is”.

A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known
as getter and setter methods.

Why use JavaBean?


According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object
from multiple places. Moreover, it provides easy maintenance.

Advantages of javaBean:

1. A Bean obtains all the benefits of Java's "write-once, run-anywhere"


paradigm.
2. The properties, events, and methods of a Bean that are exposed to an
application
builder tool can be controlled.

3. A Bean may be designed to operate correctly in different locales, which


makes it
useful in global markets.
4. Auxiliary (Support/Backup/Secondary) software can be provided to help
a person configure a Bean. This software is
only needed when the design-time parameters for that component are
being set. It does not need to be included in the run-time environment.

5. The configuration settings of a Bean can be saved in persistent storage


and restored
at a later time.

6. A Bean may register to receive events from other objects and can
generate events that are sent to other objects.

Using JavaBeans in the Java program allows us to encapsulate many objects


into a single object called a bean. Java is an object-oriented programming
language that makes the develop once, run and reuse the program
everywhere most important.

However, JavaBeans add reusability into the Java program by maintaining a


single object encapsulating many data members and member functions. In
other words, we can say that a JavaBean is a platform-independent
component that allows us to reuse the class object in our Java code. For
example, swing and AWT classes are the JavaBeans. Consider the following
example that contains a simple JavaBean.

bean-writing process:

A Java bean is a Java class that has private member variables, public
getter and setter methods, and a zero-argument, public constructor
(supplied automatically by the compiler). To create a Java bean, follow
these seven steps.

Open your text editor and create a new file that will contain the Java bean
source. Type in the following Java statements:

Open your text editor and create a new file that will contain the Java bean
source. Type in the following Java statements:
The Java bean has two properties, firstName and lastName. A property is a
private variable exposed to external programs by means of getter and setter
methods.

1. Save your file as Person.java.


2. Open your text editor to create the class that will instantiate the Java bean. Type
in the following Java statements:

The program will instantiate the Java bean and then call the setter and getter
methods of the newly created Java bean.
1. Save your file as CreateAJavaBean.java.
2. Open a command prompt and navigate to the directory containing your new Java
programs. Then type in the command to compile the Java bean source and
hit Enter.

You might also like