Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 76

AWT classes

 Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based


application in java.
 Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
 AWT is heavyweight i.e. its components uses the resources of system.
 The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below

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

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.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class


Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager
defines the layout manager for the component.
m)
changes the visibility of the component, by default
public void setVisible(boolean status)
false.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)
Example program
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}
}

Sr. Control & Description


Label
1
A Label object is a component for placing text in a container.
Button
2
This class creates a labeled button.
CheckBox
3
A check box is a graphical component that can be in either an on (true) or off (false) state.
CheckBoxGroup
4
The CheckboxGroup class is used to group the set of checkbox.

List
5
The List component presents the user with a scrolling list of text items.
TextField
6
A TextField object is a text component that allows for the editing of a single line of text.
TextArea
7 A TextArea object is a text component that allows for the editing of a multiple lines of
text.
Choice
8 A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
Canvas
9 A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
Image
10
An Image control is superclass for all image classes representing graphical images.
ScrollBar
11 A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Dialog
12 A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
FileDialog
13
A FileDialog control represents a dialog window from which the user can select a file.

WINDOWS FUNDAMENTAL

 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 window.
 Much of the functionality of these windows is derived from their parent classes.
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.
 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.
 This makes for a multileveled containment system.
 A container is responsible for laying out any components that it contains.

Panel

 The Panel class is a concrete subclass of Container.


 It doesn’t add any new methods; it simply implements Container.
 Panel is the superclass for Applet.
 When screen output is directed to an applet, it is drawn on the surface of a Panel
object. APanel is a window that does not contain a title bar, menu bar, or border.
 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( ), 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, we
don’t create
 Window objects directly. Instead, we use a subclass of Window called Frame.

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.

Canvas

 It is not part of the hierarchy for applet or frame windows. Canvas encapsulates a
blank window upon which you can draw.

WORKING WITH FRAME


 The class Frame is a top level window with border and title. It uses BorderLayout
as default layout manager.

 After the applet, the type of window you will most often create is derived from
Frame.
You will use it to create child windows within applets, and top-level or child
windows
for applications. As mentioned, it creates a standard-style window.

Here are two of Frame’s constructors:

Frame()
Frame(Stringtitle)
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. Notice that you cannot
specify the dimensions of the window. Instead, you must set the size of the window after it
has been created.There are several methods you will use when working with Frame windows.
Setting the Window’s Dimensions

The setSize( ) method is used to set the dimensions of the window.


Syntax:
void setSize(int newWidth, int newHeight)

void setSize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the width
and height fields of the Dimension object passed in newSize.
The dimensions are specified in terms of pixels.

The getSize( ) method is used to obtain the current size of a window. Its signature
is shown here:

Dimension getSize( )

This method returns the current size of the window contained within the width and
height fields of a Dimension object.

Hiding and Showing a Window

After a frame window has been created, it will not be visible until you call
setVisible( ). Its signature is shown here:

void setVisible(boolean visibleFlag)

The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window’s Title

You can change the title in a frame window using setTitle( ), which has this
general form:

void setTitle(String newTitle)

Here, newTitle is the new title for the window.


Closing a Frame Window

When using a frame window, your program must remove that window from the

screen when it is closed, by calling setVisible(false).


To intercept a window-close event, you must implement the windowClosing( ) method of the
WindowListener
interface. Inside windowClosing( ), you must remove the window from the screen.

Working With Graphics


CoordinateAxes:
When working with graphics, a coordinate system is essential for locating object. You
probably remember your mathematical coordinate axes system which utilizes an x-axis and a
y-axis. The axes for Java graphics, however, are somewhat different.

The coordinate system for the Java graphing window positions (0,0) in the upper left hand
corner. The grid is then numbered in a positive direction on the x-axis (horizontally to the
right) and in a positive direction on the y-axis (vertically going down).
We will now be using the methods contained within the Graphics Class in the package
java.awt.

Basic Graphing Methods:

g.drawLine(35, 45, 75, 95);


drawLine(int x1, int y1, int x2, int y2)
Line
Used to draw a straight line from point
(x1,y1) to (x2,y2).

g.drawRect(35, 45, 25, 35);


drawRect(int x, int y, int width, int length)
Rectangle
Used to draw a rectangle with the upper left
corner at (x,y) and with the specified width
and length.

g.drawRoundRect(35,45,25,35,10,10);
drawRoundRect(int x, int y, int width, int
Round Edge length, int arcWidth, int arcHeight)
Rectangle Used to draw a rounded edged rectangle.
The amount of rounding is controlled by
arcWidth and arcHeight.
g.drawOval(25, 35, 25, 35);
g.drawOval(25, 35, 25, 25); → circle
drawOval(int x, int y, int width, int length)
Oval / Circle
Used to draw an oval inside an imaginary
rectangle whose upper left corner is at (x,y).
To draw a circle keep the width and length
the same.

g.drawArc(35, 45, 75, 95, 0, 90);


drawArc(int x, int y, int width, int length,
int startAngle, int arcAngle)

Used to draw an arc inside an imaginary


rectangle whose upper left corner is at (x,y).
Arc The arc is drawn from the startAngle to
startAngle + arcAngle and is measured in
degrees.
A startAngle of 0º points horizontally to
the right (like the unit circle in math).
Positive is a counterclockwise rotation
starting at 0º.
int [ ] x = {20, 35, 50, 65, 80, 95};
int [ ] y = {60, 105, 105, 110, 95, 95};
g.drawPolygon(x, y, 6);
drawPolygon(int x[ ], int y[ ], int n)
Polygon
Used to draw a polygon created by n line
segments. The command will close the
polygon. (x-coordinates go in one array with
accompanying y-coordinates in the other)

g.drawString("Java is cool!", 40, 70);


drawString(String str, int x, int y);
String Draws a string starting at the point indicated
(text) by (x,y). Be sure you leave enough room
from the top of the screen for the size of the
font.

SAMPLE EXAMPLE
Drawing Rectangles
Type in the following program code and save it as a text file named "Rectangles.java". There
are two important parts to the name of this file. The first part (the "Rectangles" part) is the
name of the class which is saved in this file. The suffix (the "java" part) tells the computer
that yes, this file does contain Java code.
import java.applet.Applet;
import java.awt.*;

public class Rectangles extends Applet {

public void paint (Graphics g) {

g.drawRect(20, 20, 30, 50); // 1


g.drawRect(70, 40, 60, 10); // 2
g.drawRect(150, 30, 30, 30); // 3

g.fillRect(20, 100, 50, 30); // 4


g.fillRect(100, 100, 20, 40); // 5
}
}
Now type in the small html file below and save it as a text file named "Rectangles.html". The
important part of the name for this file is the suffix, the ".html" part which tells the computer
that this file is meant to be read by an internet browser.
<html>
<title>Working With Graphics In Java</title>

<applet code= "Rectangles.class" width=325 height=275>

</applet>
</html>
Run this program.
Look at the applet that the code produced. In line 2, was the "70" used for the x position, the
y position, the height or the width of the rectangle?
How about the other values?
(Hint: pixel (0,0) is in the top-left corner of the window.)
Below is a picture of the rectangles. Match each rectangle to its line number by writing that
number beside the rectangle.

Type in the following program code and save it as a text file named "Ovals.java".
import java.applet.Applet;
import java.awt.*;

public class Ovals extends Applet {

public void paint (Graphics g) {

g.drawOval(20, 20, 30, 50); //


g.drawOval(70, 40, 60, 10); // 2

g.drawOval(150, 30, 30, 30); // 3


g.fillOval(150, 30, 30, 30); // 4

g.drawRect(100, 100, 50, 30); // 5


g.drawOval(100, 100, 50, 30); // 6
}
}
Make a copy of the html file you used to run class Rectangles and save it as "Ovals.html".
Edit it so that it refers to class Ovals. Run this program.

PAINT MODE

Setting the paint mode


The paint mode determines how objects are drawn in a window. It is possible to have new
objects XORed on to the window by using setXORMode().

Syntax:

void setXORMode(Color XORColor)

XORColor:-color that will be XORed to the window when an object is drawn.


The advantage of XORMode is that the new object is always guaranteed to be visible no
matter what color the object is drawn over.

To return the overwrite mode,call setPaintMode().

Syntax:

void setPaintMode()

Eg:-

/*<applet code="XOR" width=200 height=100> </applet>*/

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class XOR extends Applet

{
int x=100,y=50;

public void paint(Graphics g)

{
g.setXORMode(Color.green);
g.drawLine(chsx-50,chsy,chsx+10,chsy);
g.setPaintMode();
}
}

FONTS
A font represents a combination of a font name (like Monospaced), font style (like bold) and
font size (like 20)
The Font constructor takes three parameters to create a Font object.
Syntax:
Font f1 = new Font(String fontName, int fontStyle, int fontSize);

Example:
Font newFont = new Font("Serif", Font.BOLD, 24);.
To give the font style as an integer value, the Font class comes with 3 symbolic constants.
public final static int PLAIN = 0;

public final static int BOLD = 1;

public final static int ITALIC = 2;


There are five font style attributes supported by JVM are
Monospaced
Serif
SansSerif
Dialog
DialogInput
Font f1 = new Font("Monospaced", Font.BOLD, 15);
Font f2 = new Font("Serif", Font.ITALIC, 20);
Font f3 = new Font("SansSerif", Font.PLAIN, 19);
Font f4 = new Font("DialogInput", Font.BOLD + Font.ITALIC, 25);

