[Go to site: main page, start]

0% found this document useful (0 votes)
5 views89 pages

Java OOP Basics: Classes and Objects

This document provides an overview of object-oriented programming concepts in Java, focusing on classes and objects. It explains how to declare classes, create objects, and access instance variables and methods, along with examples of Java code. The document also covers the structure of methods, including void and return types, and illustrates how to write a complete Java program.

Uploaded by

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

Java OOP Basics: Classes and Objects

This document provides an overview of object-oriented programming concepts in Java, focusing on classes and objects. It explains how to declare classes, create objects, and access instance variables and methods, along with examples of Java code. The document also covers the structure of methods, including void and return types, and illustrates how to write a complete Java program.

Uploaded by

r6532742
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SYBSC-Skill Enhancement Course (SEC)-25-26

Module-2: Object oriented programming in Java and Java Applets

CLASSES & OBJECTS


Starter:

Key concepts in Object oriented programming are Classes and Objects. Recall that, an object is an
entity having state, behavior and identity. Class contains instance variables and methods.
In this chapter, you will see how pure object-oriented concepts are applied using Java.
This chapter will start with declaration of classes and objects in Java. You will also see how to create
different methods.

1. Declaring the class in Java:

A class has instance variables and methods. They are defined inside the class body. Braces ({ ) ) are
used to mark the beginning and the end of each class. The structure of a class is:

class <class name>


{
<declaring variables >;
< declaring methods >;
}

Every thing within a square bracket is optional. In the above format:


(i) class: class is a key word used to declare a class in Java.
(ii) class name: class name is mandatory and must be given while declaring a class.

Rules for naming classes are exactly same as that of defining variables in [Link] are two kinds of
things that the definition of a class contains. They are instance variables and methods.
We study first instance variables and use them to define classes. Later on we add methods into these
classes.

Instance variables: These are variables that store data items, which are typically different from one object
of the class from another. For example, consider a class Employee of a company.

Class :Employee
Instance variables: emp_No , emp_Add
Method : empdetails( )

Some of the instance variables are emp_No (employee number) and emp_Add (employee address).

One of the method is empdetail( ) (Employee details).Any employee of the company will be the object of
the class. If Henna and Tina are two employees of a company then both of them can be taken as objects
of a class Employee. Henna and Tina will have different instance variables (i.e. emp_No as well as
emp_Add.)

Instance variables are defined in a class using following syntax:

Data type < instance variables separated by commas > ;


For example,
(i) int length, height; (ii) int n;
float x,y;
char z;
(iii) int emp_No;
String emp_Add;
Rahul Deshmukh Module-2: Basics of Java Programming 1
SYBSC-Skill Enhancement Course (SEC)-25-26

2. Simple Example of a class:

Let us begin by defining a simple class called Jbook, which can be


class Jbook consider as a class of all Java books. Suppose Jbook defines three
{ instance variables, say author (Name of the author of a book), p_nos
String author; (Number of pages of a book), and price (price of the book). The
int p_nos ; adjacent table gives Java class definition.
float price; Here Jbook is the name of the class that is useful while declaring
} objects of this class.

3. Declaring Objects of a class:

We know that, objects are instances of a class. For example, the book, which you are reading, is the
object of the class Java books. Let us denote this object by mybook and the class by Jbook.

3.1 Operator new: When we declare an object, we mearly state its data type. For example,

Jbook mybook;

This tells the compiler that the variable mybook is an object of the Jbook class. It does not allocate
memory for the object.

mybook = new Jbook( );

To allocate memory, we need to use the new operator and the statement can be given as:

Thus to create the object of the class and allocate the memory to it, you pass two statements as:
Jbook mybook;
mybook = new Jbook();

You can combine both the statements and pass a single statement as:

Jbook mybook = new Jbook();

After this statement executes, mybook will be an instance of Jbook.


Thus, following are two ways to create object and allocate memory to it.

(1) Declare the object and then allocate memory using the new operator.

<class name > <object name> ;


< object name> = new < class name >;

(2) Declare the object and at the same time allocate memory using the new operator.
<class name > <object name > = new < class name > ;

Note: The operator new is used only inside methods.

4. Accessing instance variables of a class for the object:

After creating an object it is necessary to access the instance variables for object. This can be done
using dot operator by connecting the object name and name of instance variable as shown below:

Rahul Deshmukh Module-2: Basics of Java Programming 2


SYBSC-Skill Enhancement Course (SEC)-25-26
[Link]

For example: (1) For Jbook class, instance variable p_nos can be accessed using the statement:

mybook.p_nos

To assign the value say, 100 to the variable p_nos of mybook ,we can use the following statement:
mybook .p_nos = 100;

(2) Consider the class Circle.

Class: Circle.
Instance variable: radius.
Method: -----------
Circle_1 Circle_2

It has an instance variable radius. Let circle_1, circle_2 be two circles with radius 2 and 3.
circle_1,circle_2 are the objects of the class circle. These objects can be created by:

circle circle_1= new circle( );


circle circle_2= new circle( );

Instance variable radius can be accessed for these objects using dot operator as follows:

circle_1.radius
circle_2.radius

As 2 and 3 are the radius of two circles circle_1 and circle_2 so assign them to circle_1.radius and
circle_2.radius as follows:

circle_1.radius = 2;
circle_2.radius =3;

5. First Java program consist of classes and single object:

Now you are in position to write first Java program containing classes and one object with only one
compulsory method i.e. main( ).
Example: Consider a class Rectangle with two instance variables
class Rectangle length and breadth. The class is defined as follows [See Table
{ below]:
double length; Let us find the area of a rectangle with length =10 and height =
double breadth; 20. This rectangle is the object of the class Rectangle. Let us
} denote it by myRect.

To create the object myRect we use the following statement:

Rectangle myRect = new Rectangle ( );

Rahul Deshmukh Module-2: Basics of Java Programming 3


SYBSC-Skill Enhancement Course (SEC)-25-26
Thus myRect will be the instance of Rectangle.

Class: Rectangle.
Instance variables: length, breadth.
Method: -------------

myRect

Every Rectangle object contains its own copies of the instance variables defined by classes. Here
every Rectangle object will contain its own copies of the instances variables viz. length, breadth. To
access these variables we use dot operators as follows:

myRect .length = 10; and [Link] = 20;

These statements are to be written in the main( ) method of the class say, Rect_demo1.Area can be
found in usual way by writing the statement:

area = [Link] * myRect . breadth;

The complete Java program for the Rectangle class is given below:

class Rectangle
{
double length;
double breadth;
}
class Rect_demo1
{
public static void main(String args[])
{

Rectangle myRect =new Rectangle();


double area;
[Link]=10;
myRect. breadth=20;
area = [Link]*myRect. breadth;
[Link]("Area is "+area);
}
}

Compile the above program by giving the name of the class in which main() method resides. i.e.

C: \ Maths> javac Rect_demo1.java

To run the program gives the following command:

Rahul Deshmukh Module-2: Basics of Java Programming 4


SYBSC-Skill Enhancement Course (SEC)-25-26

C: \Maths> java Rect_demo1

The output is:

Area is 200.0

6. Methods:

The concept of methods in Java is similar to the user-defined functions in C. So far you have come
across with one method in a class called main( ). This method is compulsory and has a specific meaning.
In Java, method is a self contained block of code that has a name and has the property that it is reusable
i.e. the method can be executed as many times as you can at different points in a program. Methods are
useful to divide large calculation in small segments.
The general format of a method is:

return_type methodName (para 1, para 2,…….., para n);


{
method-body;
}

Method declaration contains four parts:


➢ (methodname) The name of the method which is to be executed. This name must be identifier.
➢ (return_type) The type of the value to be returned. This value may be any data type or may be a void.
If it is void, then the method does not return any value.
➢ (parameterlist) The parameters to a method appear in its definition between parentheses following
the method name. This specifies what information is to be passed to the method when you execute it. The
parameters are optional, and a method that does not require any such information to be passed to it has an
empty pair of parentheses after the name.

From above you can classify the declaration of method into two parts:

1. void Form: This form does not return any value.


2. return Form: This form returns value.

6.1 void Form.

In this form, the compiler executes all the lines inside the body of the
method and does not return any value to the method. For example:

void setDisplay ( )
{
[Link] (“Java is Simple”);
}
Here, Java is Simple will be printed using above method.

Consider the method Sqr to find the square of x. The variable y inside the code is called local
variable. The scope of the local variable is restricted only
void Sqr (double x) to the method. Out side the method the variable y does not
{ have any meaning.
int y;
y = x * x;
}
Rahul Deshmukh Module-2: Basics of Java Programming 5
SYBSC-Skill Enhancement Course (SEC)-25-26

Let us consider another method that has two instance variables x and y of type double.

void Sum ( double x, double y )


{
double sum;
sum = x + y ;
[Link]( “ Sum =”+ sum );
}

In the above method x and y are two variables of double data type. The variable sum is a local
variable and is printed by the last line.

6.2 return form:

In this form, the compiler executes all the lines inside the body of the method and returns the value
specified by the type of the method. The format of the return statement is:
return return_expression;

Where return_expression may be any value or Java expression.


For example,

(1) Here Prod is a method of computing the product of two int variables and storing
the result into local variable c.
int Prod(int a , int b)
c. The int value of c is return to the method.
{
int c;
c = a * b;
return c;
}
Alternatively, the above method can be written as:

Here a*b is calculated and returns int value to the method.


int Prod (int a , int b ) Note that int a, b;
{ is not valid. If you write
return a * b ; int x = [Link] (3 , 4 );
} in the main( ) method then 3,4 will be assigned to a,b and
using method Prod ( ) x becomes 3*4 i.e. 12.

(2) Consider the method to calculate the area of a circle.


Here area1 is the local variable and returns the value of double type.

double area (int r ) double area( int r )


{ {
double area1; OR return (3.14)*r*r;
area1= (3.14)*r*r; }
return area1;
}

Above examples, shows that the code returns only one value at a time. Consider the following
segment:

Rahul Deshmukh Module-2: Basics of Java Programming 6


SYBSC-Skill Enhancement Course (SEC)-25-26

int Answer ( int x )


{
int y;
if ( y<=x++)
return y+ x++ − ++y;
else
return y+ ++x − y++;
}

The method Answer( ) will return int value depending upon the condition. If there is a statement
Obj. Answer (4); in the main( ) method then x=4.

If y = 7 then as x = 4 the condition is false as 7 is not less than or equal to [Link] the control
will transfer to the else part and return the value 6 to the method. Since if result = y+ ++x − y++
then we have:

Step 1: x = x+1  x=5


Step 2: x = x+1  x=6
Step 3: result = y+x- y  result = 7+6-7 = 6

Thus 6 will be return to the method Answer ().

On the other-hand, If there is a statement


Obj. Answer (7); in the main( ) method then x= 7.

If y = 4 then as x = 7 the condition is true as 4 is less than 7. Therefore the control will transfer to the
if part and return the value 7 to the method. Since if result = y+ x++ − ++y then we have:

Step 1: x = x+1  x=8


Step 2: result1 = y+x  result1 = 4+8= 12
Step 3: y = y+1  y=4+1=5
Step 4: result = result1- y  result = 12-5=7

Thus 7 will be return to the method Answer.


[See the complete program given as example (2) later.]

[Link] class:

We are now in position to write complete class containing both instance variables and methods. Let
us denote a class called Complete to find the result of the expression as shown in the adjacent box.

class Complete
{
int a,b;//instance variables
a=2;
b= 3 ;
int expression( ) //Method.
{
int result;
result= - - a + b ++;
return result;
}
Rahul Deshmukh }//end of class. Module-2: Basics of Java Programming 7
SYBSC-Skill Enhancement Course (SEC)-25-26

Explanation:
➢ The name of the class is Complete.
➢ Variables a and b are the instance variables and having values 2 and 3 respectively.
➢ Expression is a method returning int value. This method contains local variable result of int
type. The scope of this variable is restricted only for the method. In other words, this variable
cannot be accessed from out side the method as well as from out side the class.
➢ Variable result contains the expression--a +b++.
It is evaluated as follows:
Step 1: a = a - 1 = 2 - 1=1
Step 2: result= a + b =1 + 3 = 4.
Thus 4 is return to the method Expression.
➢ After return statement you should not write any statement because the control will not go to
that statement. Thus return statement must be the last statement of the method.
➢ The code of the method should be written in side the parentheses.
7.1 Accessing Methods of a class for an object:
Similar to accessing instance variables of an object, you can access methods of an object. This can be
done by:

[Link]( );
Consider the following examples:
(1) Let class_1 and class_2 be two classes having voidDisplay ( ) and main( ) methods respectively.
Let obj be the object of the class_1.Then voidDisplay ( ) method for obj can be access using the
statement:

Obj . voidDisplay( ) ;
obj
Which is inside the class_2.

class_1 class_2

Method:voidDisplay( ) main( )

(2) Let class_A and class_B two classes having mean( ) and main( ) as [Link] obj be the object of
the class_A.
Method mean( ) can be invoked
class_A for obj object by the statement
{ ……….. [Link] mean(5.0,7.0); which
double mean(double x ,double y) is inside the main( ) method of
{ the class_B.
double result ; Let us write some important
result = (x+y)/2; lines of these two classes and
return result; study them carefully. The
} //end of method. compiler will execute class_B
as main( ) method resides in it.
}//end of class.
When statement A gets
class_B executed the compiler will
{ transfer the control to the
double a; mean( ) method of the class_A.
public static void main(String args[ ] ) You can see that mean( )
{ ………….. method has two parameters x
a = [Link](5.0,7.0); // stat A and y of double type that are
…………... used to refer to the arguments
} //end of main( ) 5.0 and 7.0 respectively.
} //endDeshmukh
Rahul of class. Module-2: Basics of Java Programming 8
SYBSC-Skill Enhancement Course (SEC)-25-26
When you call the method from another method the values of the arguments passed are the initial values
assigned to the corresponding parameters. You can use any expression for the argument but note that the
data types of the arguments or expression and the data types of the parameters must be the same.
The method mean( ) declares the variable result which only exits within the body of the
method. The variable is created each time when you execute the method and it is destroyed when
execution of the method ends. All the variables declared inside the body of the method are called as local
variables. The life of these variables is only for that method. If you want to initialize these variables then
you must supply the values inside the method at the time of declaration. The code of the method mean( )
will calculate the value of the local variable result and this value is returned to the R.H.S. of the stat A.
Thus the instance variable a gets the value of result.