Sample coding using Font class:


Font courierBold10 = new Font("Courier", Font.BOLD, 10);
g.setColor(Color.red);
g.setFont(courierBold10);
g.drawString("Java Rules!!!", 120, 120);
Font getFont (String name)
The getFont() method gets the font specified by the system property name.

Text and Graphics


 If you have a paragraph of styled text that you would like to fit within a specific
width, you can use the LineBreakMeasurer class.
 This class enables styled text to be broken into lines so that they fit within a particular
visual advance.
 Each line is returned as a TextLayout object, which represents unchangeable, styled
character data. However, this class also enables access to layout information.
 The getAscent and getDescent methods of TextLayout return information about the
font that is used to position the lines in the component.
 The text is stored as an AttributedCharacterIterator object so that the font and point
size attributes can be stored with the text.
 The following applet positions a paragraph of styled text within a component, using
LineBreakMeasurer, TextLayout and AttributedCharacterIterator.

AWT CONTROLS:
 Controls Are components that allow a user to interact with your application in various
ways.
 LayoutManager automatically positions within a container.
 The appearance of a window is a combination of such controls and Layoutmanagers.

Control Fundamentals

AWT supports the following controls:

 Labels
 Push Buttons
 Check Boxes
 Choice Lists
 Lists
 Scroll Bars
 Text Editing

They are the subclasses of ‘Component’

How to add or remove controls?

 Create an instance of desired control and then add it to the window by calling add()
method.

Syntax:-
Component add(Component obj)

 We can also remove our control from window by calling remove() method.

Syntax:-
Void remove(Component obj)

And also controls can be removed by calling removeAll()

LABEL
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.LABEL

A label displays a single line of read-only text. However the text can be changed by the
application programmer but cannot be changed by the end user in any way.
Label()
1
Constructs an empty label.
Label(Stringtext)
2
Constructs a new label with the specified string of text, left justified.

Label(Stringtext,intalignment)
3
Constructs a new label that presents the specified string of text with the specified alignment.
Following are the fields for java.awt.Component class:
 static int CENTER -- Indicates that the label should be centered.
 static int LEFT -- Indicates that the label should be left justified.
 static int RIGHT -- Indicates that the label should be right justified.
METHODS
addNotify
public void addNotify()
Creates the peer for this label. The peer allows us to modify the appearance of the
label without changing its functionality.
getAlignment
public int getAlignment()
Gets the current alignment of this label. Possible values are Label.LEFT,
Label.RIGHT, and Label.CENTER.
setAlignment
public synchronized void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment. Possible values are
Label.LEFT, Label.RIGHT, and Label.CENTER.
Parameters:
alignment - the alignment to be set.
Throws: IllegalArgumentException
if an improper value for alignment is given.
getText
public String getText()
Gets the text of this label.
Returns:
the text of this label.
setText
public synchronized void setText(String text)
Sets the text for this label to the specified text.
Parameters:
text - the text that this label presents.
paramString
protected String paramString()
Returns the parameter string representing the state of this label. This string is useful
for debugging.
Returns:
the parameter string of this label.
BUTTON:

The java.awt package comes with many GUI components of which Button is the most
important and most frequently used. A button functionality (what for it is) can be known by
its label like OK or Cancel etc. A mouse click on the button generates an action. –

Any GUI component with event handling can be broadly divided into 8 steps.
1. Import java.awt and java.awt.event packages
2. Extending frame or applet and implementing appropriate listener interface that can
handle the events of the component successfully.
3. Set the layout.
4. Create components
5. Register or link the component with the listener interface
6. Beautification of the components (optional)
7. Adding the components to the frame or applet
8. Override all the abstract methods of the listener interface

java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Button

Button()
Constructs a Button with no label.
Button(String)
Constructs a Button with the specified label.

METHODS
addActionListener(ActionListener)
Adds the specified action listener to receive action events from this button.
addNotify()
Creates the peer of the button.
getActionCommand()
Returns the command name of the action event fired by this button.
getLabel()
Gets the label of this button.
paramString()
Returns the parameter string representing the state of this button.
processActionEvent(ActionEvent)
Processes action events occurring on this button by dispatching them to any registered
ActionListener objects.
processEvent(AWTEvent)
Processes events on this button.
removeActionListener(ActionListener)
Removes the specified action listener so that it no longer receives action events from
this button.
setActionCommand(String)
Sets the command name for the action event fired by this button.
setLabel(String)
Sets the button's label to be the specified string.

MENUS:
A menu is a group of commands located in a menubar. A toolbar has buttons with some
common commands in the application.

The Menu Component Hierarchy

Menu class: It is used to create menus in java.awt package.


Types of constructors defined by Menu class:
Type-1: To create a default menu.
Menu( )
Type-2: By using name of menu selection.
Menu(String optname)
Type-3: By freeing a menu from menu bar. If removable is true, menu can be removed from
menu bar. If it is false the menu remains attached.
Menu(String optname, boolean removable)
CheckboxMenuItem class: It is used to create a checkable menu item. It is a subclass of
MenuItem class.
Types of constructors defined by CheckboxMenuItem class:
Type-1: To create a default check box menu item.
CheckboxMenuItem( )
Type-2: By using name of check box menu item.
CheckboxMenuItem(String itemName)
Type-3: By using name of check box menu item and to check the entry.
CheckboxMenuItem(String itemName, boolean on)
Types of methods defined by CheckboxMenuItem class:
getState( ) method: It is used to get the status of checkable menu item.
Syntax:
boolean getState( )
setState( ) method: It is used to set the status of checkable menu item.
Syntax:
void setState(boolean checked)
CLASS METHODS OF MENU:
S.N. Method & Description
MenuItemadd(MenuItemmi)
1
Adds the specified menu item to this menu.
voidadd(Stringlabel)
2
Adds an item with the specified label to this menu.
voidaddNotify()
3
Creates the menu's peer.
voidaddSeparator()
4
Adds a separator line, or a hypen, to the menu at the current position.
intcountItems()
5 Deprecated. As of JDK version 1.1, replaced by getItemCount().

AccessibleContextgetAccessibleContext()
6
Gets the AccessibleContext associated with this Menu.
MenuItemgetItem(intindex)
7
Gets the item located at the specified index of this menu.
intgetItemCount()
8
Get the number of items in this menu.
voidinsert(MenuItemmenuitem,intindex)
9
Inserts a menu item into this menu at the specified position.
voidinsert(Stringlabel,intindex)
10
Inserts a menu item with the specified label into this menu at the specified position.
voidinsertSeparator(intindex)
11
Inserts a separator at the specified position
booleanisTearOff()
12
Indicates whether this menu is a tear-off menu.
StringparamString()
13
Returns a string representing the state of this Menu.
voidremove(intindex)
14
Removes the menu item at the specified index from this menu.
voidremove(MenuComponentitem)
15
Removes the specified menu item from this menu.
voidremoveAll()
16
Removes all items from this menu.
voidremoveNotify()
17
Removes the menu's peer.

HANDLING EVENTS BY EXTENDING AWT COMPONENTS


 The Event listener represent the interfaces responsible to handle events.
 Every method of an event listener method has a single argument as an object which is
subclass of EventObject class.
 For example, mouse event listener methods will accept instance of MouseEvent,
where MouseEvent derives from EventObject.
 EventListner interface
 It is a marker interface which every listener interface has to extend.This class is
defined in java.util package.
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.
Sr. No. Control & Description
ActionListener
1
This interface is used for receiving the action events.
2 ComponentListener
This interface is used for receiving the component events.
ItemListener
3
This interface is used for receiving the item events.
KeyListener
4
This interface is used for receiving the key events.
MouseListener
5
This interface is used for receiving the mouse events.
TextListener
6
This interface is used for receiving the text events.
WindowListener
7 This interface is used for receiving the window events

AdjustmentListener
8
This interface is used for receiving the adjusmtent events.
ContainerListener
9
This interface is used for receiving the container events.
MouseMotionListener
10
This interface is used for receiving the mouse motion events.
FocusListener
11
This interface is used for receiving the focus events.

Applet fundamentals – Applet Class – Understanding HTML Applet Tag.

APPLET
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

APPLET FUNDAMENTALS
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following:
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet:
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
 Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.

Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life cycle methods for an applet.
java.applet.Applet class:
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.

4. public void destroy(): is used to destroy the Applet. It is invoked only once.
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Four methods in the Applet class give you the framework on which you build any serious
applet:
 init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having
gone off to other pages.
 stop: This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}

}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

A "Hello, World" Applet:


The following is a simple applet named HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}}

The Applet CLASS:


Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following:
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may:
 Request information about the author, version and copyright of the applet
 Request a description of the parameters the applet recognizes
 Initialize the applet
 Destroy the applet
 Start the applet's execution
 Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.
Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example
that invokes the "Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
 The code attribute of the <applet> tag is required.
 It specifies the Applet class to run. Width and height are also required to specify the
initial size of the panel in which an applet runs.
 The applet directive must be closed with a </applet> tag.
 If an applet takes parameters, values may be passed for the parameters by adding
<param> tags between <applet> and </applet>.
 The browser ignores text and other tags between the applet tags.
 Non-Java-enabled browsers do not process <applet> and </applet>.
 Therefore, anything that appears between the tags, not related to the applet, is visible
in non-Java-enabled browsers.
 The viewer or browser looks for the compiled Java code at the location of the
document. To specify otherwise, use the codebase attribute of the <applet> tag as
shown:
<applet codebase="http://amrood.com/applets"
 code="HelloWorldApplet.class" width="320" height="120">
 If an applet resides in a package other than the default, the holding package must be
specified in the code attribute using the period character (.) to separate package/class
components.

For example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120"

Understanding HTML Applet Tag.

The HTML <applet> tag specifies an applet. It is used for embedding a Java applet within an
HTML document. It is not supported in HTML5.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code="newClass.class" width="300" height="200">
</applet>
</body>
</html>
Here is the newClass.java file:
import java.applet.*;
import java.awt.*;

public class newClass extends Applet


{
public void paint (Graphics gh)
{
g.drawString("Tutorialspoint.com", 300, 150);
}
}
This will produce following result:
Specific Attributes

ALT = alternateText
This OPTIONAL attribute specifies any text that should be displayed if the browser
understands the APPLET tag but can't run Java applets.
NAME = appletInstanceName
This OPTIONAL attribute specifies a name for the applet instance, which makes it
possible for applets on the same page to find (and communicate with) each other.
WIDTH = pixels HEIGHT = pixels
These REQUIRED attributes give the initial width and height (in pixels) of the applet
display area, not counting any windows or dialogs that the applet brings up.
ALIGN = alignment
This OPTIONAL attribute specifies the alignment of the applet. The possible values
of this attribute are the same as those for the IMG tag: left, right, top, texttop, middle,
absmiddle, baseline, bottom, absbottom.
VSPACE = pixels HSPACE = pixels
These OPTIONAL attributes specify the number of pixels above and below the applet
(VSPACE) and on each side of the applet (HSPACE). They're treated the same way
as the IMG tag's VSPACE and HSPACE attributes.
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value> . . .
This tag is the only way to specify an applet-specific attribute. Applets access their
attributes with the getParameter() method.

Unit - IV
Inheritance Basics – Using Super – Creating a Multilevel Hierarchy – When Constructors are
called – Method Overriding – Dynamic Method Dispatch – Using Abstract Classes – Using
final with Inheritance – The Object Class.
Packages – Access Protection – Importing Packages – Interfaces.

Inheritance Basics

Note:Refer program explained in class

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new
class is called a subclass.

SAMPLE PROGRAM:

class Employee
{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Multiple inheritance is not supported in java through class.

Single Inheritance example program in Java

Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Multilevel Inheritance example program in Java

Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}

Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Member access and inheritance:


Subclass include all the member of super class.
It cannot access those member of superclass that have declared as private.

Using Super
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
super Usage:
1) super.<variable_name> refers to the variable of variable of parent class.
2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
Problem without super keyword
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Test it Now :Output:100

 In the above example Vehicle and Bike both class have a common property speed.
Instance variable of current class is refered by instance bydefault, but I have to refer
parent class instance variable that is why we use super keyword to distinguish
between parent class instance variable and current class instance variable.
Solution by super keyword
//example of super keyword

class Vehicle{
int speed=50;
}

class Bike4 extends Vehicle{


int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();

}
}
Test it Now
Output:50

Multilevel Hierarchy in java programming

inheritance a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance a subclass is derived from a derived class. One class inherits only
single class. Therefore, in multilevel inheritance, every time ladder increases by one. The
lower most class will have the properties of all the super classes’.

class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}

public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

Constructor
 A java constructor has the same name as the name of the class to which it belongs.
 Java constructors are the methods which are used to initialize objects.
 Constructor method has the same name as that of class, they are called or invoked
when an object of class is created and can't be called explicitly.
 Attributes of an object may be available when creating objects if no attribute is
available then default constructor is called, also some of the attributes may be known
initially. It is optional to write constructor method in a class but due to their utility
they are used.

 Constructors may include parameters of various types. When the constructor is


invoked using the new operator, the types must match those that are specified in the
constructor definition.

 Java provides a default constructor which takes no arguments and performs no special
actions or initializations, when no explicit constructors are provided.
 The only action taken by the implicit default constructor is to call the superclass
constructor using the super() call. Constructor arguments provide you with a way to
provide parameters for the initialization of an object.

class Programming {
//constructor method
Programming() {
System.out.println("Constructor method called.");
}
public static void main(String[] args) {
Programming object = new Programming(); //creating object
}
}

When constructor are called :Note:Example program refer class notes


From super class to sub class constructer are called
public class Cube1 {

int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}

Method Overriding: Example program refer class notes


Method overriding, in object oriented programming, is a language feature that allows a
subclass or child class to provide a specific implementation of a method that is already
provided by one of its superclasses or parent classes.
class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{


public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}

This would produce the following result:


Animals can move
Dogs can walk and run
Rules for method overriding:
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level.
For example: if the superclass method is declared public then the overridding method
in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared
public or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
 Constructors cannot be overridden.
Using the super keyword:
When invoking a superclass version of an overridden method the super keyword is used.
class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[]){

Animal b = new Dog(); // Animal reference but Dog object


b.move(); //Runs the method in Dog class

}
}
This would produce the following result:
Animals can move
Dogs can walk and run

Dynamic Method Dispatch


 Method overriding forms the basis for one of Java’s most powerful concepts: dynamic
method dispatch.
 Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time.
 Dynamic Method Dispatch is related to a principle that states that an super class
reference can store the reference of subclass object.
 However, it can't call any of the newly added methods by the subclass but a call to an
overridden methods results in calling a method of that object whose reference is
stored in the super class reference.
 It simply means that which method would be executed, simply depends on the object
reference stored in super class object.

upcasting:
When parent class reference variable refers to child class object ,it is called upcasting

Example for Dynamic Method Dispatch

class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme() // override callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
void callme() // override callme()
{
System.out.println("Inside C's callme method");
}
}

public class Dynamic_disp


{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

ABSTRACT CLASS
 An abstract class is a class that is declared abstract—it may or may not include abstract
methods.
 Abstract classes cannot be instantiated, but they can be subclassed.
 Abstract classes are classes that contain one or more abstract methods. An abstract
method is a method that is declared, but contains no implementation. Abstract classes
may not be instantiated, and require subclasses to provide implementations for the
abstract methods.

Declaring an Abstract Class


 You declare that a class is abstract by adding the abstract keyword to the class
declaration. Here is an example:
public abstract class MyAbstractClass {

}
Abstract Methods
 An abstract class can have abstract methods. You declare a method abstract by adding
the abstract keyword in front of the method declaration. Here is how that looks:
public abstract class MyAbstractClass {

public abstract void abstractMethod();


}
 An abstract method has no implementation.
 It just has a method signature.
 If a class has an abstract method, the whole class must be declared abstract.
 Not all methods have to be abstract, even if the class is abstract.
 An abstract class can have a mixture of abstract and non-abstract methods.
 Subclasses of an abstract class must implement (override) all abstract methods of its
abstract superclass.
 The non-abstract methods of the superclass are just inherited as they are.
 They can also be overridden, if needed.
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}

Using final:
 The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
 The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable.
 It can be initialized in the constructor only.
 The blank final variable can be static also which will be initialized in the static block
only.

class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it Now
Output:running...

Using final to Prevent Overriding

 While method overriding is one of Java’s most powerful features.To disallow a


method from being overridden,specify final as a modifier at the start of its declaration.
 Methods declared as final cannot be overridden.
Example1:using final to Prevent Overriding

class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Here meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result.
Using final to Prevent Inheritance
 Sometimes you will want to prevent a class from being inherited. To do this, precede
the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too. As you
might expect, it is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies upon its subclasses to provide complete
implementations.

An example of a final class:


final class A
{
// ...
}
// The following class is illegal.
class B extends A // ERROR! Can't subclass A
{
// ...
}

As the comments imply, it is illegal forBto inherit A since A is declared as final.


Using object class
 The Object class is the parent class of all the classes in java bydefault. In other
words, it is the topmost class of java.
 The Object class is beneficial if you want to refer any object whose type you don't
know. Notice that parent class reference variable can refer the child class object,
know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Class methods
S.N. Method & Description
protected Object clone()
1
This method creates and returns a copy of this object.
boolean equals(Object obj)
2
This method indicates whether some other object is "equal to" this one.
protected void finalize()
3 This method is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
Class<?> getClass()
4 This method returns the runtime class of this Object.

int hashCode()
5
This method returns a hash code value for the object.
void notify()
6
This method wakes up a single thread that is waiting on this object's monitor.
void notifyAll()
7
This method wakes up all threads that are waiting on this object's monitor.
String toString()
8
This method returns a string representation of the object.
void wait()
9 This method causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
void wait(long timeout)
This method causes the current thread to wait until either another thread invokes the
10
notify() method or the notifyAll() method for this object, or a specified amount of time
has elapsed.
void wait(long timeout, int nanos)
This method causes the current thread to wait until another thread invokes the notify()
11
method or the notifyAll() method for this object, or some other thread interrupts the
current thread, or a certain amount of real time has elapsed.

Packages
 Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and
annotations easier, etc.
 A Package can be defined as a grouping of related types(classes, interfaces,
enumerations and annotations ) providing access protection and name space
management.
 Package = directory. Java classes can be grouped together in packages. A package
name is the same as the directory (folder) name which contains the .java files. You
declare packages when you define your Java program, and you name the packages
you want to use from other libraries in an import statement.
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

Package declaration
 The first statement, other than comments, in a Java source file, must be the package
declaration.
 Following the optional package declaration, you can have import statements, which
allow you to specify classes from other packages that can be referenced without
qualifying them with their package.
Default package.
 All Java classes are in a directory, it's possible to omit the package declaration. For