(3) Consider the following statements of the classes:

Here, after executing the line i =10 the control will goto the method change( ) of class C because of
statement A. Here in the definition of a method change( ) of class C,the variable j is the parameter of int
data type which will equate with the argument i having value [Link] ++j; j becomes 11,so the value of
j that is returned will be 11 and this will be stored in a.

Class: C1
Class: C
Method:main( )
Method: change ( )

obj

class C1
{
public static void main (String args[ ])
{
int i=10;

int a= [Link]( i ); // stat A


……….
}
} i=10 and j=i
class C
{
………..
int change (int j)
{
++j;
return j;
}
}

(4) Consider the classes A and B:.Stat. A transfers the control to the method product( ) which receives int
data type. Inside the body of product( ) ,c is calculated as x+2*y-1 i.e. 2+2*3-1 i.e.2+6 –1 i.e.
[Link] 7 is stored in z. See the program given below.

Rahul Deshmukh Module-2: Basics of Java Programming 9


SYBSC-Skill Enhancement Course (SEC)-25-26

class A
{
-------------------
int product (int a,int b);
{
int c= a*b;
return c;
}
}
class B
{
public static void main(String args[])
{
int x=2,y=3;
int z = [Link](x+2,y-1); // stat A
}
}
8. Few complete programs:

Example1 (Creating more than one object)


As seen earlier, each object has its own copies of the instance variables. This means that if myRect1 and
myRect2 are two objects of the class Rectangle then both will have different copies of instance variables.
These variables can be created as follows:
Similarly, one can create any number of objects of the class. Following is the complete program with two
objects created by modifying the previous program:
Rectangle myRect1 = new Rectangle( );
Rectangle myRect2 = new Rectangle( );

class Rectangle
{
double length;
double breadth;
void area()
{
[Link]("Area is ");
[Link](length* breadth);
}
}
class Rect_demo2
{
public static void main(String a[ ])
{
Rectangle myrect1 =new Rectangle ( );
Rectangle myrect2 =new Rectangle ( );
myrect1 .length=10;
myrect1. breadth =20;
[Link]=15;
myrect2. breadth =24;
[Link]( );
[Link]( );
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 10


SYBSC-Skill Enhancement Course (SEC)-25-26
After compiling and running the program you get the following:

C:\Maths>javac Rect_demo2.java
C:\Maths>java Rect_demo2
Area is 200.0
Area is 360.0

Example (2)(Method with 2 return statements)

class Answ
{
int x ;
int ans(int x)
{
int y=7;
if ( y<=x++)
{
int result = y+ x++ - ++y;
[Link]("x and y : "+x+" "+y);
return result;
}
else
{
int result= y+ ++x - y++;
[Link]("x and y : "+x+" "+y);
return result;
} //end of if.
} //end of method.
}//end of class.
class Answer1
{
public static void main(String args[ ]){
Answ obj = new Answ ();
[Link]("Result = "+ [Link](4) ) ; }
}

The output is as follows:

C:\Maths>javac [Link]
C:\Maths>java Answer1
x and y : 6 8
Result = 6

If x = 7 and y= 4 then

C:\Maths>javac [Link]
C:\Maths>java Answer1
x and y : 9 5
Result = 7

Rahul Deshmukh Module-2: Basics of Java Programming 11


SYBSC-Skill Enhancement Course (SEC)-25-26
Example 3: Following program illustrates how to interchange values of two variables.

class Swap
Class: swap
{
int x,y;
Instance variables: x ,y
void setVar()
{
x=3;
y=4; Methods: SetVar( ),
} Display( )
void Display() Code( )
{
[Link]("x="+x);
[Link]("y="+y); obj
}
void Code()
{ class: Interchange
int t;
t=x; Method:main( )
x=y;
y=t;
}
}
class Interchange
{
public static void main(String args[])
{
Swap obj=new Swap();
[Link]();
[Link]();
[Link]();
}
}

Explanation:
➢ Swap and Interchange are two classes.
➢ Swap class contains 3 methods:
SetVar( ) assigns 3 and 4 to the instance variables x and y.
SetDisplay( ) prints x and y after swapping.
Code ( ) gives the code of interchanging the values of two variables.
➢ Interchange class contains only main( ) method.
➢ Obj is a object of a class Swap, defined in the main( ) method of Interchange [Link] obj ,you
can invoke all the three methods of the class Swap.

The out is as follows:

C:\ Maths> javac [Link]


C:\ Maths> java Interchange
x=4 y =3

Rahul Deshmukh Module-2: Basics of Java Programming 12


SYBSC-Skill Enhancement Course (SEC)-25-26

[Link] this keyword:

The keyword this is used inside the instance method to refer to the current object. The value of this
points to the object on which the current method has been called. This is useful when name of the
instance variables are the same as the list of the parameters of the methods. This can be used by the
format:

this . <var_name> = var_name;

For example, this.x = x;


The following program illustrates the use of the keyword this:

Class : This1

Instance variables: a,b


Class:This
Methods:Set (a,b),
show ( )
Method:main( )
eeee th

class This1
{
int a=7,b=10;
void Set(int a,int b)
{
this.a=a;
this.b=b;
}

void show()
{
[Link]("a= "+a);
[Link]("b= "+b);
}
}
class This
{
public static void main (String args[])
{
This1 th=new This1();
[Link](2,3);
[Link]();
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 13


SYBSC-Skill Enhancement Course (SEC)-25-26

Explanation:
➢ This1 and This are two classes of which main ( ) method resides in This class.
➢ Class This1 contains instance variables a and b and two methods viz. set (a,b) and Show ( )
method.
➢ Instance variables a and b are hidden by the parameters a and b of the method set ( ).
➢ th is the object defined in the main ( )method which is used to invoked methods of the class
This1.
➢ After invoking Show ( ) method 2 and 3 will be displayed as the values of a and b

Save the file with [Link] under Maths.


Compile the file using javac [Link]
Run the file using java This
The output is as follows:

C:\ Maths> javac [Link]


C:\ Maths> java This
a= 2
b= 3
Exercise: Write a program in Java for the following:

[1] Containing a class with (1) instance variable without method, (2) method without instance
variable,(3) both instance variable and method.

[2] Define three classes say A, B and C such that A contains a main ( ) method, B contains code ( )
method for converting Fahrenheit to Celsius and C contains Display ( )method to show the
conversion.

[3] Define three classes say A, B and C such that A contains a main ( ) method, B contains code ( )
method for interchanging the values of two variables without temporary variable and C contains
Display ( )method to show the swap.

[4] Define two classes of your choice to count + ve numbers from a set of integers.

[5] Define two classes of your choice to find summation of a set of numbers.

[6] Define two classes of your choice of which one class contains main ( ) method and other class
contains the code for reversing the digits of an integer.

Rahul Deshmukh Module-2: Basics of Java Programming 14


SYBSC-Skill Enhancement Course (SEC)-25-26
SPECIAL METHOD

[Link]:

Constructor is a method to initialise the instance variables of the class. In other words, Constructor is a
special method to construct the object by initialising instance variables and creating the necessary
environment for the object.

For example, [1] If the class A contains instance variables x and y with a method name say method( ) to
compute the value of the expression y=x+1 then the variable x can be initialise with the method called as
constructor. We will write the full Java code later on.

Class: A

Method: method ( )

Constructor: Define later on.

[2] If you are planning to type a document i.e. an object using Microsoft word then by default you get
font size, name of the font etc. This is called as creating environment for an object and is termed as
default constructor. You can create your own constructor by changing font size, name of the font etc. for
the object in Microsoft word.

[Link] to define a constructor?

In Java, the constructor has the class A


same name as that of the class {
where it resides. A constructor does int x,y;
not have return type. void A( ) // Constructor.
{
For example, for a class A, the
constructor can be defined to
x=2;
initialise the variable x with name A }
(It is the name of the class). void method( ) //Method.
{
Explanation: Class A contains y = x+1;
three methods viz. [Link](" x ="+x+" y ="+y);
(i) method( ) contains the }
calculation of the expression public static void main(String args[ ])
y=x +1, {
(ii) A ( ) is a constructor to A obj= new A( );
initialize the value of the
obj.A( );
instance variable x to 2.
(iii) main ( ) method containing the
[Link]();
object obj .Statements obj. }
A( ) and [Link] ( ) will }
invoke a constructor A ( ) and
a method method ( ).

The out put is as follows.


Save the file with: [Link] under Maths
Compile the program with: C :\ Maths>javac [Link]
Run the file with: C :\ Maths>java A
x =2 y =3

Note that, if a class does not have any constructor method, the compiler provides the default constructor
to that class.
Rahul Deshmukh Module-2: Basics of Java Programming 15
SYBSC-Skill Enhancement Course (SEC)-25-26
1.2 Different types of Constructor:

Constructors can be constructed with parameters or without parameters.

[1] Constructors without parameters:

Constructor can be defined by the format:

< name of Constructor >( )


{
Initialisation body ;
}

Where the name of the constructor is the same as the name of the class in which the constructor resides.

The following program illustrates the constructor.

Class: Class:Rectangle
Rect_demo5
Constructor:
Method: Rectangle( )
main ( )
myRect
Methods: Area( )

//CONSTRUCTOR WITHOUT PARAMETERS.


class Rectangle
{
double length;
double height;
// Constructor to initialised
Rectangle()
{
length = 30;
height = 20;
}
// Compute Area & return area
double area()
{
return length * height;
}
}
class Rect_demo5
{
public static void main(String a[])
{
Rectangle myRect = new Rectangle();
double area;
//Get area of rect
area = [Link](); // statement I
[Link]("Area = "+area);
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 16


SYBSC-Skill Enhancement Course (SEC)-25-26
Explanation:
➢ Rectangle and Rect_demo5 are two classes.
➢ Rectangle class contains the constructor with the name Rectangle( ) to initialised instance variables
length and breadth to 30 and 20 respectively. This class also contains method area ( ) to find the area
of a rectangle.
➢ Rect_demo5 class contains only one method main( ). myRect is the object of the class Rectangle to
find the area. Area is found by invoking the method area() using statement I. Note that it is not
required to invoke constructor method directly.
The output is as follows:
Save the file with: Rect_demo5
Compile the file with:C:\Maths>javac Rect_demo5.java
Run the file with: C:\Maths>java Rect_demo5
Area = 600.0

[2] Constructors with parameters:


Constructor can be defined by the format:
<name of Constructor>(list of [Link] data type )
{
Initialisation body;
}

Where the name of the constructor is the same as the name of the class in which the constructor resides.
Example 1: The following program illustrates the constructor by modifying the above program.
//Parameterised constructor
class Rectangle
{
double length;
double height;
// Constructor to initialised
Rectangle ( double l , double h)
{
length = l;
height = h;
}
// Compute Area & return area
double area()
{
return length*height;
}
}
class Rect_demo6
{
public static void main(String args[ ])
{
Rectangle myRect1 = new Rectangle(10,20);
Rectangle myRect2 =new Rectangle(30,40);
double area;
// Get area of rect1
area = [Link]();
[Link]("Area = "+area);
area = [Link]();
[Link]("Area= "+area);
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 17


SYBSC-Skill Enhancement Course (SEC)-25-26
Explanation:
➢ Rectangle and Rect_demo6 are two classes.
➢ Rectangle class contains the constructor with the name Rectangle ( ) to initialised instance variables
length and breadth of int type respectively. This class also contains method area ( ) to find the area of
a rectangle.
➢ Rect_demo5 class contains only one method main ( ). myRect 1 and myRect 2 are two objects of the
class Rectangle to find the area. Area is found by invoking the method area (). 10 and 20 are the
arguments passed to the constructor and assigns the values to the parameters l and h respectively by
statement [Link] 30 and 40 are passed using statement II. The out put is as follows:
Save the file with: Rect_demo6 under Maths
Compile the file with: C:\Maths>javac Rect_demo6.java
Run the file with: C:\maths>java Rect_demo6
Area = 200.0
Area = 1200.0
Example 2: Let Operator class contains 4 methods to calculate sum, product, and division of two
variables. Let Operator be a constructor to initialise the instance variables. Oper_constructor class
contains main ( ) method. myOper is an object of the class Operator to invoke different methods of
Operator class.
Class :Operator
Instance variables: a,b
Constructor:Operator
Methods:sum , product,division,

Class:Oper_constructor
Method: main ( ) myOper
The program is given below:

class Operator1
{ int a,b;
int sum(int x, int y)
{ int z ;
z=x+y ;
return z ; }
int product(int x, int y)
{ int z ;
z=x * y;
return z ; }
int division(int x, int y)
{ return x / y ; }
public Operator1 (int m, int n) //constructor
{ a=m ;
b=n ; }
}
class Oper_constructor
{ public static void main(String args[ ])
{
//Create and allocate memory to the object.
Operator1 myOper = new Operator1 (7,4);
// sum( ) method is invoked for myOper
[Link] ("Sum="+[Link] (2,4));
// product( ) method is invoked for myOper
[Link] ("Product="+[Link] (11,10));
// division( ) method is invoked for myOper
[Link] ("Division="+[Link] (8,3));
} }
Rahul Deshmukh Module-2: Basics of Java Programming 18
SYBSC-Skill Enhancement Course (SEC)-25-26
The output is as follows:
Save the file with: Oper_constructor under Maths
Compile the file with: C:\Maths>javac Oper_constructor.java
Run the file with: C:\Maths>java Oper_constructor
Sum=6
Product=110
Division=2

[Link]:

Suppose you have a class called Compute with three different methods of adding two variables where the
first method adds 2 integers, another method that add 2 float values and the third adds a float and a int.
These methods are doing the same job so it is appropriate to give the same name to all three methods.
This is possible using overloading technique in Java. Hence these three methods can be declared as:

void add(int a, int b); // adds 2 integers


void add(float a, float b); // adds 2 floats
void add(int a, float b); // adds 1 integer and 1 float

Thus overloaded methods are those methods which are in the same class and have the same name but
different parameter lists.

Its name and the parameter list define a signature of the method. Thus, two methods having same name
must have different parameter list in the order to have different signatures. A class cannot have two
methods with same signature. This is because the compiler will not know which method to invoke, if
more than one method has the same signature. Java uses method overloading to implement
polymorphism.

Example1: Let us write a program to calculate the sum of different parameter list as given in the above
box.

Class: Compute Class: compu_demo


Method: main ( )
Methods: 3 add( ) with different
parameters.

Rahul Deshmukh Module-2: Basics of Java Programming 19


SYBSC-Skill Enhancement Course (SEC)-25-26

class Compute
{
int add(int a, int b) // Method 1
{
int c;
c=a+b;
return c;
}
float add(float a , float b) // Method 2
{
float c;
c=a+b;
return c;
}

float add(float a , int b) //Method 3


{
float c;
c=a+b;
return c;
}
}

class compu_demo
{
public static void main(String args[])
{
Compute com = new Compute ();
[Link] ([Link](10,30)); //Goes to method 1
[Link]([Link](10.2f,30)); //Goes to method3
}
}

In the above program, there are three add () methods. At the time of compilation, the compiler will search
for the versions of add () method to be called based on the parameters passed.

The output is as follows:

Save the file with: compu_demo under Maths


Compile the file with: C:\Maths>javac compu_demo.java
Run the file with: C:\Maths>java compu_demo
40
40.2

Example 2:Consider 4 different methods with same name result( ) but contains different code. The box
diagram is as follows.

Rahul Deshmukh Module-2: Basics of Java Programming 20


SYBSC-Skill Enhancement Course (SEC)-25-26

Class:Operator Class:Result_demo7

Methods: result( ) Object statements:


i) Without parameter. result( )
ii) a  0, result (7)
iii) add 2 int , result (10,15)
iv) multiply 2 double, result(12.5)
iv)without parameter.

op.

The program is given below:

//Overloading
class Operator
{
void result () //Method 1
{
[Link]("No parameter ");
}
void result (int a )
{
[Link]("a is not zero ");
}
void result (int a,int b)
{
int c;
c=a+b;
[Link]("sum of a and b is : "+ c);
}
double result (double a )
{
[Link]("Double a :"+a);
return a*a;
}
}
class Result_demo7
{
public static void main(String a[])
{
double r;
Operator op = new Operator();
[Link] ();
[Link] (7);
[Link] (10,15);
r= [Link] (12.5);
[Link]("Result of [Link] (12.5)"+r);
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 21


SYBSC-Skill Enhancement Course (SEC)-25-26
The out put is as follows:
Save the file with: Result_demo7 under Maths
Compile the file with: C:\Maths> javac Result_demo7.java
Run the file with: C:\Maths> java Result_demo7
No parameter
a is not zero
sum of a and b is : 25
Double a :12.5
Result of [Link](12.5)156.25

// method to find distance of a point from origin & from a point by method overloading
class Point
{
private double x,y;

/* method to initialize the the properties of a point*/


public void setxy(double x,double y)
{
this.x=x;
this.y=y;
}

/* method to find distance of a point from origin */


double getDistance()
{
double dist=[Link]( x*x + y*y );
return dist;
}

double getDistance(Point P)
{
double dist=[Link]( (x-P.x)*(x-P.x) + (y-P.y)*(y-P.y) );
return dist;
}

void Display()
{
[Link]("X = " + x + " Y = " + y);
}
}

class DemoPoint
{
public static void main(String arg[])
{
Point p=new Point();
[Link](10,10);
Point q=new Point();
[Link](5,5);
[Link]("The point P is :");
[Link]();
[Link]("The point q is :");
[Link]();
[Link]("The d(P,Q) is : " + [Link](q));
}
}
Rahul Deshmukh Module-2: Basics of Java Programming 22
SYBSC-Skill Enhancement Course (SEC)-25-26

Using Objects as Parameters

So far we have only been using simple types as parameters to methods. However, it is both
correct and common to pass objects to methods.

For example, consider the following simple program:

// Objects may be passed to methods.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
[Link]("ob1 == ob2: " + [Link](ob2));
[Link]("ob1 == ob3: " + [Link](ob3));
}
}

This program generates the following output:

ob1 == ob2: true


ob1 == ob3: false

As you can see, the equals( ) method inside Test compares two objects for equality and returns
the result.
That is, it compares the invoking object with the one that it is passed. If they contain the same
values, then the method returns true. Otherwise, it returns false.
Notice that the parameter o in equals( ) specifies Test as its type. Although Test is a class type
created by the program, it is used in just the same way as Java's built-in types.

One of the most common uses of object parameters involves constructors. Frequently you will
want to construct a new object so that it is initially the same as some existing object. To do this, you must
define a constructor that takes an object of its class as a parameter.

For example, the following version of Box allows one object to initialize another:

Rahul Deshmukh Module-2: Basics of Java Programming 23


SYBSC-Skill Enhancement Course (SEC)-25-26

// Here, Box allows one object to initialize another.


class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = [Link];
height = [Link];
depth = [Link];
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
// get volume of first box
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
// get volume of second box
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
// get volume of cube
vol = [Link]();
[Link]("Volume of cube is " + vol);
// get volume of clone
vol = [Link]();
[Link]("Volume of clone is " + vol);
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 24


SYBSC-Skill Enhancement Course (SEC)-25-26

As you will see when you begin to create your own classes, providing many forms of constructor
methods is usually required to allow objects to be constructed in a convenient and efficient manner.

A Closer Look at Argument Passing

In general, there are two ways that a computer language can pass an argument to a subroutine.
The first way is call-by-value. This method copies the value of an argument into the formal parameter of
the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the
argument used to call it.
The second way an argument can be passed is call-by-reference. In this method, a reference to an
argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference
is used to access the actual argument specified in the call. This means that changes made to the parameter
will affect the argument used to call the subroutine.
As you will see, Java uses both methods, depending upon what is passed. In Java, when you pass
a simple type to a method, it is passed by value. Thus, what occurs to the parameter that receives the
argument has no effect outside the method.
For example, consider the following program:

// Simple types are passed by value.


class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: " +
a + " " + b);
[Link](a, b);
[Link]("a and b after call: " +
a + " " + b);
}
}