small programs it's common to omit it, in which case Java creates what it calls a
default package. Sun recommends that you do not use default packages.
Package declaration syntax
The statement order is as follows. Comments can go anywhere.
1. Package statment (optional).
2. Imports (optional).
3. Class or interface definitions.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Some of the existing packages in Java are::


 java.lang - bundles the fundamental classes
 java.io - classes for input , output functions are bundled in this package
Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.

Access protection:
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
 Visible to the package. the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within
the declared class itself.
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be accessed from any other
class.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.

Importing package in java


In a Java source file, import statements occur immediately following the package statement
(if it exists) and before any class definitions
. This is the general form of the importstatement:
import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed by the
file system. Finally, you specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.
This code fragment shows both forms in use:
importjava.util.Date;
import java.io.*;

Unit - II
Operators – Arithmetic operators – Bitwise operators – Relational operators – Relational
operators – Boolean operators – Logical operators – Assignment operators? Operators -
Control
statement – Selection statements – if, switch, iteration statements – while, do while, for,
nested
loops – jump statements, break, continue, return statements.

Operators:Note:for sample program refer class note also

Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
The Arithmetic Operators:
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication,
division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and
negation.
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Show Examples
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
Subtraction - Subtracts right hand operand from left hand A - B will give -
-
operand 10
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and
% B % A will give 0
returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

The Relational Operators:


There are following relational operators supported by Java language
Relational operators in Java are used to compare 2 or more objects. Java provides six
relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==),
and not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.

Assume variable A holds 10 and variable B holds 20, then


Operator Description Example
Checks if the values of two operands are equal or not, if yes (A == B) is not
==
then condition becomes true. true.
Checks if the values of two operands are equal or not, if values
!= (A != B) is true.
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of (A > B) is not
>
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than or equal to the
<= (A <= B) is true.
value of right operand, if yes then condition becomes true.

public class RelationalOperatorsDemo {


public RelationalOperatorsDemo( ) {

int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}

public static void main(String args[]){


new RelationalOperatorsDemo();
}
}

The Bitwise Operators:


 Java provides Bit wise operators to manipulate the contents of variables at the bit
level.
 These variables must be of numeric data type ( char, short, int, or long). Java provides
seven bitwise operators. They are AND, OR, Exclusive-OR, Complement, Left-shift,
Signed Right-shift, and Unsigned Right-shift.
 The result of applying bitwise operators between two corresponding bits in the
operands is shown in the Table below.

Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b =
13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Show Examples
Operator Description Example
(A & B) will give
Binary AND Operator copies a bit to the result if it exists in
& 12 which is 0000
both operands.
1100
(A | B) will give
| Binary OR Operator copies a bit if it exists in either operand. 61 which is 0011
1101
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one operand
^ 49 which is 0011
but not both.
0001
(~A ) will give -61
which is 1100
Binary Ones Complement Operator is unary and has the effect 0011 in 2's
~
of 'flipping' bits. complement form
due to a signed
binary number.
A << 2 will give
Binary Left Shift Operator. The left operands value is moved
<< 240 which is 1111
left by the number of bits specified by the right operand.
0000
Binary Right Shift Operator. The left operands value is moved A >> 2 will give
>>
right by the number of bits specified by the right operand. 15 which is 1111
Shift right zero fill operator. The left operands value is moved A >>>2 will give
>>> right by the number of bits specified by the right operand and 15 which is 0000
shifted values are filled up with zeros. 1111

The Logical Operators:


Logical operators return a true or false value based on the state of the Variables.
There are six logical, or boolean, operators.
They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT.
Each argument to a logical operator must be a boolean data type, and the result is always a
boolean data type.
An example program is shown below that demonstrates the different Logical operators in
java.
The following table lists the logical operators:
public class LogicalOperatorsDemo {

public LogicalOperatorsDemo() {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
public static void main(String args[]) {
new LogicalOperatorsDemo();
}
}

Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
Called Logical AND operator. If both the operands are non- (A && B) is
&&
zero, then the condition becomes true. false.
Called Logical OR Operator. If any of the two operands are
|| (A || B) is true.
non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state
!(A && B) is
! of its operand. If a condition is true then Logical NOT operator
true.
will make false.
The Assignment Operators:
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo {
public AssignmentOperatorsDemo() {
// Assigning Primitive Values
int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : " + j);
System.out.println("k is : " + k);
// Assigning References
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
i1 = i2;
System.out.println("i1 is : " + i1);

System.out.println("i2 is : " + i2);


// Multiple Assignments
k = j = 10; // (k = (j = 10))
System.out.println("j is : " + j);
System.out.println("k is : " + k);
}
public static void main(String args[]) {
new AssignmentOperatorsDemo();
}
}

There are following assignment operators supported by Java language:


Show Examples
Operator Description Example
C = A + B will
Simple assignment operator, Assigns values from right side
= assign value of A
operands to left side operand
+ B into C
C += A is
Add AND assignment operator, It adds right operand to the left
+= equivalent to C =
operand and assign the result to left operand
C+A
C -= A is
Subtract AND assignment operator, It subtracts right operand
-= equivalent to C =
from the left operand and assign the result to left operand
C-A
C *= A is
Multiply AND assignment operator, It multiplies right operand
*= equivalent to C =
with the left operand and assign the result to left operand
C*A
C /= A is
Divide AND assignment operator, It divides left operand with
/= equivalent to C =
the right operand and assign the result to left operand
C/A
C %= A is
Modulus AND assignment operator, It takes modulus using two
%= equivalent to C =
operands and assign the result to left operand
C%A
C <<= 2 is same
<<= Left shift AND assignment operator
as C = C << 2
C >>= 2 is same
>>= Right shift AND assignment operator
as C = C >> 2
C &= 2 is same as
&= Bitwise AND assignment operator
C=C&2
C ^= 2 is same as
^= bitwise exclusive OR and assignment operator
C=C^2
C |= 2 is same as
|= bitwise inclusive OR and assignment operator
C=C|2
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;

System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
This would produce the following result:
Value of b is : 30
Value of b is : 20

Control statement – Selection statements – if, switch, iteration statements – while, do


while, for, nested loops – jump statements, break, continue, return statements.

Control statement
Java Control statements control the order of execution in a java program, based on data
values and conditional logic. There are three main categories of control flow statements;
· Selection statements: if, if-else and switch.
· Loop statements: while, do-while and for.
· Transfer statements: break, continue, return, try-catch-finally and assert.
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest of the
program.
You can either have a single statement or a block of code within an if statement.
Note that the conditional expression must be a Boolean expression.

The simple if statement has the following syntax:


if (<conditional expression>)
<statement action>
Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}
Output
b>a

The If-else Statement


The if/else statement is an extension of the if statement.
If the statements in the if statement fails, the statements in the else block are executed.
You can either have a single statement or a block of code within if-else blocks.
Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
Below is an example that demonstrates conditional execution based on if else statement
condition.

public class IfElseStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
} else {
System.out.println("b > a");
}
}
}
Output
b>a

Switch Case Statement (Example program refer class note)


The switch case statement, also called a case statement is a multi-way branch with several
choices.
A switch is easier to implement than a series of if/else statements.
The switch statement begins with a keyword, followed by an expression that equates to a no
long integral value.
Following the controlling expression is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique.
When the switch statement executes, it compares the value of the controlling expression to
the values of each case label.
The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the switch statement
code block will be executed.
Java includes a default label to use in cases where there are no matches. We can have a
nested switch within a case block of an outer switch.
Its general form is as follows:
switch (expression)
{
case label1:
<statement1>
case label2:
<statement2>

case labeln:
<statementn>
default:
<statement>
} // end switch
Public class Test {

public static void main(String args[])


{
char grade = 'C';

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;

case 'B' :
case 'C' :

System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
OutPut
$ java Test
Well done
Your grade is a C
$

The while and do-while Statements


The while statement continually executes a block of statements while a particular condition is
true. Its syntax can be expressed as:
while (expression)
{
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while block.
The while statement continues testing the expression and executing its block until the
expression evaluates to false. Using the while statement to print the values from 1 through 10
can be accomplished as in the following WhileDemo program:

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true)
{
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed
as follows:
Do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once, as shown in the following DoWhileDemo program:

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);

count++;
} while (count < 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:

class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Nested Loops
Loop within another loop is nested loop

for (int i = 1; i <= n; i++) {


for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

The break Statement


The break statement has two forms: labeled and unlabeled.
You saw the unlabeled form in the previous discussion of the switch statement
You can also use an unlabeled break to terminate a for, while, or do-while loop
for(int var =0; var < 5 ; var++)
{
System.out.println(“Var is : “ + var);
if(var == 3)
break;
}

Example:
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

 The break statement terminates the labeled statement; it does not transfer the flow of
control to the label.
 Control flow is transferred to the statement immediately following the labeled
(terminated) statement.
The continue Statement
 The continue statement skips the current iteration of a for, while , or do-while loop.
 The unlabeled form skips to the end of the innermost loop's body and evaluates the
boolean expression that controls the loop.
 A labeled continue statement skips the current iteration of an outer loop marked with
the given label
 Continue statement is used when we want to skip the rest of the statement in the body
of the loop and continue with the next iteration of the loop.
There are two forms of continue statement in Java.
1. Unlabeled Continue Statement
2. Labeled Continue Statement
Unlabeled Continue Statement
This form of statement causes skips the current iteration of innermost for, while or do while
loop.

For example,
for(int var1 =0; var1 < 5 ; var1++)
{
for(int var2=0 ; var2 < 5 ; var2++)
{
if(var2 == 2)
continue;
System.out.println(“var1:” + var1 + “, var2:”+ var2);
}
}

In above example, when var2 becomes 2, the rest of the inner for loop body will be skipped.
Labeled Continue Statement
Labeled continue statement skips the current iteration of the loop marked with the specified
label. This form is used with nested loops.
For example,
Outer:
for(int var1 =0; var1 < 5 ; var1++)
{

for(int var2=0 ; var2 < 5 ; var2++)


{
if(var2 == 2)
continue Outer;

System.out.println(“var1:” + var1 + “, var2:”+ var2);

The return Statement


The last of the branching statements is the return statement.
The return statement exits from the current method, and control flow returns to where the
method was invoked.
The return statement has two forms: one that returns a value, and one that doesn't. To return a
value, simply put the value (or an expression that calculates the value) after the return
keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return
value.
When a method is declared void, use the form of return that doesn't return a value.
return;

Unit - I
Internet – Overview –Internet Protocols – Internet address – Internet access – Applications –
Future of Internet and intranet related Applications. – Basic concepts of OOP – benefits of
OOP
– Object Oriented applications of OOP – Data types, variables and arrays – Programs with
input,
numeric input – type conversion and casting.

Internet – Overview
 The Internet is a collection of computers connected by network cables or through
satellite links. Rather than connecting every computer on the Internet with every other
computer, individual computers in an organization are normally connected in a local
area network (LAN). One node on this local area network is physically connected to
the Internet. So the Internet is a network of networks . There are millions of
computing devices that are connected to this network either permanently or for a short
duration. These devices run network applications that communicate through copper or
fiber optic cables, radio or satellite transmission. The communication is governed by
protocols established by an international body.

Internet Protocols
 Among the most common Internet protocols are FTP (File Transfer Protocol), HTTP
(Hypertext Transfer Protocol), TCP/IP (Transfer Control Protocol/Internet
Protocol), and SMTP (Simple Mail Transfer Protocol). A uniform set of rules that
enable two devices to connect and transmit data to one another.
 Short for Internet Protocol. IP specifies the format of packets, also called datagrams,
and the addressing scheme. Most networks combine IP with a higher-level protocol
called Transmission Control Protocol (TCP), which establishes a virtual connection
between a destination and a source.
 IP by itself is something like the postal system. It allows you to address a package and
drop it in the system, but there's no direct link between you and the recipient. TCP/IP,
on the other hand, establishes a connection between two hosts so that they can send
messages back and forth for a period of time.
 The current version of IP is IPv4. A new version, called IPv6 or IPng, is under
development.

IP address
 An Internet address uniquely identifies a node on the Internet. Internet address may
also refer to the name or IP of a Web site (URL). The term Internet address can also
represent someone's e-mail address.
 An Internet Protocol address (IP address) is a numerical label assigned to each
device (e.g., computer, printer) participating in a computer network that uses the
Internet Protocol for communication. An IP address serves two principal functions:
host or network interface identification and location addressing.

Internet access

 Internet access connects individual computer terminals, computers, mobile devices,


and computer networks to the Internet, enabling users to access Internet services, such
as email and the World Wide Web. Internet service providers (ISPs) offer Internet
access through various technologies that offer a wide range of data signalling rates
(speeds).
Applications of Internet
 There are many different applications of the internet used commonly across the world.
The most common names are the JAVA, JAVA script and the Flash.
 These are the most useful as well as the most frequently used applications which need
to be installed on the computer before the full access of the internet can be
guaranteed.
 The flash is required for the animated videos and pictures. For example the electronic
greeting cards these days used extensively for various occasions all require the us if
the internet application Flash. Some websites which are used to upload videos online
like the most commonly used YouTube also require the latest flash player to work.
Every other website consists of flash content these days and so it is one of the most
useful applications of the internet.
 Another mentioned application which is also well-known is the JAVA; java is also
needed for the internet access to a certain extent. For example using the ftp services
on the internet, you need to have the JAVA technology JVM to be able to manage and
control the documentation transfers.
 These applications are basically used to run the applets on the internet web pages
which are made to work with them, without these tools the internet though can be
easily accessed it does not offer all the features to the user, which might also be some
useful information.
 The internet applications all reduce the traffic on the network and thus make the
server work on a much optimized level. All the applications are interoperable, and
support the cross platforms, both of the OS servers and the clients.

Basic concept of OOP

 Object Oriented Programming is a paradigm that provides many concepts such as


inheritance, data binding, polymorphism etc.
 Simula is considered as the first object-oriented programming language. The
programming paradigm where everything is represented as an object, is known as
truly object-oriented programming language.
 Smalltalk is considered as the first truly object-oriented programming language.
 OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

What Is an Interface?
An interface is a contract between a class and the outside world. When a class implements an
interface, it promises to provide the behavior published by that interface. This section defines
a simple interface and explains the necessary changes for any class that implements it.
What Is a Package?
A package is a namespace for organizing classes and interfaces in a logical manner. Placing
your code into packages makes large software projects easier to manage. This section
explains why this is useful, and introduces you to the Application Programming Interface
(API) provided by the Java platform.

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global
data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.

Data type
 Variables are nothing but reserved memory locations to store values.
 This means that when you create a variable you reserve some space in memory.
 Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.
 By assigning different data types to variables, you can store integers, decimals, or
characters in these variables.
There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by
the language and named by a keyword. Let us now look into detail about the eight primitive
data types.
byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an int.
 Example: byte a = 100 , byte b = -50
short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int
 Default value is 0.
 Example: short s = 10000, short r = -20000
int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000
long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.

Float is mainly used to save memory in large arrays of floating point numbers.

Default value is 0.0f.

Float data type is never used for precise values such as currency.

Example: float f1 = 234.5f

double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values, generally
the default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example: double d1 = 123.4
boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true
char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'
Reference Data Types:
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");

Variable
 A variable provides us with named storage that our programs can manipulate.
 Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
 You must declare all variables before they can be used.
The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
There are three kinds of variables in Java:
 Local variables
 Instance variables
 Class/static variables
There are three kinds of variables.
 instance variables Any method in the class definition can access these variables
 parameter variables Only the method where the parameter appears can access these
variables. This is how information is passed to the object.
 local variables Only the method where the parameter appears can access these
variables. These variables are used to store intermediate results.

Local variables:
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables so local variables should be declared and
an initial value should be assigned before the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]){


Test test = new Test();
test.pupAge();
}
}

Instance variables:
 Instance variables are declared in a class, but outside a method, constructor or any
block.
 When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
 Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However
visibility for subclasses can be given for these variables with the use of access
modifiers.
 Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during
the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the
class. However within static methods and different class ( when instance variables are
given accessibility) should be called using the fully qualified name .
ObjectReference.VariableName.

Example:
import java.io.*;

public class Employee{


// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName){
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal){
salary = empSal;
}

// This method prints the employee details.


public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]){


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This would produce the following result:
name : Ransika
salary :1000.0
Class/static variables:
 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.
 Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned
during the declaration or within the constructor. Additionally values can be assigned
in special static initializer blocks.
 Static variables can be accessed by calling with the class name .
ClassName.VariableName.
 When declaring class variables as public static final, then variables names (constants)
are all in upper case. If the static variables are not public and final the naming syntax
is the same as instance and local variables.
Example:
import java.io.*;

public class Employee{


// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]){


salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000

Scope and Lifetime of Variables

The scope of a variable defines the section of the code in which the variable is visible.
As a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables
when declaring it. Scope refers to the range of code where you can access a variable.
 method body scope Variable is accessible in method body only (local variables,
parameters)
 class definition scope Variable is accessible i class definition (instance variables)
Lifetime refers to the amount of time a variable (or object) exists. Since object variables are
both a box (holding a handle) and an object, the lifetimes may differ. An object variable
could disappear (for example, a local variable disappears once you exit the method where the
local variable is declared), yet the object still exists.
We can divide lifetime into categories too:
 method body lifetime Exists on method body entry, disappears on method body exit.
(local variables, parameters)
 class definition lifetime Exists as long as object is around (instance variables)

Arrays
Note:Program refer claswork note

An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed. You
have seen an example of arrays already, in the main method of the "Hello World!"
application. This section discusses arrays in greater detail.

Each item in an array is called an element, and each element is accessed by its numerical
index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.

Declaring Array Variables:

Declaring an arraydataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.


int[] anArray;
Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator.
anArray = new int[10];

Multidimensional Array
The element type followed by a pair of square brackets

To use a multidimensional array to represent a multiplication table:


int[][] products;

– Programs with input, numeric input

Standard input and the io package


The program uses various classes (such as BufferedReader and InputStreamReader) that are
defined in the java.io package. It is thus necessary to import this package.
import java.io.*;
 Write a Java program with a main() method
 Use System.out.println to send output to the console
 Override the toString() method
 Use the Scanner class for keyboard input
 Read in both numeric and String data, taking care to avoid the pitfalls that may occur
with newline characters
Program:
import java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;

Scanner in = new Scanner(System.in);

System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string "+s);

System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer "+a);

System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

Type conversion and casting


If the two types are compatible, then Java will perform the conversion automatically.
For example, assign an int value to a long variable.
For incompatible types we must use a cast.
Casting is an explicit conversion between incompatible types.
Java's Automatic Conversions
An automatic type conversion will be used if the following two conditions are met:
The two types are compatible.
The destination type is larger than the source type
public class Main {
public static void main(String[] argv) {
byte b = 10;
int i = 0;

i = b;
System.out.println("b is " + b);
System.out.println("i is " + i);
}
}
The output:

b is 10
i is 10

Unit - III
Class fundamentals – Declaring Objects – Assigning Object Reference Variables –
Introducing
methods – Constructors – The this keyword – Garbage collection – The finalize () method.
Overloading Methods – Objects as Parameters – Arguments Passing – Returning Objects –
Recursion – Access Control – Static – Final – Arrays – Nested and Inner Classes – String
Class –
Command Line Arguments.

CLASS FUNDAMENTAL
 The most important thing to understand about a class is that it defines a new data type.
Once defined, this new type can be used to create objects of that type.
 Thus, a class is a template for an object, and an object is an instance of a class.
 Because an object is an instance of a class, you will often see the two words object
and instance used interchangeably.
1. A class is declared by use of the class keyword.
2. The general form of a class definition is shownhere:

class classname {
type instance-variable1;
type instance-variable2;
// ..
type instance-variableN;

type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list) {
//body of method
}
//..
type methodnameN(parameter-list) {
// body of method
}
}

The data, or variables, defined with a class are called instance variables.
The code is contained within methods. Collectively, the methods and variables
defined within a class are called members of the class.
In most classes, the instance variables are acted upon and accessed by the methods
defined for that class. Thus, it is the methods that determine how a class’ data can be used.

Variables defined within a class are called instance variables because each instance of
the class (that is, each object is separate and unique from the data for another.
All methods have the same general form as main (), which we have been using thus
far. However, most methods will not be specified as static or public.

Declaring objects
In object is created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name with an object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Example of creating an object is given below:
public class Puppy{

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Assigning Object Reference Variables
1. We can assign value of reference variable to another reference variable.
2. Reference Variable is used to store the address of the variable.
3. Assigning Reference will not create distinct copies of Objects.
4. All reference variables are referring to same Object.
Assigning Object Reference Variables does not -
1. Create Distinct Objects.
2. Allocate Memory
3. Create duplicate Copy
Consider This Example -
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
 r1 is reference variable which contain the address of Actual Rectangle Object.
 r2 is another reference variable
 r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it
does not create duplicate object , nor does it allocate extra memory.
Assigning Object Reference Variables
class Rectangle {
double length;
double breadth;
}

class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

r1.length = 10;
r2.length = 20;

System.out.println("Value of R1's Length : " + r1.length);


System.out.println("Value of R2's Length : " + r2.length);

}
}
Output :
C:Priteshjava>java RectangleDemo
Value of R1's Length : 20.0
Value of R2's Length : 20.0

Introducing Method in Java Class


Note:refer class note for program if needed
Classes usually consist of two things:- Instance variable and Methods.
The topic of methods is a large one because java gives them so much power and
flexibility.
However, there are some fundamentals that you need to learn now so that you can
begin to add methods to your classes.
This is the general form of a method:

Type name( parameter-list)


{
//body of method
}
Here, type specifies the type of data returned by the method.
 This can be any valid type, including class types that you create
 If the method does not return a value, its return type must be void.
 The name of the method is specified by name.
 This can be any legal identifier other than those already used by other items within the
current scope.
 The parameter-list is a sequence of type and identifier pairs separated by commas.
 Parameters are essentially variables that receive the value of the arguments passed to
the method when it is called. If the method has no parameters, then the parameter list
will be empty.
 Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;
Here, value is the value returned.

Adding a method to a class


 methods define the interface to most classes.
 This allows the class implementor to hide the specific layout of internal data
structures behind cleaner method abstractions. In addition to defining methods that
provide access to data, you can also define methods that are used internally by the
class itself.

Syntax : Methods in Java Classes


return_type method_name ( arg1 , arg2 , arg3 )
1. return_type is nothing but the value to be returned to an calling method.
2. method_name is an name of method that we are going to call through any method.
3. arg1,arg2,arg3 are the different parameters that we are going to pass to a method

class Rectangle {
double length;
double breadth;

void setLength(int len)


{
length = len;
}
}

class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle();

r1.length = 10;
System.out.println("Before Function Length : " + r1.length);

r1.setLength(20);
System.out.println("After Function Length : " + r1.length);

}
}
Output :
C:Priteshjava>java RectangleDemo
Before Function Length : 10.0
After Function Length : 20.0