The output from this program is shown here:


a and b before call: 15 20
a and b after call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10. When you pass an object to a method, the
situation changes dramatically, because objects are passed by reference. Keep in mind that when you
create a variable of a class type, you are only creating a reference to an object.
Thus, when you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument. This effectively means that objects are passed to methods
by use of call-by-reference. Changes to the object inside the method do affect the object used as an
argument.

For example, consider the following program:

Rahul Deshmukh Module-2: Basics of Java Programming 25


SYBSC-Skill Enhancement Course (SEC)-25-26

// Objects are passed by reference.


class Test {
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
[Link]("ob.a and ob.b before call: " + ob.a + " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}

This program generates the following output:

ob.a and ob.b before call: 15 20


ob.a and ob.b after call: 30 10

As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument. As a point of interest, when an object reference is passed to a method, the reference itself is
passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that
value will still refer to the same object that its corresponding argument does.

Note - When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed
by use of call-by-reference.

Returning Objects

A method can return any type of data, including class types that you create.

For example, in the following program, the incrByTen( ) method returns an object in which the
value of a is ten greater than it is in the invoking object.

Rahul Deshmukh Module-2: Basics of Java Programming 26


SYBSC-Skill Enhancement Course (SEC)-25-26

// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: " + ob2.a);
}
}

The output generated by this program is shown here:


ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it
is returned to the calling routine.
The preceding program makes another important point: Since all objects are dynamically
allocated using new, you don't need to worry about an object going out-of-scope because the method in
which it was created terminates. The object will continue to exist as long as there is a reference to it
somewhere in your program. When there are no references to it, the object will be reclaimed the next
time garbage collection takes place.

Examples-

Rahul Deshmukh Module-2: Basics of Java Programming 27


SYBSC-Skill Enhancement Course (SEC)-25-26

// Passing object to the method


/* we can pass object to the method by giving object name.
The passing object to the method is called passing by reference.*/
class Complex
{
float real;
float imag;
Complex()
{ }
Complex(float r, float i)
{
real = r;
imag = i;
}
void Add( Complex C2)
{
Complex C3 = new Complex();
[Link] = real + [Link];
[Link] = imag + [Link];
[Link]([Link] + "+" + [Link] + "i");
}
void Display()
{
[Link](real + "+" + imag + "i");
}
}
class ComplexAdd
{
public static void main(String args[])
{
Complex C1 = new Complex(5, 7);
Complex C2 = new Complex(2, 3);
[Link](C2);
[Link]();
}
}

Save & Run above program


7.0+10.0i
5.0+7.0i

Rahul Deshmukh Module-2: Basics of Java Programming 28


SYBSC-Skill Enhancement Course (SEC)-25-26

// Passing object to the method


/* we can pass object to the method by giving object name.
The passing object to the method is called passing by reference.*/
class Complex
{
float real;
float imag;
Complex()
{ }
Complex(float r, float i)
{
real = r;
imag = i;
}
Complex Add( Complex C2)
{
Complex C3 = new Complex();
[Link] = real + [Link];
[Link] = imag + [Link];
return(C3);
}
void Display()
{
[Link](real + "+" + imag + "i");
}
}
class ComplexAdd2
{
public static void main(String args[])
{
Complex C1 = new Complex(5, 7);
Complex C2 = new Complex(2, 3);
Complex C3 = new Complex();
C3=[Link](C2);
[Link]();
}
}

Save & Run above program


7.0+10.0i

Rahul Deshmukh Module-2: Basics of Java Programming 29


SYBSC-Skill Enhancement Course (SEC)-25-26

// Passing object to the method


/* we can pass object to the method by giving object name.
The passing object to the method is called passing by reference.*/
class Complex
{
float real;
float imag;
Complex()
{ }
Complex(float r, float i)
{
real = r;
imag = i;
}
static Complex Add( Complex C1, Complex C2)
{
Complex C3 = new Complex();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return(C3);
}
void Display()
{
[Link](real + "+" + imag + "i");
}
}
class ComplexAdd3
{
public static void main(String args[])
{
Complex C1 = new Complex(5, 7);
Complex C2 = new Complex(2, 3);
Complex C3 = new Complex();
C3=[Link](C1, C2);
[Link]();
}
}

Save & Run above program


7.0+10.0i
Questions:

(1) What are constructors? How they are different from methods? Can you overload the constructor?
(2) Can you call one constructor from another?
(3) What is overloading? Give one example.

Rahul Deshmukh Module-2: Basics of Java Programming 30


SYBSC-Skill Enhancement Course (SEC)-25-26

INHERITANCE

Starter: In the previous chapter you learn two special methods viz. constructors and overloading. In this
chapter you will see the implementation of the object oriented programming feature namely, Inheritance
via Java.

9.1 Definition of Inheritance:


In object oriented programming inheritance means the properties of the class that can be used by other
classes. It defines a relationship between classes. It can also be thought of as a hierarchy of abstraction,
where a class inherits a set of all attributes and related behaviour from a parent class. For instance, in real
life a child inherits all its (good and bad) properties from both parents.
9.2 Super classes and Sub classes:
Consider a class of vehicle. Vehicles are of two types: Land Vehicles and Air Vehicles. Both of them
have common attributes, for instance Vehicle number, colour, number of wheels, or there maybe certain
attributes which are not common to both of them for examples ladders are required by all air vehicles to
board passengers.
Vehicle

Land Air
Vehicle Vehicle

You can incorporate the structure and behaviour for these two classes to form a new class called the
super class. The superclass contains generalised properties taken from the class called sub class.
Subclass contains specialised property, which are not taken into the superclass.
A superclass is a class from which another class inherits properties. It shares its properties with its
child classes. A subclass is a class that inherits attributes and methods from a superclass.
A subclass does not inherit the constructors of the superclass, since, constructors hold a special
meaning to the compiler. Subclasses may also have their own instance variables & methods besides
those, which are inherited from the super class. Super class is referred to as parent class or base class and
subclass as a derived class or child class.
There are four types of inheritance: -
1. Single Inheritance
2. Multiple Inheritance ( Several Super classes )
3. Multilevel Inheritance
4. Hierarchical Inheritance

1. Single Inheritance: Here there is only one super class and subclasses are derived from the super
class. i.e. one subclass is derived from only one super class.

Super Class A

B
Subclass
For example, Car & Truck are 2 subclasses derived from the super class Vehicle.

Vehicle
Supe
r
Car Truck
class
Sub classes
Rahul Deshmukh Module-2: Basics of Java Programming 31
SYBSC-Skill Enhancement Course (SEC)-25-26

2. Multiple inheritance: Here there are several super classes and the subclasses are derived from more
then one super class.

For example a subclass child inherits the properties from the super class Father and Mother. Java does
not support Multiple Inheritance.

Father Mother 2 Super


classes

Sub
Child class
However Java does not support directly implement multiple inheritance. It is implemented in
the form of Interfaces Chapter.

9.2 Keyword extends:

Subclasses are derived from the super class using the key word called extends. The general format is:

class subclass_name extends super class_name


{
body of class ;
}
Consider the following program where the subclass - new class is derived from the super class - old
class.

Class: Old class Class: New class


Instance variables: a , b Instance variables: k
Method: setDisplayab( ) Method: setDisplayc( )
add ( )

Super
class supobj
Sub
subobj class

Following is the complete Java program.

Rahul Deshmukh Module-2: Basics of Java Programming 32


SYBSC-Skill Enhancement Course (SEC)-25-26

// Example of single inheritance