(OR)

class Test
{
double item1;
double item2;
double item3;
void value()
{
System.out.println(“value is”);
System.out.println( item1 + item2 + item3);
}
}
class Testdemo()
{
public static void main (String args[])
{
Test test1 = new test();
Test test2 = new test();

test1.item1 = 10;
test1.item2 = 20;
test1.item3 = 15;

test2.item1 = 3;
test2.item2 = 6;
test2.item3 = 9;

test1.value();

test2.value();
}
}

This program generates the following output,


value is 45.0
value is 18.0

Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1
{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
class Student3
{
int id;
String name;

void display(){System.out.println(id+" "+name);}


public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
222 Aryan
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
Method is used to expose behaviour
Constructor is used to initialize the state of an object.
of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
Method name may or may not be
Constructor name must be same as the class name.
same as class name.
This Keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
Usage of java this keyword
 Here is given the 6 usage of java this keyword.
 This keyword can be used to refer current class instance variable.
 This() can be used to invoke current class constructor.
 This keyword can be used to invoke current class method (implicitly)
 This can be passed as an argument in the method call.
 This can be passed as argument in the constructor call.
 This keyword can also be used to return the current class instance.

Class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output111 Karan
222 Aryan

Garbage collection – The finalize () method.


Overloading Methods – Objects as Parameters – Arguments Passing – Returning Objects –
Recursion – Access Control – Static – Final – Arrays – Nested and Inner Classes – String
Class –Command Line Arguments.

Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?


There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
1. new Employee();

finalize() method
 The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing.
 This method is defined in Object class as:
protected void finalize()
{
}

 When we use final specifier with a method, the method cannot be overridden in any of
the inheriting classes. Methods are made final due to design reasons.
Since private methods are inaccessible, they are implicitly final in Java. So adding
final specifier to a private method doesn’t add any value. It may in-fact cause
unnecessary confusion.
class Base {

private final void foo() {}

// The above method foo() is same as following. The keyword


// final is redundant in above declaration.

// private void foo() {}


}

For example, both ‘program 1′ and ‘program 2′ below produce same compiler error “foo()
has private access in Base”.
Program 1
// file name: Main.java
class Base {
private final void foo() {}
}

class Derived extends Base {


public void foo() {}
}

public class Main {


public static void main(String args[]) {
Base b = new Derived();
b.foo();
}
}

Overloading method
Method Overloading in Java
1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion
If a class have multiple methods by same name but different parameters, it is known as

Method Overloading.
 If we have to perform only one operation, having same name of the methods increases
the readability of the program.
 Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So,
we perform method overloading to figure out the program quickly.

Advantage of method overloading?


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
Test it Now
Output:30
40
Java Constructor Overloading Examples
Like method overloading we can overload constructors also. Along with default constructor,
we can have constructors with parameters. The no of parameters can be same, and it can have
different datatypes. Below example gives sample code for constructors overloading.
Java Constructor Overloading Sample Code
Code:
package com.myjava.constructors;

public class MyOverloading {

public MyOverloading(){
System.out.println("Inside default constructor");
}
public MyOverloading(int i){
System.out.println("Inside single parameter constructor with int value");
}
public MyOverloading(String str){
System.out.println("Inside single parameter constructor with String object");
}
public MyOverloading(int i, int j){
System.out.println("Inside double parameter constructor");
}

public static void main(String a[]){


MyOverloading mco = new MyOverloading();
MyOverloading spmco = new MyOverloading(10);
MyOverloading dpmco = new MyOverloading(10,20);
MyOverloading dpmco = new MyOverloading("java2novice");
}
}
USING OBJECT AS PARAMETER
 The first thing that anyone needs to know is the difference between argument and
parameters. Arguments are the variables that are passed to the functions and
parameters are the variables that receive the value of the arguments. Java rich Object
Oriented Features allow us to use Objects as the parameter.

The only point that needs to be taken care of is that when objects are passed to a
method, they are always passed via call be referance. So, any changes made to the
object values in the method would be reflected in the passed object values too.
Class Rectangle {
int length;
int width;

Rectangle(int l, int b) {
length = l;
width = b;
}

void area(Rectangle r1) {


int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}

Output of the program :


Area of Rectangle : 200

ARGUMENT PASSING
 All parameters to methods in Java are pass-by-value.

// Method definition
public int mult(int x, int y)
{
return x * y;
}

// Where the method mult is used


int length = 10;
int width = 5;
int area = mult(length, width);
We use the term formal parameters to refer to the parameters in the definition of the method.
In the example, x and y are the formal parameters. You can remember to call them ``formal''
because they are part of the method's defintion, and you can think of a definition as being
formal.
We use the term actual parameters to refer to variables in the method call, in this case length
and width. They are called ``actual'' because they determine the actual values that are sent to
the method.
You may have heard the term "argument" used, or just "parameter" (without specifying actual
or formal). You can usually tell by the context which sort of parameter is being referred to.

What Pass-by-Value Means


Pass-by-value means that when you call a method, a copy of the value of each actual
parameter is passed to the method. You can change that copy inside the method, but this will
have no effect on the actual parameter.
Unlike many other languages, Java has no mechanism for changing the value of an actual
parameter. Isn't this very restrictive? Not really. In Java, we can pass a reference to an object
(also called a "handle")as a parameter. We can then change something inside the object; we
just can't change what object the handle refers to. For primitives, the story is a little different.
Let's look closely at some examples of passing different kinds of things to methods:
primitives, objects, strings, and array.

RETURNING OBJECTS’

In Java Programming A method can return any type of data, including class types that you
create.
For example, in the following program, the getRectangleObject( ) method returns an object.

Java Program : Returning the Object From Method


package com.pritesh.programs;

import java.io.File;
import java.io.IOException;

class Rectangle {
int length;
int breadth;

Rectangle(int l,int b) {
length = l;
breadth = b;
}

Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
}
class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;

ob2 = ob1.getRectangleObject();
System.out.println("ob1.length : " + ob1.length);
System.out.println("ob1.breadth: " + ob1.breadth);

System.out.println("ob2.length : " + ob2.length);


System.out.println("ob2.breadth: " + ob2.breadth);

}
}
Output of the Program :
ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20

RECURSION:
Java supports recursion. Recursion is the process of defining something in terms of
itself. As it relates to java programming, recursion is the attribute that allows a method to call
itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. for
example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a
recursive method.
class Factorial {
int fact(int n) {
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}
class Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println(“Factorial of 3 is “ + f.fact(3));
System.out.println(“Factorial of 3 is “ + f.fact(4));
System.out.println(“Factorial of 3 is “ + f.fact(5));
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
If you are unfamiliar with recursive methods, then the operation of fact() may seem a
bit confusing. Here is how it works. When fact() is called with an argument of 1, the
function returns 1; otherwise it returns the product of fact(n-1)*n. to evaluate this expression,
fact() is called with n-1. this process repeats until n equals 1 and the calls to the method
begin returning.
To better understand how the fact() method works, let’s go through a short example.
When you compute the factorial of 3, the first call to fact() will cause a second call to be
made with an argument of 2. this invocation will cause fact() to be called a third time with an
argument of 2. This call will return 1, which is then be called a third time with an argument
of 1. This call will return1, which is then multiplied by 2 (the value of n in the second
invocation). This result (which is 2) is then returned to the original invocation of fact() and
multiply by 3 ( the original value of n). This yields the answer, 6. You might find it
interesting to insert println() statements into fact() which will show at what level each call is
and what the intermediate answers are.
When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start. A
recursive call does not make a new copy of the method. Only the arguments are new. As each
recursive call returns, the old local variables and parameters are removed from the stack, and
execution resumes at the point of the call inside the method. Recursive methods could be said
to “telescope” out and back.
Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls. Many recursive
calls to a method could cause a stack overrun. Because storage for parameters and local
variables, it is possible that the stack could be exhausted. If this occurs, the java run-time
system will cause an exception. However, you probably will not have to worry about this
unless a recursive routine runs wild.
The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives. For example, the
QuickSort sorting algorithm is quite difficult to implement in an iterative way.

ACCESS CONTROL
As you know, encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control. Through encapsulation,
you can control what parts of a program can access the members of a class. By controlling
access, you can prevent misuse. For example, allowing access to data only through a well-
defined set of methods, you can prevent the misuse of that data. Thus, when correctly
implemented, a class creates a “black box” which may be used, but the inner workings of
which are not open to tampering. However, the classes that were presented earlier do not
completely meet this goal. For example, consider the Stack class shown at the end of the
Recursion article. While it is true that the methods push() and pop() do provide a controlled
interface to the stack, this interface is not enforced. That is, it is possible for another part of
the program to bypass these methods and access the stack directly. Of course, in the wrong
hands, this could lead to trouble. In this section you will be introduced to the mechanism by
which you can precisely control access to the various members of a class.
The access specifier that modifies its declaration determines how a member can be
accessed. Java supplies a rich set of access specifiers. Some aspects of access control are

related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.)


These parts of java’s access control mechanism will be discussed later. Here, let’s begin by
examining access control as it applies to a single class. Once you understand the
fundamentals of access control, the rest will be easy.
Java’s access specifiers are public, private, and protected. Java also defines a
default access level. protected applies only when inheritance is involved. The other access
specifiers are described next.
Let’s begin by defining public and private. When a member of a class is modified by
the public specifier, then that member can be accessed by any other code in your program.
When a member of a class is specified as private, then that member can only be accessed by
other members of its class. Now you can understand why main() has always been preceded
by the public specifier. It is called by code that is outside the program that is, by the java run-
time system. When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.
In the classes developed so far, all members of a class have used the default access
mode, which is essentially public. However, this is not what you will typically want to be the
case. Usually, you will want to restrict access to the data members of a class allowing access
only through methods. Also, there will be times when you will want to define methods, which
are private to a class.
An access specifier precedes the rest of a member’s type specification. That is, it must
begin a member’s declaration statement. Here is an example:
public int i;
private double j;
private int myMethod(int a, char b) {//…
To understand the effects of public and private access, consider the following program:
class Test {
int a;
public int b;
private int c;
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test ();
ob.a = 10;
ob.b = 20;
ob.setc(100);
System.out.println(“a, b, and c: “ + ob.a + ” “ + ob.b+ “ “+ ob.getc());
}
}
As you can see, inside the Test class, a uses default access, which for this example is
the same as specifying public. b is explicitly specified as public. Member c is given private
access. This means that it cannot be accessed by code outside of its class. So, inside the
AccessTest class, c cannot be used directly. It must be accessed through its public methods:
setc() and getc(). If you were to remove the comment symbol from the beginning of the
following line;
ob.c = 100;
then you would not be able to compile this program because of the access violation.
To see how access control can be applied to a more practical example, consider the
following improved version of the Stack class shown at the end of the article Recursion.
class Stack {
private int stck[] = new int [10];
private int tos;
Stack() {
tos = -1;
}
void push(int item) {
if( tos==9)
System.out.println(“Stack is full.”);
else
stck[++tos] = item;
}
int pop() {
if(tos <0) {
System.out.println(“Stack underflow.”);
Return 0;
}
else
return stck[tos--];
}
}
As you can see, now both stck, which holds the stack, and tos, which is the index of
the top of the stack, are specified as private. This means that they cannot be accessed or
altered except through push() and pop(). Making tos private, for example, prevents other parts
of your program from inadvertently setting it to a value that is beyond the end of the stck
array.
UNDERSTANDING STSTIC IN JAVA
There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally a class member must be accessed only in
conjunction with an object of its class. However, it is possible to create a member that can be
used by itself, without reference to a specific instance. To create such a member, precede its
declaration with the keyword static. When a member is declared static, it can be accessed
before any objects of its class are created, and without reference to any object. You can
declare both methods and variables to be static. The most common example of static member
is main (). main () is declared as static because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the class
share the same static variable.
1. Methods declared as static have several restrictions:
 They can only call other static methods
 They must only access static data.
 They cannot refer to this or super in any way.
If you need to do computation in order to initialize your static variables, you can
declare a static block, which gets executed exactly once, when the class is first loaded. The
following example shows a class that has a static method, some static variables, and a static
initialization block:
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println(“x = “ + x);
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
}

static {
System.out.println(“Static block initialized.”);
B = a *4;
}
public static void main (String args[]){
mech(42);
}
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is
set to 3, then the static block executes (printing a message), and finally, b is initialized to a*4
or 12. Then main() is called, which calls meth(), passing 42 to x. the three println() statements
refer to the two static variables a and b, as well as to the local variable x.
It is illegal to refer to any instance variables inside of a static method.
Here is the output of the program:
Static block initialized.
x = 42
a=3
b =12
Outside of the class in which they are defined, static methods and variables can be
used independently of any object. To do so, you need only specify the name of their class
followed by the dot operator. For example, if you wish to call a static method from outside its
class, you can do so using the following general form:
classname.method()
Here, classname is the name of the class in which the static method is declared. As
you can see, this format is similar to that used to call non-static methods through object-
reference variables. A static variable can be accessed in the same way by use of the dot
operator on the name of the class. This is how java implements a controlled version of global
functions and global variables.
Here is an example. Inside main(), the static method callme() and the static variable b
are accessed outside of their class.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println(“a = “ + a);
}
}
class StaticByName {
public static void main (String args[]) {
StaticDemo.callme();
System.out.println(“b =” + StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99

INTRODUCING FINAL IN JAVA’


The final keyword is a very important and often overlooked weapon in your concurrency
armoury. Essentially, final can be used to make sure that when you construct an object,
another thread accessing that object doesn't see that object in a partially-constructed state, as
could otherwise happen. This is because when used as an attribute on the variables of an
object, final has the following important characteristic as part of its definition:
When the constructor exits, the values of final fields are guaranteed to be visible to other
threads accessing the constructed object.

Why is this necessary?


The final field is a means of what is sometimes called safe publication. Here, "publication"
of an object means creating it in one thread and then having that newly-created object be
referred to by another thread at some point in the future. When the JVM executes the
constructor of your object, it must store values into the various fields of the object, and store
a pointer to the object data. As in any other case of data writes, these accesses can potentially
occur out of order, and their application to main memory can be delayed and other processors
can be delayed unless you take special steps to combat this. In particular, the pointer to the
object data could be stored to main memory and accessed before the fields themselves have
been committed (this can happen partly because of compiler ordering: if you think about how
you'd write things in a low-level language such as C or assembler, it's quite natural to store a
pointer to a block of memory, and then advance the pointer as you're writing data to that
block). And this in turn could lead to another thread seeing the object in an invalid or
partially constructed state.
final prevents this from happening: if a field is final, it is part of the JVM specification that it
must effectively ensure that, once the object pointer is available to other threads, so are the
correct values of that object's final fields.
Final object references
The fields on any object accessed via a final reference are also guaranteed to be at least as up
to date as when the constructor exits. This means that:
Values of final fields, including objects inside collections referred to by a final reference, can
be safely read without synchronization.
Note that if you have a final reference to a collection, array, or some other mutable object,
you must still synchronize all accesses to that object (or use a thread-safe collection such as a
ConcurrentHashMap) if that collection is ever accessed by a thread other than the
constructing thread.
Thus, immutable objects (ones where all fields are final and are either primitives or
references to immutable objects) can be concurrently accessed without synchronization. It
is also safe to read "effectively immutable" objects (ones whose fields aren't actually final,
but in practice never change) via a final reference. However, from a program design
perspective, you'd be wise to try and enforce immutability in this case (e.g. by wrapping a
collection in a Collections.unmodifiableList()1 etc). That way, you'll spot bugs introduced
when one of your colleagues naughtily attempts to modify a collection that you didn't intend
to be modified!
Restrictions and limitations of using final
When you declare a field final, you must set the value once by the time the constructor
exits. This means that you can declare a final field as follows:
public class MyClass {
private final int myField = 3;
public MyClass() {
...
}
}
or you can write the following:
public class MyClass {
private final int myField;
public MyClass() {
...
myField = 3;
...
}
}
It's important to emphasise that storing a reference to an object in a final field only makes the
reference immutable, not the actual object. For examlple, if a list is declared as follows:
private final List myList = new ArrayList();
there's nothing to stop modifications to the list:
myList.add("Hello");
However, the following would not be possible:
myList = new ArrayList();
myList = someOtherList;
When should I use final?
One answer to this is "whenever you possibly can". Any field that you never expect to be
changed (be that a primitive value, or a reference to an object, whether or not that particular
object is itself immutable or not), should generally be declared final. Another way of looking
at things is:
If your object is accessed by multiple threads, and you don't declare its fields final, then you
must provide thread-safety by some other means.
Other means could include declaring the field volatile, using synchronized or an explicit Lock
around all accesses to that field.
A typical case that people overlook is where an object is created by one thread and then later
consumed by another thread, e.g. an object via a ThreadPoolExecutor. In this case, the object
must still be made properly thread-safe: it doesn't matter that the accesses by different threads
aren't concurrent. What matters is that the object is accessed by different threads at any point
in its lifetime.

1. It's important to understand, however, that such wrappers give you an


unmodifiable view of a collection. If some other reference to the
original collection escapes, then the collection can still be modified by
that other reference.
ARRAY REVISITED
An important point can be made about arrays: they are implemented as objects. Because of
this, there is a special array attribute that you will want to take advantage of. Specifically, the
size of an array that is, the number of elements that an array can hold is found in its length
instance variable. All arrays have this variable, and it will always hold the size of the array.
Here is a program that demonstrates this property:
class Length {
public static void main (String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};

System.out.println(“length of a1 is “ + a1.length);
System.out.println(“length of a1 is “ + a1.length);
System.out.println(“length of a1 is “ + a1.length);
}
}
This program displays the following output:
length of a1 is 10
length of a1 is 8
length of a1 is 4
INTRODUCING NESTED AND INNER CLASSES
It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if
class B is defined within class A, then B is known to A, but not outside of A. A nested class
has access to the members, including private members, of the class in which it is nested.
However, the enclosing class does not have access to the members of the nested class.
There are two types of nested classes: static and non-static. A static nested class is one
which has the static modifier applied. Because it is static modifier applied. Because it is
static, it must access the members of its enclosing class through an object. That is, it cannot
refer to members of its enclosing class directly. Because of this restriction, static nested
classes are seldom used.
The most important type of nested class is the inner class is the inner class. An inner
class is a non-static nested class. It has access to al of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members of the
outer class do. Thus, an inner class is fully within the scope of its enclosing class.
The following program illustrates how to define and use an inner class. The class
named Outer has one instance variable named outer_x, one instance method named test(), and
defines one inner class called Inner.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
class Inner {
void display() {
System.out.println(“display : outer_x =” + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. an instance
method named display() is defined inside Inner. This method displays outer_x on the standard
output stream. The main() method of InnerClassDemo creates an instance of class Inner and
the display() method is called.
It is important to realize that class Inner is known only within the scope of class
Outer. The java compiler generates an error message if any code outside of class Outer
attempts to instantiate class Inner. Generalizing, a nested class is no different than any other
program element: it is known only within its enclosing scope.

EXPLORING THE STRING CLASS


Introduction
String manipulation is arguably one of the most common activities in computer
programming. String class has variety of methods for string manipulation. We will discuss
about basic methods with examples.
public char charAt(int index)
This method requires an integer argument that indicates the position of the character that the
method returns.This method returns the character located at the String's specified index.
Remember, String indexes are zero-based—for example,

String x = "airplane";

System.out.println( x.charAt(2) ); // output is 'r'

public String concat(String s)


This method returns a String with the value of the String passed in to the method appended to
the end of the String used to invoke the method—for example,

String x = "book";

System.out.println( x.concat(" author") ); // output is "book author"

The overloaded + and += operators perform functions similar to the concat()method—for


example,

String x = "library";

System.out.println( x + " card"); // output is "library card"

String x = "United";
x += " States"

System.out.println( x ); // output is "United States"

public boolean equalsIgnoreCase(String s)


This method returns a boolean value (true or false) depending on whether the value of the
String in the argument is the same as the value of the String used to invoke the method. This
method will return true even when characters in the String objects being compared have
differing cases—for example,

String x = "Exit";

System.out.println( x.equalsIgnoreCase("EXIT")); // is "true"

System.out.println( x.equalsIgnoreCase("tixe")); // is "false"

public int length()


This method returns the length of the String used to invoke the method—for example,

String x = "01234567";

System.out.println( x.length() ); // returns "8"

public String replace(char old, char new)


This method returns a String whose value is that of the String used to invoke the method,
updated so that any occurrence of the char in the first argument is replaced by the char in the
second argument—for example,

String x = "oxoxoxox";

System.out.println( x.replace('x', 'X') ); // output is "oXoXoXoX"

public String substring(int begin)/ public String substring(int begin, int end)
The substring() method is used to return a part (or substring) of the String used to invoke the
method. The first argument represents the starting location (zero-based) of the substring. If
the call has only one argument, the substring returned will include the characters to the end of
the original String. If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the second argument.
Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last
character in the returned String will be in the original String's 7 position, which is index 6.
Let's look at some examples:

String x = "0123456789"; // the value of each char is the same as its index!

System.out.println( x.substring(5) ); // output is "56789"

System.out.println( x.substring(5, 8)); // output is "567"

public String toLowerCase()


This method returns a String whose value is the String used to invoke the method, but with
any uppercase characters converted to lowercase—for example,

String x = "A New Java Book";

System.out.println( x.toLowerCase() ); // output is "a new java book"


public String toUpperCase()
This method returns a String whose value is the String used to invoke the method, but with
any lowercase characters converted touppercase—for example,

String x = "A New Java Book";

System.out.println( x.toUpperCase() ); // output is"A NEW JAVA BOOK"

public String trim()


This method returns a String whose value is the String used to invoke the method, but with
any leading or trailing blank spaces removed—for example,

String x = " hi ";

System.out.println( x + "x" ); // result is" hi x"

System.out.println(x.trim() + "x"); // result is "hix"

public char[ ] toCharArray( )


This method will produces array of characters from characters of String object. For example

String s = “Java”;

Char [] arrayChar = s.toCharArray(); //this will produce array of size 4

public boolean contains(“searchString”)


This method returns true of target String is containing search String provided in argument.
For example-

String x = “Java is programming language”;

System.out.println(x.contains(“Amit”)); // This will print false

System.out.println(x.contains(“Java”)); // This will print true

COMMAND LINE ARGUMENT


 The java command-line argument is an argument i.e. passed at the time of running the
java program.
 The arguments passed from the console can be received in the java program and it can
be used as an input.
 So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
A Java application can accept any number of arguments from the command line. This allows
the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them
after the name of the class to be run. For example, suppose a Java application called Sort
sorts lines in a file. To sort the data in a file named friends.txt, a user would enter:

java Sort friends.txt


When an application is launched, the runtime system passes the command-line arguments to
the application's main method via an array of Strings. In the previous example, the command-
line arguments passed to the Sort application in an array that contains a single String:
"friends.txt".
Echoing Command-Line Arguments
The Echo example displays each of its command-line arguments on a line by itself:

public class Echo {


public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}

The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java
Drink
Hot
Java
Note that the application displays each word — Drink, Hot, and Java — on a line by itself.
This is because the space character separates command-line arguments. To have Drink, Hot,
and Java interpreted as a single argument, the user would join them by enclosing them within
quotation marks.
java Echo "Drink Hot Java"
Drink Hot Java
Parsing Numeric Command-Line Arguments
If an application needs to support a numeric command-line argument, it must convert a String
argument that represents a number, such as "34", to a numeric value. Here is a code snippet
that converts a command-line argument to an int:
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the
Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert
a String representing a number to an object of their type.

You might also like