class oldclass //Create a super class
{
int a,b;
void setDisplayab()
{
[Link] ("a= "+a+" b= "+b);
}
}
class newclass extends oldclass
{
int c;
void setDisplayc()
{
[Link]("c= "+c);
}
void add()
{
[Link](a+b+c);
}
}
class Single_Inher
{
public static void main(String args[])
{
oldclass supobj=new oldclass();
newclass subobj=new newclass();
//Access the members from Super class.
supobj.a=6;
supobj.b=8;
[Link]("Content of Superclass:");
[Link]();
[Link]();
/* The subclass has access to all the public members of its superclass */
subobj.a=2;
subobj.b=3;
subobj.c=4;
[Link]("Content of Subclass:");
[Link]();
[Link]();
[Link]();
[Link]("sum of a,b and c is:");
[Link]();
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 33


SYBSC-Skill Enhancement Course (SEC)-25-26
You can see from the above program that the subclass newclass includes all the members of the super
class oldclass. For the same reason subobj can access a and b and call the method
SetDisplayab ( ). Also inside the method add ( ), a and b can be referred to directly as if they are sitting
inside the new class

Save the file :Single_Inher.java under Maths


Compile with:javac Single_Inher.java
Run with: java Single_Inher
The output is as follows:

C:\Maths>javac Single_Inher.java

C:\Maths>java Single_Inher
Content of Superclass: a= 6 b= 8
Content of Subclass: a= 2 b= 3 c= 4
sum of a,b and c is:9

9.3 Use of the Keyword super:

A subclass can be invoked by a constructor method of the super class by the keyword super with
the following format:
super (list of parameters);

This keyword is used only under the following conditions


(i) super ( ) is used only in the subclass constructor method.
(ii) super ( ) must be the first statement executed inside a subclass constructor.
(iii) List of parameters in the super ( ) must match the order and type of the instance
variable declared in the super class.

Thus if super_class is a super class and sub_class is a sub class then we have,

class super_class
{
super_class (list of variables)
{
---------
}
}
class sub_class extends super_class
{
sub_class (list of variables)
{
super (list of variables);//line 1 of the subclass constructor
}
}

Example: Consider the super class Rectangle and the sub class Box defined by the following box
diagram:

Rahul Deshmukh Module-2: Basics of Java Programming 34


SYBSC-Skill Enhancement Course (SEC)-25-26

Class: Rectangle Class: Box


Instance variables: length,breadth Instance variables: height
Constructor:Rectangle(a,b) Constructor:Box( a,b,c)
Method: area( ) Method: volume ( )

Super Class Sub Class

Following is the complete program to compute the area and volume.

class Rectangle
{
int length;
int breadth;
Rectangle (int a, int b) //constructor of
{ super class
length = a ;
breadth = b;
}
int area ( ) //method in super class
{
return(length*breadth);
}
}
class Box extends Rectangle
{
int height;
Box(int a, int b, int c ) //constructor of sub class
{
super (a,b );//passing values to super class
height = c;
}
int volume ()
{
return (length*breadth*height);
}
}
class Inher_demo
{ public static void main(String[] args)
{
Box bo= new Box (12,14,17);
int area1= [Link]();//super class method
int volume1=[Link]();//subclass method
[Link](" Area = " + area1);
[Link](" Volume = "+volume1);
}
}

Save the file :Inher_demo.java under Maths


Compile with:javac Inher_demo.java
Run with: java Inher_demo
The output is as follows:
Rahul Deshmukh Module-2: Basics of Java Programming 35
SYBSC-Skill Enhancement Course (SEC)-25-26
C:\Maths>javac Inher_demo.java
C:\Maths>java Inher_demo
Area = 168
Volume = 2856

9.4 Use of super to access the member of Super class:


The super keyword is used to access the members of super class. It can be done by the format:

[Link];
Where the member might be an instance variable or method
Consider the super class Outer and the sub class Inner as shown in the following box diagram:

Class: Inner
Class: Outer
Instance variables: i
Instance variables: i , j
Constructor: Inner ( )
Method: show( )
Method: show ( )

Super
class Sub
obj class
Class : Super_Demo
Method: main( )
Following is the complete program where the method show ( ) will be accessed from Inner class.

Class Outer
{ int i,j ;
void show ()
{
[Link](“Super i = “ +i );
}
} // end of Outer class
class Inner extends Outer
{
int i ; // this i hides the i in the outer class
Inner (int a, int b) // constructor of Inner
{ super.i = a ;// i is from the OuterClass
i = b; // i is from the InnerClass
j=a; // j is from the OuterClass
} //end of constructor
void show()
{ [Link](" i from super class " + super.i);
[Link](" i from subclass and j from super class: " + i +" and "+j );
}
} // end of Inner class
class super_demo
{ public static void main(String[] args)
{ Inner obj= new Inner (10,20);
[Link]( ); } }
Save the file :super_demo.java under Maths
Compile with:javac super_demo.java
Run with: java super_demo The output is as follows:
Rahul Deshmukh Module-2: Basics of Java Programming 36
SYBSC-Skill Enhancement Course (SEC)-25-26

C:\Maths>javac super_demo.java
C:\Maths>java super_demo
i from super class: 10
i from subclass and j from super class: 20 and 10

// Example of single inheritance


class One
{
int a;
void GetOne()
{
a=10;
}
void PutOne()
{
[Link]("a="+a);
}
}
class Two extends One
{
int b;
void GetTwo()
{
b=20;
}
void PutTwo()
{
[Link]("b="+b);
}
}
class SingleInher
{
public static void main(String args[])
{
Two x = new Two();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

C:\Maths> javac [Link]


C:\Maths> java SingleInher
a=10
b=20

Rahul Deshmukh Module-2: Basics of Java Programming 37


SYBSC-Skill Enhancement Course (SEC)-25-26

3. Multilevel Inheritance – A subclass is derived from another derived class or subclass. It uses a
derived class or subclass as a superclass.

A // Example of Multilevel inheritance


Super class class One
{ int a;
void GetOne()
Intermediate B { a=10;
Superclass }
void PutOne()
{ [Link]("a="+a);
Subclass C }
}
class Two extends One
{ int b;
void GetTwo()
{ b=20;
}
void PutTwo()
{ [Link]("b="+b);
}
}
class Three extends Two
{ int c;
void GetThree()
{ c=30;
}
void PutThree()
{ [Link]("c="+c);
}
}
class MultiInher
{ public static void main(String args[])
{
Three x = new Three();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

C:\Maths> javac [Link]


C:\Maths>j java MultiInher
a=10
b=20
c=30

Rahul Deshmukh Module-2: Basics of Java Programming 38


SYBSC-Skill Enhancement Course (SEC)-25-26

4 Hierarchical Inheritance
Many subclasses are derived from one superclass.

B C D

Example –

// Example of Hierarchical inheritance


class One
{ int a;
void GetOne()
{ a=10;
}
void PutOne()
{ [Link]("a="+a);
}
}
class Two extends One
{ int b;
void GetTwo()
{ b=20;
}
void PutTwo()
{ [Link]("b="+b);
}
}
class Three extends One
{ int c;
void GetThree()
{ c=30;
}
void PutThree()
{ [Link]("c="+c);
}
}
class HierarchicalInher
{ public static void main(String args[])
{ Two x = new Two();
Three y = new Three();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](); } }

Rahul Deshmukh Module-2: Basics of Java Programming 39


SYBSC-Skill Enhancement Course (SEC)-25-26

The Output is as follows


C:\Maths> javac [Link]
C:\Maths>j java MultiInher
a=10
b=20
a=10
c=30

9.5 Overriding Method:

We have seen that overloaded methods are those methods, which are in the same class and have the
same name but different parameter lists. On the other hand, if methods are in super class as well as in
subclass then these methods are called as overriding methods.

For example, consider a class Shape as a super class. Let rectangle and circle be two derived
classes from the Shape class. Suppose CompuetArea ( ) is a behaviour of the Shape class. There are
different formulae to calculate the area for different shapes. Therefore the ComputeArea ( ) method is
invoked in different ways in the classes rectangle and circle.

Shape super class

ComputeArea ( )

Rectangle circle

Hence we have the following definition:


If a method defined in the subclass has the same signature as that of the super class, then the subclass
method overrides (hides or suppressed) the definition of the super class method.
Example: Let A and B be two classes with i,j be the instance variables of A and k be the instance
variable of B. Let display ( ) be the method of both the classes to display i,j,k. Following is the box
diagram:
Class: A Class: B
Instance variables: i , j Instance variables: k
Constructor: A Constructor:B
Method: display( ) Method: display( )

Superclass

Subclass
subobj
suo

Class:Override
Method:main ( )

Rahul Deshmukh Module-2: Basics of Java Programming 40


SYBSC-Skill Enhancement Course (SEC)-25-26

Following is the complete program.

class A
{
int i,j;
A{int a, int b) //constructor
{
i=a;
j=b;
}
//display i and j
void display( )
{
[Link](" i and j ; " + i + " " + j );
}
}

class B extends A
{
int k;
B(int a, int b, int c ) //constructor
{
super (a,b); //invoking from constructor A
k=c;
}
//display k-- this overrides display() of A
void display()
{
[Link](" k : " + k );
}
}
class override
{
public static void main(String[] args)
{
B subobj = new B (1,2,3);
[Link]();//this calls display() of B
}
}
Let us execute the program and then run it by giving following commands:

Save the file :[Link] under Maths


Compile with:javac [Link]
Run with: java override
The output is as follows:

C:\Maths>javac [Link]
C:\Maths>java override
K=3

Rahul Deshmukh Module-2: Basics of Java Programming 41


SYBSC-Skill Enhancement Course (SEC)-25-26
Important Remarks:
1. In the above program, when display ( ) method is invoked of an object in the class B, the code of
display () defined within B is invoked. That is the code of display( ) inside B overrides the code declared
in A.
If you are interested to invoke display ( ) method of class A then it can be done by the
keyword super. For example, consider the following code:

class B extends class A


{
int k;
B (int a, int b , int c )
{
super (a,b);
k=c;
}
void display()
{
[Link]();//this calls A's display()
[Link](" k : " + k );
}
}

If you insert this code into the previous program, then you will get the following output

i and j : 1 2
k:3

Here [Link] ( ) statement plays an important role and sends the control to super class A
and displays i and j of A.

2. Overriding methods occur if and only if the name and the type of signatures of the two methods are
identical. If they are not then the two methods are said to be overloaded. For example, modify the above
program as follows:
Sub class: B
Super
Super class:
class: A A
Instance variables: i,j Instance variables: k
Instance variables: i,j
Constructor: (a,b) Constructor: B(a,b,c)
Constructor: A(a,b)
Method: display()
Method: display()
Method: display()

Rahul Deshmukh Module-2: Basics of Java Programming 42


SYBSC-Skill Enhancement Course (SEC)-25-26
class A
{
int i,j;
A(int a, int b) //constructor of A
{
i=a;
j=b;
}
void display( ) ////display i and j
{
[Link](" i and j ; " + i + " " + j );
}
} //end of class A
class B extends A
{
int k;
B(int a, int b, int c ) //constructor of B
{
super (a,b);
k=c;
}
void display(String msg) //overload display ( )
{
[Link](msg + k);
}
}
class override1 {
public static void main(String args[])
{
B subobj = new B ( 1,2,3);
[Link](“this is k :”);//this call display() in B
[Link]();//this calls display() in A
}
}

Let us execute the program and then run it by giving following commands:

Save the file :[Link] under Maths


Compile with:javac [Link]
Run with: java override1
The output is as follows:

C:\Maths>javac [Link]
C:\Maths>java override1
This is k : 3
i and j : 1 2

The code of display in B takes a string parameter. This makes its type signature different from the one in
A, which takes no parameters. Therefore no overriding (name hiding) takes place.

Rahul Deshmukh Module-2: Basics of Java Programming 43


SYBSC-Skill Enhancement Course (SEC)-25-26

9.6 ABSTRACT CLASSES:

In real life it is difficult to imagine the model of a given object. For instance, you know that
rectangle, circle and parabola are the objects of the class shape. If some one asks you how the rectangle
looks like? You will immediately answer that “A rectangle is a 2- dimensional figure having length and
breadth”. Area and perimeter can be found for rectangle. But if someone asks you how would you
describe a shape? Then you will not have answer as shape is abstract and can’t be properly defined like
circle, parabola. There are many classes, which are abstract. For example, Vehicle, mammals are
abstract classes.
Abstract class is a super class and has generalised properties. In Java abstract class is defined
using the keyword abstract .For example, the class shape can be defined as:

abstract class shape


{

}

The method can be defined as abstract with the following format:

abstract type name (parameter list);


Note that there is no body for this method. For example, area ( ) method of the abstract class
Shape will not have body. One can also have more than one abstract method.
Example: Let us consider a simple example of finding area of 2 different shapes say triangle and circle.
Let Shape be an abstract class with Shape () as a constructor and area () as an abstract method. Let
Triangle and Circle be two subclasses of Shape contains corresponding area ( ) methods. It should be
noted that variables used in these methods must be taken as instance variables and not local variables.
Following is the box diagram:

Class: Shape

Abstract Instance variables: a , b


class
Constructor: Shape( )

Method: area ( )

Class: Triangle Class: Circle


T C
Instance variables:x, y Instance variables: x,y

Constructor: Triangle( ) Sub Constructor: Circle( )


Classes
Method: area ( ) Method: area ( )

Rahul Deshmukh Module-2: Basics of Java Programming 44


SYBSC-Skill Enhancement Course (SEC)-25-26

abstract class Shape


{
double a;
double b;
Shape ( double x, double y) //constructor
{
a=x;
b=y;
}
// area is a abstract method
abstract double area();
}
class triangle extends Shape
{
triangle(int x, int y)
{
super (x,y);
}
// override area() for the triangle
double area()
{
return (a*b)/2;
}
}
class circle extends Shape
{
circle (int x, int y) //constructor
{
super (x,y);
}
//override area for circle
double area( )
{
return((a*a)*(22/7));
}
}
class abstract_demo
{
public static void main(String args[])
{
triangle T = new triangle(4,2);
circle C = new circle (14,0);
Shape sha;//no object is created
// Shape sha = new Shape (4,2);//Not correct
sha = T;
[Link](" Area of triangle is " +[Link]());
sha = C;
[Link](" Area of circle is " + [Link]());
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 45


SYBSC-Skill Enhancement Course (SEC)-25-26
It should be noted that it is not possible to define the object of class shape as shape is an abstract class but
you can create a reference variable of type shape.
Reference variable means that it can be used to refer too an object of any class derived from shape.
Let us execute the program and then run it by giving following commands:
Save the file :abstract_demo.java under Maths
Compile with:javac abstract_demo.java
Run with: java abstract
The output is as follows:

C:\Maths>javac abstract_demo.java
C:\Maths>java abstract_demo
Area of triangle is 4.0
Area of circle is 588.0

9.7 FINAL VARIABLES AND METHODS:


We have seen in overriding method that all the variables and methods can be overridden in subclasses.
To prevent this the keyword final is used. It can be used as follows for variables and methods:

(i) final int var = 40;


means the value of a final variable of the class can never be changed and this value of var will not be
taken automatically by their derived classes.

(ii) final void display ( ){ }


means that this is the last method of that class and can’t be used by their derived classes.
Example: Let us consider the following segment of code:
class A
{ final void display()
{
[Link](“ In show of A “);
}
}
class B extends A
{ void display() // can not override because it is declared with final
{
[Link](“ In show of B “);
}
}// can’t found output.
(iii) final class A{}
If we want a particular class should not be inherited y any other class then that class must be declared
with final keyword.
Example: Let us consider the following segment of code:

final class A
{ void display()
{
[Link](“ In show of A “);
}
}
class B extends A // error class should not be inherited
{ void display()
{
[Link](“ In show of B “);
}
}// can’t found output.

Rahul Deshmukh Module-2: Basics of Java Programming 46


SYBSC-Skill Enhancement Course (SEC)-25-26
9.8 Static Keyword

Normally a member must be accessed only in conjunction with an object of its class. 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 as static,
it can be accessed before any objects of its class are created. Both methods and variables of a class
can be declared as static. The most common example of a static member is main() .

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.

Method 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. (super would be discussed later)

In order to initialize static variables, a static block is declared, which gets executed exactly once.

Example

class A Static data member


{
static int a;
static int b;
int b;
static Static initialization block
{
a=1;
b=1;
} Static member method
static void disp()
{
[Link](“The variable a is : “ + a);
[Link](“The variable b is : “ + b);
}
}

To call a static method from outside the class use the following form :

[Link]();
classname is the name of the class in which the static member is defined.
Eg: [Link]();

A static variable can be accessed in the same way.


Eg: A.a = 10

Rahul Deshmukh Module-2: Basics of Java Programming 47


SYBSC-Skill Enhancement Course (SEC)-25-26
Garbage Collection
An object exists in the heap, and it can be accessed only through variables that hold references to the
object. What should be done with an object if there are no variables that refer to it? Such things can
happen. Consider the following two statements (though in reality, you'd never do anything like this):

Student std = new Student("John Smith");


std = null;
In the first line, a reference to a newly created Student object is stored in the variable std.
But in the next line, the value of std is changed, and the reference to the Student object is gone. In
fact, there are now no references whatsoever to that object stored in any variable. So there is no way for
the program ever to use the object again. It might as well not exist. In fact, the memory occupied by the
object should be reclaimed to be used for another purpose.

Java uses a procedure called garbage collection to reclaim memory occupied by objects that are
no longer accessible to a program. It is the responsibility of the system, not the programmer, to keep track
of which objects are "garbage". In the above example, it was very easy to see that the Student object
had become garbage. Usually, it's much harder. If an object has been used for a while, there might be
several references to the object stored in several variables. The object doesn't become garbage until all
those references have been dropped.

In many other programming languages, it's the programmer's responsibility to delete the garbage.
Unfortunately, keeping track of memory usage is very error-prone, and many serious program bugs are
caused by such errors. A programmer might accidently delete an object even though there are still
references to that object. This is called a dangling pointer error, and it leads to problems when the
program tries to access an object that is no longer there. Another type of error is a memory leak, where a
programmer neglects to delete objects that are no longer in use. This can lead to filling memory with
objects that are completely inaccessible, and the program might run out of memory even though, in fact,
large amounts of memory are being wasted.

Because Java uses garbage collection, such errors are simply impossible. Garbage collection is an old
idea and has been used in some programming languages since the 1960s. You might wonder why all
languages don't use garbage collection. In the past, it was considered too slow and wasteful. However,
research into garbage collection techniques combined with the incredible speed of modern computers
have combined to make garbage collection feasible.
The finalize Method

Some times an object will need to perform some action when it is destroyed. To handle such situations,
java provides a mechanism called finalization. By using finalization one can specify the actions that will
occur when an object is just about to be reclaimed by the garbage collector. To add finalizer to a class
simply define finalize() method. The java runtime calls that method whenever it is about to recycle an
object of that class. Inside the finalize() method, code is specified for actions that must be performed
before an object is destroyed.

Syntax

protected void finalize()


{
// finalization code here
}

Rahul Deshmukh Module-2: Basics of Java Programming 48


SYBSC-Skill Enhancement Course (SEC)-25-26
Questions:

[1] What do you understand inheritance in Java? What are their advantages? What are the different forms
of inheritance? Does Java support all of them?
[2] Consider the class hierarchy class1 --- class2--- class3. Assume that all classes contains a method
called as show ( ) and if you want to call the method show ( ) of class2 and class3 then how you will
proceed?. How can you call the constructors of class2 and class3?
[3] What does overriding mean?
[4] What do you mean by abstract class? Can an abstract class contain method with body? Can you call a
variable as abstract?
[5] What do you mean by final variable and final method?

Try your self:


[1] Write a Java program contains a method set () to hold two float numbers in a base class. The derived
class contains method showMax () which displays the maximum of two numbers and method
showMin () which displays the minimum of two numbers.
[2] Create a class called Number that accepts an array of ten numbers. Create a sub class called subNum
having menu as follows:
❖ Display numbers entered.
❖ Sum of the numbers.
❖ Average of numbers.
❖ Maximum of numbers.
Create an appropriate method in the subclasses to execute as per choice and it should continue
until you press Ctrl + a. Write a Java application to do this.
[3] Create a class called Shape as base class having two methods: setCoord () to accept x and y co-
ordinates, showCoord () to display these co-ordinates. Create a subclass called Rectangle contains a
method showCoord () to display the length and breadth of the rectangle.
In the main method, execute the showCoord () method of the Rectangle class. Write a Java application
for this.
[4] Create a class car. Initialise the colour and the body to blue and wagon respectively. Create two
constructors of which one is a default constructor that create a blue car and other contains two
arguments viz. colour and body. Write a method toString that returns the colour and the body.
Create a subclass playCar having two constructors. Call the base class constructors from these two
constructors. Write another method playCD in the subclass that display the message “Beautiful
music fills the passenger compartment”. Execute the methods to display the following:
My car is a blue wagon.
My father’s car is a red convertible.

Rahul Deshmukh Module-2: Basics of Java Programming 49


SYBSC-Skill Enhancement Course (SEC)-25-26

ACCESS SPECIFIERS

The feature of a class (the calls itself, instance variable, and methods) used by other classes is
called access specifies. Java supports three access specifies
1. public access specifier
2. private access specifier
3. protected access specifier

1. The Public Access Specifier:

We know that the scope of variable and methods is for the entire class. To make this scope
available to all the classes outside this class you can define variable or method as public. For example,

public int pubvar;


public void show( ){ … …}
2. private access specifier:

All the classes except inner classes have the public access specifier
to make the scope of the members (instance variable and methods )restricted to the class you can use
private access specifier. Variables and methods can be made private and their scope is only for that class.
Thus these members can't be inherited into subclasses if members of the class are defined as private. A
method declared as private behaves like a method declared as final.
This modifier is the most restrictive access modifier. Note that the top level class in the
inheritance hierarchy is never declared as private. The members can be declared as private by the
following example:
private int add(int a, int b ){… …}
Consider the following example:
class Pubpri
{ void int a; //default access
public int b;//public access
private int c;//private access
void setDimC(int i)
{
c=i;
}
int getc() Class: pubpri
{
return c; Instance variables:
} a - void,b -public, c- private
class Access_Pubpri Methods: Set DimC(i) for c.
{ getc()
public static void main(String[ ] args)
{ Class: access pubpri public
Pubpri obj = new Pubpri(); method
obj.a =1;//this is possible
obj.b=2;//this is possible
obj.c=3; // this will give an error
[Link](10);//this is possible
[Link]("a,b,and
c:"+obj.a+obj.b+[Link]());
}
}
Rahul Deshmukh Module-2: Basics of Java Programming 50
SYBSC-Skill Enhancement Course (SEC)-25-26

3. Protected Access Specifier:

Variable methods and inner classes that are declared protected are accessible to the subclasses of
the class in which they are declared. For example,
Protected int [Link];

Consider the following set of classes. Class B and C are inherited from class A. class c belongs to
the package F1 which is a collection of classes P1 and classes A and B belong to the package P2.
Suppose a method My method( ) is in the class A . The following table shows you accessibility of
the method my method from classes B and C.

Class A
Package2

Class B
Class C

Access Specifier Class B Class C


Mymethod() is declared Accessible as B is a subclass. Accessible as C is a subclass.
protected
Mymethod() is declared public Accessible as it is in the Accessible as it in the same
same package. package.

Mymethod() is declared Accessible as it is in the Accessible as it is in the


friendly same package. same package.

Following table summarises the visibility provided by various access modifiers.

Access Modifier Public Private Protected Default Friendly

Access Location

Same Classes Yes Yes Yes Yes


Subclass in same package Yes No Yes Yes
Other classes in same package Yes No Yes Yes
Subclasses in other package Yes No Yes Yes

Non-subclasses in other package. Yes No Yes Yes

Rahul Deshmukh Module-2: Basics of Java Programming 51


SYBSC-Skill Enhancement Course (SEC)-25-26

Access Specifier mymethod Class B subclass in same P Class C subclass in other P


of Class A declared
Public Accessible as it is in the Accessible as C is a
same package. subclass of A.
Private Not accessible. Not accessible.
Protected Accessible Accessible
Friendly Accessible Not Accessible

4. Friendly Access:

In previous examples, we have not used public modifier but then members are accessible to
other classes in a program. When no access modifier is specified, the member defaults to a limited
version of public accessibility known as “Friendly” level of access.
The difference between the ‘public’ access and the ‘friendly’ access is that the public
modifier makes scope of members accessible to all the classes regardless of their package. On the
other hand the friendly access makes scope of member accessibility only in the same package, but
not in other package.

Rahul Deshmukh Module-2: Basics of Java Programming 52


SYBSC-Skill Enhancement Course (SEC)-25-26
EXCEPTIONS

Starter: The programmer always makes mistakes in typing or in the logic of the program. It is rare that
the program run successfully at the first attempt. A mistake might lead to an error causing the program to
produce unexpected results.
Following are two types of errors:
 Compile-time error.
 Run-time error.
Let us study one after another.
11.1 Compile-time error:
Java compiler handles the errors like syntax errors, missing semi colons (;), missing brackets for the
methods or for the classes etc. at the time of the compilation of the program and therefore these
errors are termed as Compile-time error.
11.2 Run-time error:
Some times, Java program may compile successfully by creating the. class file but may not run.
Such programs may produce wrong results due to wrong logic or may terminate due to errors such
as stack over flow. These errors are termed as run time error. Some of the run time errors are
dividing an integer by zero, accessing an element that is out of bounds of an array etc.
Consider the following simple example where run-time error has occurred.
P
class Error
{
public static void main( String args [ ])
{
int x = 14;
int y = 6;
int z= 6;
int result = x/(y-z); /* Division by zero */
[Link]( “Result =”+result);
int ans = x/(y+z); /*This is sensible */
[Link]( “Answer =”+ans);
}
}

The above program does not have any serious error and you will not get any compile-time error.
The programmer is expecting an output after running the program, but will be disappointed as the
computer will shout and display the following message.

Exception in thread "main" [Link]: / by zero


at [Link]([Link])

When Java run-time tries to execute a division by zero, it generates an error condition, which causes the
program to stop after displaying an appropriate message.
11.3 What are Exceptions and call stack?
Java supports run-time error mechanism known as Exceptions. Run time errors occur at the time
of the running of the program. These errors are handle by writing block of code so, if error occurs then
this block take care of this error and execute the remaining portion of the program. In Java, there is a
mechanism to handle these exceptions which you are going to learn in this chapter.

A call stack is a sequence of methods invoked by the Java Circle ( ) Top


compiler.
For example, if a method name
shape ( ) calls another method name Shape ( ) Bottom
circle ( ) then the call stack looks as shown in the figure.

Rahul Deshmukh Module-2: Basics of Java Programming 53


SYBSC-Skill Enhancement Course (SEC)-25-26
One can have more methods calling each other. For instance circle ( ) might call another
method called draw( ).Then
circle ( ) can sit at the bottom of the call stack and draw ( ) might call
another method say paint ( ). Top paint ( )
If an exception occurred in paint ( ) method then it would be
possibly ignored by all the methods of the call stack and this
exception would be passed all the way down in the call stack and the draw( )
program will be terminated.
To handle exception, one has to catch this exception along the
way in the call stack. These exceptions are handle in Java using circle ( )
five keywords: try, catch, finally, throws and throws.
Bottom shape ( )
11.4 try and catch block:

When there is a possibility of an exception in a program it is better to Exceptio


use try and catch keywords. The advantage of these keywords is that, n in
it fixes the error and prevents the program to terminate abruptly.
The general syntax is:

try
{
Block of statements where possible
exception has occured;
}
catch ( Exception_type object )
{
Block of statements to catch the
exception occurred in try block;
}

The sequence of code, which is to be guarded, must be written try block :


inside the try block. The catch block must be immediately after the try Guarding the
block. The catch block contains statements explaining the cause of statements
exception generated.

There are some of the common type of exceptions Catch block :


(Exception_type) occurred in Explanation of the
the program as listed below. These exceptions are to be written in exception.
the bracket after the key word catch along its object.

Type of Exception Reason of Exception

ArithmeticException Occurred because of math errors like division by zero.


ArrayOutOfBoundsException Occurred by bad array indexes.
ArrayStoreException Occurred when you tries to store wrong type of data in an
array.
FileNotFoundException Occurred by an attempt to access a non existent file.

Rahul Deshmukh Module-2: Basics of Java Programming 54


SYBSC-Skill Enhancement Course (SEC)-25-26

Type of Exception Reason of Exception

IOException Occurred due to general I/O failuer,such as inability to


read from a file.
NumberFormatException Occurred due to the conversion between string and
number fails.
StringIndexOutofBoundsException Occurred when a program attempts to access a
nonexistent character position in a string.

For example, consider the following:

try
{
ans=a/b;
}
catch(ArithmeticException e)
{
[Link](“Division is not possible”);
}

Where a=4 and b=0.


Let us consider few programs to illustrate the catch and try block.

Example1: Following program illustrates the catch and try block, where try block guards the
arithmetic expression and throws an exception object in catch block.

class mistake1
{
public static void main( String args [ ])
{
int x = 14;
int y = 6;
int z= 6;
try
{
int result = x/(y-z); /* Division by zero */
}
catch(ArithmeticException e)
{
[Link]( "Division by zero");
}
int ans = x/(y+z); /*This is sensible */
[Link]( "Answer ="+ans);
}
}
How the program works?
• x,y and z are declared as int variables taking values 4,6 and 6 respectively.
Rahul Deshmukh Module-2: Basics of Java Programming 55
SYBSC-Skill Enhancement Course (SEC)-25-26
• try block contains only one statement for finding the integer value of the expression and assigning it
to result. This statement is guarded using try block. If an exception occurs then the control will shift
to catch block. Here the exception has occurred as the denominator is zero.
• The exception is of Arithmetic in nature so the object e of ArithmeticException is taken inside the
bracket after the keyword catch.
• ans is the int variable holding the value of the expression given on the R.H.S. The question will
definitely come in your mind that, why this statement is written after the try/catch block and why not
inside the try block as the statement, after the value of the result is found. The answer of this question
will be given in the next example.
Compile the above program by giving the command:
C:\MATHS >javac [Link]
Run the above program by giving the command:
C:\MATHS >java mistake1
Division by zero
Answer =1
Example 2:Let us insert the expression for ans inside the try block as follows:
class mistake2
{
public static void main( String args [ ])
{
int x,y,z;
int result,ans;
x=[Link](args[0]);
y=[Link](args[1]);
z=[Link](args[2]);
try
{
result = x/(y-z);
ans = x/(y+z);
}
catch(ArithmeticException e)
{
[Link]( "Division by zero");
}
[Link]( "Answer ="+ans);
} }

How the program works?


• The class mistake1 contains the important method called parse of the Wrapper class. This method is
used to insert the values to the integer variables using console. You will learn this method in detail in
the chapter of Streams.
Let us execute and run the program as follows:
C:\MATHS >javac [Link]
C:\MATHS>java mistake2 20 3 4
Answer =2
This means that x= 20,y= 3,z=[Link] there is no error so you get the required value of ans. Note
that the control for the above values will not enter the catch block.
Let us run the program one more time as follows:
C:\MATHS>java mistake2 20 3 3
Division by zero
Answer =0
As there is an exception in the first line of the try block because the denominator is zero so the
control will shift to the catch block without calculating the value of the variable ans. ans is shown
0 because of initialization.
Rahul Deshmukh Module-2: Basics of Java Programming 56
SYBSC-Skill Enhancement Course (SEC)-25-26

The above example shows that if exception occurs in any of the statement of the try block, the
control will switch to the catch block by ignoring all the statements ahead of the statement where the
exception has occurred. This problem can be solved using the keyword finally, which you will see later
on.
11.5 Multiple catch statements:
For one try block, it is possible to write more than one catch block. If the program generates
more than one exception then multiple catch statements are required. These catch statements are searched
by the exception thrown in order. The first matching catch clause is executed. Lastly, if the exception
doesn’t find a matching catch clause then it is passed to default handler. The general format is:

try
{
Block of statements where possible
exception has occured;
}
catch ( Exception_type1 object )
{ Block of statements to catch the
exception occurred in try block;
} catch ( Exception_type2 object )
{ Block of statements to catch the
exception occurred in try block;
}
catch ( Exception_type3 object )
{ Block of statements to catch the
exception occurred in try block;
}
You can have more catch blocks.

Example3: Consider the following program to find the value of the array expression, which is
assigned to the variable x.

class mistake3
{ public static void main(String args[])
{ int x[ ] = { 2 , 4 };
int y = 4;
try
{
int a = x[1]/x[2]-y;
}
catch(ArithmeticException e)
{
[Link]("Division by zero!");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Error!");
}
catch(ArrayStoreException e)
{
[Link]("Wrong data type!");
}
int b = x[1]/x[0];
[Link]("b
Rahul Deshmukh = "+b ); Module-2: Basics of Java Programming 57
}}
SYBSC-Skill Enhancement Course (SEC)-25-26

How the program works?


• try block contains the expression of which the denominator is zero i.e. the exception has occurred so
the control will go to the correct catch block where this exception can be handle and display the
corresponding message.
• The value of b will be calculated and display on the screen.
Let us execute and run the program as follows:
C:\MATHS>javac [Link]
C:\MATHS>java mistake3
Array Index Error!
b=2
11.6 The finally block:
If a try block contains set of statements and an exception has occurred in the first statement of this
block then all the remaining statements of the try block will be ignored.
Consider the following snippet of the program:

try
{
int x=y/z; /*Exception occurred */
int a=b*c ;
}
catch( ArithmeticException e)
{
/* process the exception */
}

Here the value of the variable a is to be calculated irrespective of whatever an exception is raised or not.
To find the value of a, you can write this statement out side the try and catch block [as done in the class
mistake2]. The problem is that this statement is not guarded so an exception may occur. To guard this
statement you can use the block called finally. This block can be used to handle any exception occurred
in the try block. The finally block may be added immediately after the try block or after the last catch
block. Thus, you can write finally block as shown below:

try catch( -----)


{ {
----------- -------------
---------- -------------
} OR
}
finally catch( -----)
{ {
------------ -------------
------------- -------------
} }
finally
{
-------------
-------------
}

Rahul Deshmukh Module-2: Basics of Java Programming 58


SYBSC-Skill Enhancement Course (SEC)-25-26
For the above example, you can write try and finally blocks as follows:

try
{
int x=y/z; /*Exception occurred */
}
finally
{
int a=b*c ;
[Link](“Value of a is :”+ a);
}

Thus whether x is zero or not you will definitely get the value of a.
Examples 4: Consider the following program:

class mistake4
{
public static void main( String args [ ])
{
String name;
float a,b;
try
{
name=new String( " Sushil Maths. " );
a=[Link](args[0]);
b=[Link](args[1]);
[Link]( name);
[Link]( "Division is "+a/b);
}

catch(ArithmeticException e)
{
[Link]( "Division by zero not possible!");
}
finally
{
name=null;
[Link]( "Finally Executed!");
}
}
}

In the above program, you can see that after executing the try/catch block the control shifts automatically
to the finally block irrespective of an exception.
Execute and run the above program as follows:
C:\MATHS>javac mistake4
C:\MATHS>java mistake4 2 3
Sushil Maths.
Division is 0.6666667
Finally Executed!
Rahul Deshmukh Module-2: Basics of Java Programming 59
SYBSC-Skill Enhancement Course (SEC)-25-26
As there is no exception so the control goes to finally block and get the above result.
Let us run the program again as follows:

C:\MATHS >java mistake4 2 0


Sushil Maths.
Division is Infinity
Finally Executed!
Here the exception has occurred so the control goes to all the three blocks.

Example5: Following program contains the use of try/catch/finally blocks using constructor:

class mistake5
{
String name;
int a,b;
mistake5(String args[ ])
{

try
{
name=new String( " Sushil Maths. " );
a=[Link](args[0]);
b=[Link](args[1]);
[Link]( name);
[Link]( "Division is "+a/b);
}

catch(ArithmeticException e)
{
[Link]( "Division by zero not possible!");
}
finally
{
name=null;
[Link]( "Finally Executed!");
}
}
public static void main( String args [ ])
{
new mistake4(args);

}
}

Execute and run the above program two times as follows:


C:\MATHS>javac [Link]
C:\MATHS>java mistake5 4 2
Sushil Maths.
Division is 2
Finally Executed!

Again run the program:


C:\MATHS >java mistake5 4 0
Sushil Maths.
Rahul Deshmukh Module-2: Basics of Java Programming 60
SYBSC-Skill Enhancement Course (SEC)-25-26
Division by zero not possible!
Finally Executed!

11.6 Throwing your own exception using keyword throw:


Programmer can throw his own type of exception using the keyword throw. The general format is:

throw new Throwable_subclass;

For example, In the previous programs ArithmeticException is used, which is the subclass of Throwable
[Link] you can write:

throw new ArithmeticException( );

To use your own exception one can write:

throw new MyException ( “ GOOD ONE !” );

And the catch block can be written as:

catch (MyException e )
{
---------
---------
}

Program
11.8 Use of throws:
Whenever a programmer does not want to handle exceptions using the try block then the throws
clause along with the main ( ) method can be used as follows:

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


{ }

The throws clause is responsible to handle the different types of exceptions generated by the
program. This clause contains list of various types of exceptions that are likely to occur in the program.
Consider the following example:

class mistake6
{
public static void main (String args[]) throws ArithmeticException
{
[Link]("Inside the main");
int i=0;
int j=12/i;
[Link]("This statement is not printed");
}
}
After executing and running the program you get:
C:\MATHS >javac [Link]
C:\MATHS>java mistake6
Rahul Deshmukh Module-2: Basics of Java Programming 61
SYBSC-Skill Enhancement Course (SEC)-25-26
Inside the main
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

Review Questions:
1. Define an exception.
2. Explain the use of try and catch clause.
3. How do you define a (i) try, (ii) catch block?
4. List some of the most common types of exception that occurs in Java. Give examples.
5. Is it necessary to catch all types of exceptions?
6. Is it possible to have more than one catch block with one try block?
7. What do you understand by a finally clause? What is the use of this clause? Give suitable example.
Try your self:
1. Create a try block that can generate two types of exception and then incorporate necessary catch
blocks to catch and handle them accordingly.
2. Define an exception called “No MatchException” that is thrown when a string is not equal to
“Pakistan”. Write a program that uses this exception.
3. Create a user-defined exception, which is to be generated whenever the user inputs the string “I am
fool”.
4. Write a program to illustrate the usage of (i) try and catch blocks,(ii) try, catch and finally blocks.

Rahul Deshmukh Module-2: Basics of Java Programming 62


SYBSC-Skill Enhancement Course (SEC)-25-26
3: APPLETS

Starter: You have learned so far Java programs of applications. These programs are executed using MS-
DOS or UNIX prompt. Now in this chapter, you will learn Java programs that run inside a WebPages.
These programs are called as Applets. You will also see the package called as [Link].* containing
Graphics class with different methods.

13.1 What is the Web?


The Word Wide Web is the brainchild of CERN (European Laboratory for Particle
Physics) engineer Tim Berners-Lee, who had the idea of creating an electronic Web of research
information. During the 1980s he developed a programming language called Hypertext Mark-up
Language (HTML), on which the Web is based. Early Web pages tended to be text-based, but since
the rapid expansion of the Web in 1994,they have become capable of holding rich graphical and
multimedia elements.
For majority of Internet users, the Word Wild Web (WWW or W3) is by far the most
exciting aspect of the Internet. It is certainly the fastest growing area, with estimated 20-30 millions
“WebPages” to visit, and with thousands appearing every month. The Web, as it is usually called, is the
universe of linked “pages”. A typical Web page contains words and pictures-often like a magazine page-
but with one major difference: the information is interactive. Navigating the Web is much like using a
multimedia CD-ROM. If you want to find out more information you point the mouse to a “Live” area of
the screen-usually a highlighted piece of text or an image-and click. This takes you to new screen. All
you need to access the WWW is a standard Internet connection and some “browser” software.

13.2 Web Browsers:


A few years ago, a Web browser was simply a tool for viewing the pages of the Web. Today’s
leading Web browsers have become much more than web Navigation tools: they have developed into all-
in-one Internet “launchpads” from which you can send e-mail, visit newsgroups, run Telnet sessions, and
access FTP and Gopher sites. Today’s sophisticated Web browsers are capable to run latest Web
applications using “helper” application or by “plug-ins”. Today’s leading Web browsers are: Netscape
Corporation’s Netscape Navigator and Microsoft’s Internet Explorer.

13.3 How do Web page works?


Each Web page is a “hyper text” document. Hypertext is not a piece of software: it is a term coined
by 1950’s computer visionary Ted Nelson. In practice, it means that a piece of text within one
document may have a pointer to other pieces of text, either within the same document.
Nearly all Web pages are created using Hypertext Mark-up Language (HTML)-one of the
simplest computer languages ever created. HTML is a set of instructions inserted into plain text by the
programmer.
To create an HTML document, text is sandwich between a series of commands, or “tags”. These
tags control the way in which the text is presented when views with Web browser. They are set up
between pairs of brackets and don’t appear when you view a Web page.
Most of the leading Web browsers allow you to view the HTML code “behind” the Web page. In
Netscape Navigator, for example, choose Document source from the View menu to see the HTML
coding for the page currently in your browser window.

13.3 What is an Applet?


Java enables Web pages to contain miniature programs called as Applets. Applets appear as
animation, sound, scrolling text, or interactive features such as functional spreadsheets. This
enhancement has revolutionized the way the Web is perceived both the developers and users. Your Web
browser needs to be Java-enhanced if you want to view Java applets.
In order to run an applets, you need to use the Internet browser or an applet viewer produced by Sun.

13.4 Use of [Link] package:


awt stands for abstract window toolkit. In this package there are 63 classes and 14 interfaces.
Components of these classes are used to write GUI programs. One of the important class that you are

Rahul Deshmukh Module-2: Basics of Java Programming 63


SYBSC-Skill Enhancement Course (SEC)-25-26
going to deal in this chapter is Graphics. This class is used to draw graphs or mathematical figures like
lines, rectangle, square, circle, Oval and text using different fonts.
13.4.1 How to insert text in an applet?

In an applet the line of text or string can be inserted using the method drawString ( ) of the class
Graphics of awt package. The syntax of this method is:

drawString ( String_msg, x cord ,y cord ) ;

For example,to place the line “ Applet is still not created” starting from (20,40) the following method
is used:

drawString ( “ Applet is still not created” “, 20, 40 );

13.4.2 Use of paint ( ) method:


This method is in the class Graphics. It is used to draw/ redrawing, creating a coloured background
or images onto the applets. It can be used by the following syntax:

public void paint ( Graphics object )


{
body ;
}
For example,

public void paint ( Graphics g )


{
g. drawString ( “ Applet is still not created” “, 20, 20 );
}
You will learn more about Graphics class later on.
13.5 Use of [Link] package:
In this package there is 1 class and 3 interfaces. This is the smallest package in Java. Applet
is the only class in this package with more than 20 methods used to display images, play audio file
and respond when you interact with it. This package has to be included in all the applets created by
you.
13.6 Simple Applet:
Let us write a simple applet to display the text line:
“ This is my first applet. “
Following are the steps to create this applet.
Step 1: Write a following source code using any of the word pad.

import [Link].*; //Package to run applet


import java .awt.*;
public class My_Applet extends Applet
{
String disp_str;
public void paint(Graphics g)
{
[Link]( “ This is my first applet.”,50,25);
}
}
Rahul Deshmukh Module-2: Basics of Java Programming 64
SYBSC-Skill Enhancement Course (SEC)-25-26
Here there is only one method paint ( ) of the class Graphics used of the package [Link]. Using this
method the required text line will be displayed from the point (50,25) in an applet Our_applet. To
inherit all the properties of the class Applet from the package [Link] it is necessary to used
extends key in all applets.
Save the above program by giving name:
My_applet.java
and compile it by passing command:
javac My_applet.java
using DOS-prompt.
Step 2: Now create HTML document as follows for the applet Our_applet.

<HTML>
This line <APPLET CODE ="My_applet.class"
tells the WIDTH=250 HEIGHT=250 > browser
that the file is a
</APPLET>
hypertext mark-
up document. </HTML>

This is the body of the HTML containing End of all


all the formatted tags. HTML body.

Save the above HTML file by giving name: [Link]


Step 3: Run the above HTML file by giving the following command.

C:\ Maths \ Applet>appletviewer [Link]

The output is as follows:

13.7 Life cycle of an applet:

The Java applets inherits behavior from the class

Applet. When an applet is loaded, it goes through certain changes in its state of an applet:
(1) The init ( ) state
(2) The start ( ) state
(3) The paint ( ) state
Let us study these states one after another.

Rahul Deshmukh Module-2: Basics of Java Programming 65


SYBSC-Skill Enhancement Course (SEC)-25-26
(1) The init ( ) state:
When an applet is created the init ( ) method is called. This method is used to initialize objects of an
applet. This method is called only once during the lifetime of an applet. This method is accessible to
every one so the method is declared as public.
Following programs demonstrates init ( ) method.
Program1: This program initialize two strings using init ( ) method and display it using paint ( )
method.

import [Link].* ;
import java .awt.* ;
public class Our_Applet extends Applet
{
String disp_str1,disp_str2;
public void init ( )
{
disp_str1="Smell of Java";
disp_str2="Author: Sushil Maths";
}
public void paint(Graphics g)
{
[Link](disp_str1,50,20);
[Link](disp_str2,50,50);
}
}

Save the above program by giving name:


Our_Applet.java
and compile it by passing command:
javac Our_Applet.java
using DOS-prompt. Open the file [Link] that you have already created. In this file replace the
applet Code as “Our_Applet.class” and run this file by giving the command:
C:\ Maths \ Apple>appletviewer [Link]
The output is as follows:

Rahul Deshmukh Module-2: Basics of Java Programming 66


SYBSC-Skill Enhancement Course (SEC)-25-26
Program2: Consider the program to display two names with the nationality as Indian. Change the
nationality as U.S.A. and display the third name with the nationality U.S.A. Also it should display
the second name with the nationality as U.S.A.

import java .awt.*;


import [Link].*;
class Person
{
static String nationality="Indian";
String name;
}
public class name_applet extends Applet
{
Person p1,p2;
public void init()
{
p1=new Person();
p2=new Person();
[Link]="Smita";
[Link]="Nidhi";
}
public void paint(Graphics g)
{
[Link](" Name of person: "+[Link],10,20);
[Link](" Nationality: "+[Link],10,40);
[Link]("Name of person: "+[Link],10,60);
[Link]("Nationality: "+[Link],10,80);
[Link]="U.S.A";
[Link]="Kathy";
[Link]("Name and Nationality of person is changed ",10,100);
[Link]("Name of person: "+[Link],10,120);
[Link]("Nationality: "+[Link],10,140);
[Link]("Name of person: "+[Link],10,160);
[Link]("Nationality: "+[Link],10,180);
}
}

Save the above program by giving name:


name_applet.java
and compile it by passing command:
javac name_applet java
using DOS-prompt.

Open the file [Link] that you have already created. In this file replace the applet Code as
“name_applet.class” and run this file by giving the command:
C:\ Maths \ Apple>appletviewer [Link]

The output is as follows:

Rahul Deshmukh Module-2: Basics of Java Programming 67


SYBSC-Skill Enhancement Course (SEC)-25-26

Now you learn remaining two states of an applet.


(2) The start ( ) state: The start ( ) method is called immediately after the init ( ) method. This
method is used to start the applet from a stop state.
(3) The paint ( ) state: You have already learn about this method.
Before going to the next program you will learn another method of the Graphics class called as
repaint ( ) method.
13.7.1 repaint ( ) method:
This method is used to repaint an applet. The repaint ( ) method calls the update ( ) method to
clear the screen of any existing content. The update ( ) method then calls paint ( ) method to draw the
content of the current frame. You can override the update method if you do not want the applet to be
cleared.
13.7.2 Two terminating methods:
When the applet is terminated the following methods are called in sequence:
(a) The stop ( ) method.
(b) The destroy ( ) method.
(a) The stop ( ) method: The stop ( ) method is used to halt the running of an applet.
(b) The destroy ( ) method : Whenever the browser on which the applet is running is to be closed or
when a new site is to be open in that browser or the applet is permanently removed from the memory
then the destroy ( ) method is used. This method removes all the resources used by the running
applet. Following program demonstrates the above methods:
import [Link].*;
import java .applet.*;
public class Applet_method extends Applet
{
int initcount=0;
int startcount=0;
int stopcount=0;
int destroycount=0;
public void init( )
{
initcount++;
repaint( );
}
public void start( )
{
startcount++;
repaint();
}
Rahul Deshmukh Module-2: Basics of Java Programming 68
SYBSC-Skill Enhancement Course (SEC)-25-26

//Cont..
public void stop( )
{
stopcount++;
repaint();
}
public void destroy( )
{
destroycount++;
repaint( );
}
public void paint (Graphics g)
{
[Link]("init has been invoked"+
[Link](initcount)
+ "times",20,20);
[Link]("start has been invoked"+
[Link](startcount)
+ "times",20,35);
[Link]("stop has been invoked"+
[Link](stopcount)
+ "times",20,50);
[Link]("destroy has been invoked"+
[Link](destroycount)+"times",20,65);
}}

Save the above program by giving the name Applet_Method.java under the directory Maths\Apple
Compile the program by the command:
javac Applet_Method.java
Create the HTML file and run that file by the command:
appletviewer [Link]
The output is as follows:

Rahul Deshmukh Module-2: Basics of Java Programming 69


SYBSC-Skill Enhancement Course (SEC)-25-26
13.8 How to passing parameters to the Applet?

In Java applications you have learn how to pass parameters. You can pass parameters to the
applets by the following two things:
❖ In an applet program init ( ) method contains a method called as getParameter ( ).This method is
used by the following signature:

variable1=getParameter (“variable2”);
Where variable1 is the string variable and variable2 is the string const., which is assigned to
NAME in the HTML file.variable1, can be taken as a string const.

For example,
(i) str= getParameter (“college” ); or
college= getParameter (“college” );
(ii) svar=getParameter (“marks”); or
marks=getParameter(“marks”);

Note that if the parameter is an integer, then it has to be converted into string and passed on as
parameter to the getParameter ( ) method.

❖ The special parameter tag <PARAM> is to be created in HTML file by the following format:

<PARAM NAME= string const. VALUE=” constant”>

For example,
(i) <PARAM NAME= College
VALUE=” Jai Hind”>
(ii) <PARAM NAME= marks
VALUE=” 72”>

Example:Following program illustrates the above method.

import [Link].*;
import [Link].*;
public class Passpara extends Applet
{
String strname="Mehir"; //initialization
public void init ( )
{
String name;
strname=getParameter ("strname");
if( strname==null)
strname = "No Name Entered.";
strname="What is your name?: "+strname;
}
public void paint (Graphics g)
{I
[Link]([Link]); //learn this method later.
[Link](strname,50,50);
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 70


SYBSC-Skill Enhancement Course (SEC)-25-26
How the program works?
In the above program getParameter ( ) method accepts the string variable strname as its
parameter. If value is not given to the variable strname then it will take default vale as “No value is
entered”. The paint ( ) method of the Applet class is overridden to execute the paint ( ) method of
your class. This method contains the drawString ( ) method apart from two more methods namely
setFont ( ) and setColor ( ).These methods are used to set the font type and color of the text. Above
program contains only setColor ( ) method. You will see these methods in detail later on.

Save the above program by giving the name


Passpara_Method.java
under the directory Maths \Apple
Compile the program by the command:
javac Passpara_Method.java

Create the HTML file by giving the name [Link]


as follows:
<html>
<applet CODE="[Link]"
WIDTH=400 HEIGHT=100>
<PARAM NAME=strname VALUE="Aishwarya">
</applet>
</ html>
Note the use of the tag <PARAM> in the above HTML file. If the value of the parameter is to be
changed then VALUE attribute of the <PARAM> tag is to be changed accordingly.
Run the program by giving the command:
C:\Maths\Apple>appletviewer [Link]

The output is as follows:

13.9 Font and Color classes of Graphics:

You know that the [Link] package contains the class called Graphics for drawing strings,
lines, rectangles and other shapes. This package also contains Font and color classes besides
Graphics class. In this article you will learn Font and color classes.

13.9.A (1) Font class:

Fonts are used to display the text in different forms Font class contains various methods. You
will deal with some of them.
This class contains wide variety of fonts like Times Roman, Courier, Helvetica, Palatino etc.
and some of the font styles available in this class are PLAIN, BOLD, ITALIC. These are integer
constants and so you can add them. For example, if you want the text to be printed BOLD as well as
ITALIC then you can write, [Link]+[Link].
Rahul Deshmukh Module-2: Basics of Java Programming 71
SYBSC-Skill Enhancement Course (SEC)-25-26
If the font is not specified then the system chooses Courier as the font for the text.
[A]To display the text using necessary font the following constructor is
used:

Font obj = new Font (“ name_font”, [Link], size );

Where obj is the instance of the class Font, name_font denotes the object of the family of fonts, style
may be PLAIN, BOLD or ITALIC and size is the font size.
For example,
(i)
Font f = new Font (“ Serif ”, [Link], 30);

means the text will be displayed with Serif font with style as BOLD and size 30.
(ii)
Font f = New Font(“ Impact ” ,[Link] + [Link],40);

means the text will be displayed with Serif font with style as BOLD as well as ITALIC and size 30.
[B]The method used to set the font is:

[Link] (obj2);
Where obj1 is the instance of the class Graphics and obj2 is the instance of the class Font.
For example,
[Link](f);

Where g is the instance of the class Graphics and f is the instance of the class Font.
Following example illustrates the above constructor and the method:
In this program, the text line “I am learning JAVA” is displayed from the point (50,50) on the
screen. This text line is displayed with the font dialog of bold type and point size 30.
import [Link].*;
import [Link].*;
public class Font_applet extends Applet {
Font f = new Font ("Dialog",Font .BOLD,30);
public void paint(Graphics g)
{
[Link](f);
String str="I am learning JAVA";
[Link](str,50,50);
}
}
Save the above program by giving the name
Font_applet.java
under the directory Maths \Apple
Compile the program by the command:
javac Font_applet.java
Create the HTML file by giving the name
no_appet1.html

as follows: <HTML>
<APPLET CODE="Font_applet.class"
WIDTH=400 HEIGHT=150>
</APPLET>
</ HTML>
Rahul Deshmukh Module-2: Basics of Java Programming 72
SYBSC-Skill Enhancement Course (SEC)-25-26
The output is as follows:

Let us write the program to display two text lines with two different constructors and two different
methods.
Note that the constructors are defined in paint ( ) method.

import [Link].*;
import [Link].*;
public class Font_applet1 extends Applet
{
public void paint(Graphics g)
{
Font f1 = new Font ("Serif",[Link]+Font. ITALIC,40);
[Link](f1);
String str1="I am learning JAVA";
[Link](str1,20,50);

Font f2 = new Font ("MS Outlook", [Link]+[Link], 40);


[Link](f2);
String str2="I am learning JAVA";
[Link](str2,20,90);
}
}

Save the above program by giving the name Font_applet1.java


under the directory Maths \Apple
Compile the program by the command:
javac Font_applet1.java
Create the HTML file by giving the name no_appet2.html
as
<APPLET CODE="Font_applet1.class" WIDTH=400 HEIGHT=150>
</APPLET>

and the output is as follows.

Rahul Deshmukh Module-2: Basics of Java Programming 73


SYBSC-Skill Enhancement Course (SEC)-25-26

13.9.A (2) How many different fonts are available?


It will definitely come in your mind that how many different fonts can be used in an applet?
The answer is given as follows:
[Link] package contains an abstract class called GraphicsEnvironment. This class contains
an important method called getAvailableFontFamilyNames ( )
Since the class GraphicsEnvironment is an abstract so you can’t instantiated this class. To
access
getAvailableFontFamilyNames ( ) method you have to access another method called as
getLocalGraphicsEnvironment ( ) of the class GraphicsEnvironment. getLocalGraphicsEnvironment
( ) method returns static reference hence if you issue the statement:
ge=[Link] ( )

then a reference to the class can be assigned to ge.


Thus with ge you can invoke the method getLocalGraphicsEnvironment ( ).
Following program illustrates this method:
import [Link].*;
import [Link].*;
public class Nfonts extends Applet
{
Font f = new Font("Serif",[Link],12);
Font f1 = new Font ("Arial",[Link],12);
public void paint (Graphics ge)
{
int i;
GraphicsEnvironment g =
[Link]();
String s[]=[Link] ( );
[Link](f);
[Link]("List of fonts available in the system” ,
20,20);
[Link](f1);
for(i=0;i<([Link]/2);i++)
[Link](s[i],20,(40+(15*i)));
int j=0;
for(i=(([Link]/2)+1);i<[Link];i++)
{
[Link](s[i],200,(40+(15*j)));
j++;
}
}
}

Rahul Deshmukh Module-2: Basics of Java Programming 74


SYBSC-Skill Enhancement Course (SEC)-25-26
Save the above program by giving the name
[Link]
under the directory Maths \Apple
Compile the program by the command:
javac [Link]
Create the HTML file by giving the name [Link]
as
<APPLET CODE="Font_applet.class"
WIDTH=400 HEIGHT=550>
</APPLET>

and the output is as follows:

13.9.(B) Color class:

You can set colour to the text in an applet using following syntax:

[Link](Color.<name_colour>);

Rahul Deshmukh Module-2: Basics of Java Programming 75


SYBSC-Skill Enhancement Course (SEC)-25-26
Where g is the instance of the class Graphics name_colour is the colour name that you wish
to give to the text.
For example,
[Link] ([Link] ); will display the given text in red colour.
The color class contains some predefined colours that are given below.

white black
orange gray
lightGray darkGray
red green
blue pink
cyan magenta
yellow

Following program illustrate the method setColor ( )

import [Link].*;
import [Link].*;
public class Font_applet2 extends Applet
{

public void paint(Graphics g){


Font f1 =
new Font ("Serif",[Link]+[Link],40);
[Link](f1);
[Link]([Link]);
String str1="I am learning JAVA.";
[Link](str1,20,50);

Font f2 =
new Font("MSOutlook",[Link]+[Link],40);
[Link](f2);
String str2="From Smell Of JAVA";
[Link]([Link]);
[Link](str2,20,90);

Font f3 =
new Font( “Garamond",[Link]+[Link],40);
[Link](f3);
[Link]([Link]);
String str3="Author: Sushil Maths.";
[Link](str3,20,140);
}
}

Save the file as Font_applet2.java under Maths\applet and compile it. Create the HTML file
as Font_applet2.html under Maths\applet as follows:

<APPLET CODE="Font_applet2.class" WIDTH=500


HEIGHT=200>
</APPLET>

Rahul Deshmukh Module-2: Basics of Java Programming 76


SYBSC-Skill Enhancement Course (SEC)-25-26
Execute the above HTML file using appletviewer. The output is as shown in the following figure.

13.9 How to draw Lines, Ovals, Rectangles,


Polygons?

Before going to different methods to draw lines, ovals, rectangles Polygons [Link] try to
understand co-ordinate system of Java.

13.9.1 Java’s co-ordinate system:

The upper left corner of the monitor screen is called as the origin of the Java’s co-ordinate
system and is denoted by O (0,0).[See [Link] below.)

O(0,0) +ve X axis

(x ,y )

+ve Y axis

In this system, x coordinate is the distance moving right from the origin and y coordinate is
the distance moving down from the origin. The point (x,y) is a +ve ordered pair where both x and y
are + ve integers. Any shape or diagram can be drawn on a screen by specifying an ordered pair.

13.9.2 How to draw Lines?

A line can be drawn using Graphics class of [Link] package by the following method:

drawLine ( int x1 , int y1, int x2 , int y2 );

Rahul Deshmukh Module-2: Basics of Java Programming 77


SYBSC-Skill Enhancement Course (SEC)-25-26
Where the line begins with the point (x1, y1) and ends with (x2, y2). You can draw colorful lines by
setting the colour using Color class

(x1,y1)

(x2,y2)

Following program illustrates the method drawLine ( ).


import [Link].*;
import [Link].*;
public class Drawline extends Applet {
public void paint(Graphics g) {
[Link]([Link]);
[Link](70,70,120,70);
[Link]([Link]);
[Link](95,45,95,95);
[Link]([Link]);
[Link](82,50,112,95);
[Link]([Link]);
[Link](107,50,82,90);
}
}

Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE=" Drawline. class" WIDTH=200


HEIGHT=100>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following figure.

Rahul Deshmukh Module-2: Basics of Java Programming 78


SYBSC-Skill Enhancement Course (SEC)-25-26

13.9.2 How to draw Ovals?

An Oval can be drawn using Graphics class of the [Link] package as follows:
drawOval ( int x , int y, int width, int height);

Here there are 4 parameters to draw an Oval. An oval starts with the co-ordinates (x, y) and width,
height are the width and height of an oval. The oval can be coloured by setColor ( ) method.
Oval can be filled by the colour using the method with the same 4 parameters as above. The method
can be written as:
fillOval ( int x , int y, int width, int height);

For example,
1. drawOval (100,200,70,40);means the an oval starts from the point (100,200) with width 70 and
height 40.
2. fillOval (200,200,70,90);means the an oval starts from the point (200,200) with width 70 and
height 90.
If you wish to draw a circle or filled circle then you have to take width equal to height.
Following program illustrates these methods.

import [Link].*;
import [Link].*;
public class Drawoval extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,80,50);
[Link]([Link]);
[Link](150,50,50,100);
[Link]([Link]);
[Link](50,50,80,80);
[Link]([Link]);
[Link](150,170,50,50);
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE=" Drawoval. class" WIDTH=250


HEIGHT=250>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

Rahul Deshmukh Module-2: Basics of Java Programming 79


SYBSC-Skill Enhancement Course (SEC)-25-26

13.9.3 How to draw Rectangles?

A rectangle can be drawn using Graphics class of the [Link] package as follows:
drawRect ( int x , int y, int width, int height);

Here there are 4 parameters to draw a rectangle. A rectangle starts with the co-ordinates (x, y) and
width, height are the width and height of a rectangle The rectangle can be coloured by setColor ( )
method.
A rectangle can be filled by the colour using the method with the same 4 parameters as above. The
method can be written as:

fillRect ( int x , int y, int width, int height);

For example,
1. drawRect (50,100,70,40);means a rectangle starts from the point (50,100) with width 70 and height
40.
2. fillRect (100,200,70,90);means a rectangle starts from the point (100,200) with width 70 and height
90.
If you wish to draw a square or filled a square then you have to take width equal to
height.
You can also draw round rectangle and fill it by the following methods:

drawRoundRect ( int x, int y, int width, int height,


int arcwidth, int archeight);
fillRoundRect ( int x, int y, int width, int height,
int arcwidth, int archeight);

Here, method got 6 parameters, of which the first 4 parameters are the same as the
drawRect ( ) method. The addition two are:
1. arcwidth: This is used to round off the leftmost and rightmost corners of the rectangle.
2. archeight: This is used to round off the topmost and bottommost corners of the rectangle.
Following program illustrates these methods.

Rahul Deshmukh Module-2: Basics of Java Programming 80


SYBSC-Skill Enhancement Course (SEC)-25-26

import [Link].*;
import [Link].*;
public class Drawrect extends Applet{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,60,90);
[Link]([Link]);
[Link](150,50,50,100,20,40);
[Link]([Link]);
[Link](50,150,70,70);
[Link]([Link]);
[Link](150,170,70,50,30,40);
}
}

Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE=" Drawrect. class" WIDTH=250


HEIGHT=250>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

13.9.4 Applications:

In this article you will see the applications of all the methods seen above.

Example1: (Creating a hut) let us write a program to create a small hut. The code is given below:

Rahul Deshmukh Module-2: Basics of Java Programming 81


SYBSC-Skill Enhancement Course (SEC)-25-26

import [Link].*;
public class hut extends [Link]{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](200,20,60,130);
[Link]([Link]);
[Link](100,100,300,100);
[Link]([Link]);
[Link](340,130,200,20);
[Link]([Link]);
[Link](100,100,200,200);
[Link]([Link]);
[Link](160,200,80,100);
[Link]([Link]);
[Link](80,300,240,50);
}
}

Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE=" hut. class" WIDTH=400


HEIGHT=400>
</APPLET>
Execute the above HTML file using appletviewer. The output is as shown in the following figure.

Rahul Deshmukh Module-2: Basics of Java Programming 82


SYBSC-Skill Enhancement Course (SEC)-25-26
Example 2: (A MAN standing on the TABLE)
Let us develop the code to show the man standing on the table. This code is fully self-
explanatory.

import [Link].*;
import [Link].*;
public class Man extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](150,50,100,100); //Face
[Link](200,150,200,300); //body
[Link](200,200,125,275);//left hand
[Link](200,200,275,275);//right hand
[Link](200,300,125,375);//left leg
[Link](200,300,275,375);//right leg
[Link]([Link]); //colour of eyes
[Link](210,70,20,20);//left eye
[Link](170,70,20,20);//right eye
[Link]([Link]);
[Link](200,90,200,110);//nose
[Link](200,110,195,106);//nose
[Link]([Link]);
[Link](180,120,35,10);//mouth
[Link]([Link]);
[Link](80,340,250,75);/*table top */
[Link](120,408,10,50); /* left leg of table */
[Link](260,412,10,50); /* right leg of table */
}
}

Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE="man. class" WIDTH=350


HEIGHT=500>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

Rahul Deshmukh Module-2: Basics of Java Programming 83


SYBSC-Skill Enhancement Course (SEC)-25-26

Example 3: (Hello World problem)


Following program display the text “Hello World” using graphics techniques.
import [Link].*;
import [Link].*;
public class Hello extends Applet
{
static final String message="Hello Word";
private Font font;
//One time initialization for the applet
//Note:No constructor defined.
public void init()
{
font = new Font("Helvetica",[Link],48);
}

Rahul Deshmukh Module-2: Basics of Java Programming 84


SYBSC-Skill Enhancement Course (SEC)-25-26

public void paint( Graphics g)


{
[Link]([Link]); //The pink oval
[Link]([Link]);
[Link](10,10,330,100);
//The red [Link] doesnot support wide lines,
//so try to simulate a 4-pixel wide line by drawing four Ovals.
[Link]([Link]);
[Link](10,10,330,100);
[Link](9,9,332,102);
[Link](8,8,334,104);
[Link](7,7,336,106);
//The text
[Link]([Link]);
S [Link](font);
[Link](message,40,75);
}
}

save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE="Hello. class" WIDTH=400


HEIGHT=160>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

13.10 Can you use Control Loops in Applets?

The answer of the above question is “ YES “. Following code shows by drawing 5-circles
using for loop. Here 5 circle are touching each other externally.

Rahul Deshmukh Module-2: Basics of Java Programming 85


SYBSC-Skill Enhancement Course (SEC)-25-26

import [Link].*;
import [Link].*;
public class Circle5 extends Applet {
public void paint(Graphics g)
{
for(int i=0;i<=4;i++)
{
// If circle is at even position colour it red else blue.
if((i%2)==0)
{
[Link]([Link]);
[Link](130,i*50+20,50,50);
}
else
{
[Link]([Link]);
[Link](130,i*50+20,50,50);
}
}
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:

<APPLET CODE="Circle5. class" WIDTH=300


HEIGHT=300>
</APPLET>

Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

Rahul Deshmukh Module-2: Basics of Java Programming 86


SYBSC-Skill Enhancement Course (SEC)-25-26
13.11 How to draw an Arc?

To draw an arc, Graphics class contains a method called as drawArc ( ) .This method works
similar to the method drawOval ( ).In this case, the arc is taken as an Oval and hen draw only a
part of it as dictated by the last two parameters of the
drawArc ( ) method. The first four parameters are the same as drawOval ( ) [Link] is
given as:

drawArc( int x , int y, int width, int height ,int ang1,ang2);


An arc starts with the co-ordinates (x, y) and width, height are the width and height of an arc.
Also
ang1 is the beginning angle and ang2 is the angular extent of the arc, relatives to the beginning angle i.e.
[Link] is called as swap angle.
The idea of defining ang1 and ang2 is similar to define angles in Unit circle. The three O’clock
position is taken as zero degree of an angle. An angle increases in terms of degrees in anti-clockwise
direction as shown in fig.
90

445

180 0

270
For example, to draw an arc from an angle 45 degrees to 180 degrees then starting angle would
be 45 and the swap would be 135 [since (45 to 90 it is 45) +(90 to 180 it is 90)]. The method can be
given as

drawArc(80,120,60,45,135);

You can also used fillArc ( ) method to fill the arc.

Following program uses this method to draw the face of a man and Save the file as [Link]
under Maths\applet and compile it. Create the HTML file as [Link] under Maths\applet as follows:

<APPLET CODE="Face. class" WIDTH=250


HEIGHT=250>
</APPLET>

Rahul Deshmukh Module-2: Basics of Java Programming 87


SYBSC-Skill Enhancement Course (SEC)-25-26

import java .awt.*;


import [Link].*;
public class Face extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,130,160); /* Head */
[Link]([Link]);
[Link](67,85,40,30); /* Left eye */
[Link](120,85,40,30);/* Right eye */
[Link]([Link]);
[Link](78,91,20,20); /* Left Pupil */
[Link](131,91,20,20);/* Right Pupil */
[Link]([Link]);
[Link](95,115,40,40);/* Nose */
[Link]([Link]);
[Link](70,140,80,40,180,180);/* Mouth */
[Link]([Link]);
[Link](25,102,25,40); /* Left Ear */
[Link](180,102,25,40);/* Right Ear */
}
}
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.

Rahul Deshmukh Module-2: Basics of Java Programming 88


SYBSC-Skill Enhancement Course (SEC)-25-26
Review Questions:

[1] What is an applet? How do applets differ from application programs?


[2] Discuss the steps involved to execute and run the applet.
[3] Describes the various states involved in the life cycle of an applet.
[4] Why all the classes used in applets is defined as public?
[5] What is the use of <PARAM> tag? How many parameters used in this tag?
[6] Describe the Java coordinate system.
[7] Explain with example the methods used to draw
(i)Line (ii) Oval (iii) Circle (iv) Rectangle
(v) Square (vi) arc.

Try your self:


[1] Create an applet to display the following text:
What are you reading?
I am reading “Smell of JAVA”
[2] Create an applet to accept an integer as a parameter and display a message as “ Are you __ years
old?” The age should be displayed in the blank space. The default should be 45.
[3] Create an applet to display a string “I am at the Center” in MSOutlook, with size 40 and style bold
and italic. The text should be centered both horizontally and vertically.
[4] Write applets to draw the following shapes:
(i) Cone (ii) Cylinder (iii) cube
(iv) Square inside a circle
(v) Circle inside a square.
[5] Write an applet to display 9 circles (3 in each row)
(i)Give different colours to first row and second row.
(ii)Give different colours to even position circles and odd position circles.
[6] Write an applet by improving the FACE applet of a man.

Rahul Deshmukh Module-2: Basics of Java Programming 89

You might also like