0% found this document useful (0 votes)
2 views46 pages

Java Unit-2

The document outlines control structures in programming, specifically focusing on selection statements (if and switch), iteration statements (for, while, and do-while loops), and jump statements (break and continue). It provides syntax and examples for each type of control structure, demonstrating their usage in Java programming. Additionally, it includes sample programs to illustrate concepts such as checking number properties and calculating factorials.

Uploaded by

bkcda432
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)
2 views46 pages

Java Unit-2

The document outlines control structures in programming, specifically focusing on selection statements (if and switch), iteration statements (for, while, and do-while loops), and jump statements (break and continue). It provides syntax and examples for each type of control structure, demonstrating their usage in Java programming. Additionally, it includes sample programs to illustrate concepts such as checking number properties and calculating factorials.

Uploaded by

bkcda432
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

BSC-II Semester-IV

[Link]. II Semester IV
Paper - I
UNIT – 2
1 Control Structure:

There are three types of control structures.


• Selection statement
• Iteration statement
• Jumps in statement

2.1 Selection Statement:


Selection statement is also called as Decision making statements. It controls the flow of a program
with their conditions.
There are two types:
• if statement
• switch statement

2.1.1 if Statement:
The “if statement” is also called as conditional branch statement.

Syntax:
if (condition)
{
Statement 1; Statement 2;
...
}
else
{
Statement 3;
Statement 4;
... }

2.1.2 Simple if statement:

Syntax:
If (condition)
{
Statement block;
}

Statement-a;

If the condition is true then statement block will be executed. If the condition is false then statement
block will omit and statement-a will be executed.

2.1.3 The if…else statement:


Syntax:
If (condition)
{
Statement Block-A
}
else
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
Statement block-B;
}
Statement-a;
If the condition is true then Statement Block-A will be executed. If the condition is false then Statement
Block-B will be executed. In both cases the statement-a will always executed.

Program: write a program to check whether the number is positive or negative.

import [Link].*;
class NumTest
{
public static void main (String[] args) throws IOException
{
int Result=11;
[Link]("Number is"+Result);
if ( Result < 0 )
{
[Link]("The number "+ Result +" is negative");
}
else
{
[Link]("The number "+ Result +" is positive");
}
}
}

For example: write a program to check whether the number is divisible by 2 or not.
import [Link].*;
class divisorDemo
{
public static void main(String[] args)
{
int a =11;
if(a%2==0)
{
[Link](a +" is divisible by 2");
}
else
{
[Link](a+" is not divisible by 2");
}

}
}
Output:

1.1.4 Nesting of if-else statement:


Syntax:
if (condition1)
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
If(condition2)
{
Statement block-A;
}
else
{
Statement block-B;
}
}
else
{
Statement block-C;
}
Statement- a;

If the condition1 is true then it will be goes for condition2. If the condition2 is true then statement block-
A will be executed otherwise statement block-B will be executed. If the condition1 is false then
statement block-C will be executed. In both cases the statement-a will always executed.
// Nested IF For example:Write a program to find out greatest number from three numbers.

// Program to find largest using nested IF


import [Link].*;
class largest
{
public static void main(String args[]) throws IOException
{
int a,b,c;
[Link]("Enter A? ");
InputStreamReader reader = new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text= [Link]();
a= [Link](text);
[Link]("Enter B ? ");
text= [Link]();
b= [Link](text);

[Link]("Enter C ? ");
text= [Link]();
c= [Link](text);
if (a>b)
{
if (a>c)

[Link]("a is gratest");

else

[Link]("c is gratest");
}
else
{
if (b>c)
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]("b is gratest");
else
[Link]("c is gratest");
}
}
}

// Program using nested IF


import [Link].*;
class eleunit
{
public static void main(String args[]) throws IOException
{
int units, custnum ;
double charges=0;
String text;
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter Customer No. ?");
text=[Link]();
custnum=[Link](text);
[Link]("Enter Units Consumed ?");
text=[Link]();
units=[Link](text);
if (units<=200)
charges=0.5*units;
else if (units<=400)
charges=100+0.65*(units-200);
else if(units<=600)
charges=230+0.8*(units-600);
[Link]("Customer No. "+custnum+" Charges = "+charges);
}

2.1.5 switch statement:


Switch statement check the value of given variable against a list of case values and when the match is
found, a statement-block of that case is executed. Switch statement is also called as multiway decision
statement.
Syntax:
switch(condition)
{
case value-1:
statement block1;
break;
case value-2:
statement block2;
break;
case value-3:
statement block3;
break;

Shivaji Science College, Nagpur
BSC-II Semester-IV

default:
statement block-default;
break;
}
statement a;

The condition is byte, short, character or an integer. value-1,value-2,value-3,…are constant and is called
as labels. Each of these values be compared with condition. Statement block1, Statement block2,
Statement block3,..are list of statements which contain one statement or more than one statements. Case
label is always end with “:” (colon).

Program:write a program for bank account to perform following operations.

-Check balance
-withdraw amount
-deposit amount
For example:
//program to demonstrate switch statment
import [Link].*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=[Link](args[0]);
[Link]("Menu");
[Link]("1:check balance");
[Link]("2:withdraw amount... plz enter choice and amount");
[Link]("3:deposit amount... plz enter choice and amount");
[Link]("4:exit");
switch(ch)
{
case 1:[Link]("Balance is:"+bal);
break;
case 2:int w=[Link](args[1]);
if(w>bal)
{
[Link]("Not sufficient balance");
}
bal=bal-w;
[Link]("Balance is"+bal);
break;
case 3:int d=[Link](args[1]);
bal=bal+d;
[Link]("Balance is"+bal);
break;
default:break;
}
}
}

Shivaji Science College, Nagpur


BSC-II Semester-IV

//program to find roots of quadratic equations to demonstrate switch statment


import [Link].*;
import [Link].*;
class quadratic
{
public static void main(String args[]) throws IOException
{
int a,b,c,i;
double d,r1,r2;
[Link]("Quadratic Equation :");
[Link]("a*x^2 + b*x + c ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter Coefficient a ?");


String ainput=[Link]();
a=[Link](ainput);
[Link]("Enter Coefficient b ?");
String binput=[Link]();
b=[Link](binput);
[Link]("Enter Coefficient c ?");
String cinput=[Link]();
c=[Link](cinput);
if (a==0)
{
[Link]("Equation is linear ");
[Link]("Root is "+ (-c/(float)b));
}
else
{
d=b*b-4*a*c;
if (d==0)
i=1;
else if (d>0)
i=2;
else
i=3;
switch(i)
{
case 1:
[Link]("Roots are Real and Equal");
r1=r2=(-b/(float)2*a);
[Link]("Root1 = "+r1+" Root2 = "+r2);
break;
case 2:
[Link]("Roots are Real and UnEqual");
r1=-b+([Link](d)/(float)2*a);
r2=-b-([Link](d)/(float)2*a);

[Link]("Root1 = "+r1+" Root2 = "+r2);


break;
case 3:
[Link]("Roots are Imaginary");

Shivaji Science College, Nagpur


BSC-II Semester-IV

/*d=-d;
r1=-b+[Link](d)/(float)2*a;
r2=-[Link](d)/(float)2*a;
[Link]("Root1 = "+r1+" Root2 = "+r2);*/
break;

}
}
}

2.2 Iteration Statement:


The process of repeatedly executing a statements is called as looping. If a loop executing continuous
then it is called as Infinite loop. Looping is also called as iterations.
There are three types of loops :
• for loop
• while loop
• do-while loop

2.2.1 for loop:


The for loop is entry controlled loop.
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}
When the loop is starts, first part(i.e. initialization) is execute. It is just like a counter and provides the
initial value of [Link] next part( i.e. condition) is executed after the initialization. It provides the
condition for looping. If the condition true then loop will execute otherwise it will terminate.
Third part(i.e. iteration) is executed after the condition. The statements that incremented or decremented
the loop control variables.
For example:
import [Link].*;
class number
{
public static void main(String args[]) throws Exception
{
int i;
[Link]("list of 1 to 10 numbers");
for(i=1;i<=10;i++)
{
[Link](i);
}
}
}

// Program to find factorial using for loop


import [Link].*;
class factorial
{
public static void main(String args[]) throws IOException
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
InputStreamReader reader = new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
int n, fact=1;
[Link]("Enter the number? ");

String text= [Link]();


n= [Link](text);
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
[Link]("The factorial is " + fact);
}
}

import [Link].*;
class series1
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=0;
[Link]("Summation of the Sequence :");
[Link](" 1 - 1/2 + 1/3 - 1/4...... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter number of terms required ?");
String minput=[Link]();
n=[Link](minput);
j=1;
for(i=1;i<=n;i++)
{
sum=sum+j*(1.0/(float)i);

j=-j;
}
[Link]("Sum of sequence upto "+n+"terms is "+sum);
}
}

import [Link].*;
class series2
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=0;
[Link]("Summation of the Sequence :");
[Link](" 2/9 - 5/13 + 8/17 - 11/21...... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));

Shivaji Science College, Nagpur


BSC-II Semester-IV

[Link]("Enter number of terms required ?");


String minput=[Link]();
n=[Link](minput);
j=1;
for(i=1;i<=n;i++)
{
sum=sum+j*((3*i-1)/(float)(4*i+5));

j=-j;
}
[Link]("Sum of sequence upto "+n+"terms is "+sum);
}
}

import [Link].*;
class series3
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=1;
[Link]("Summation of the Sequence :");
[Link]("1 + 1/1! + 1/2! + 1/3! + ..... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter number of terms required ?");


String minput=[Link]();
n=[Link](minput);
j=1;
for(i=1;i<=n;i++)
{
j=j*i;
sum=sum+ 1.0/(float)(j);
}
[Link]("Sum of sequence upto "+n+"terms is "+sum);
}
}

2.2.2 while loop:


The while loop is entry controlled loop statement. The condition is evaluated. If the condition is true then
the block of statements is executed.
Syntax:
While(condition)
{
Statement block;

For example:Write a program to display 1 to 10 numbers using while loop.


import [Link].*;
class number
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

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


{
int i=1;
[Link]("list of 1 to 10 numbers");
while(i<=10)
{
[Link](i);
i++;
}
}
}

// Program to find sum of digits and reverse of digits using while loop
import [Link].*;
import [Link].*;
class sumofdigit
{
public static void main(String args[]) throws IOException
{
int num, rev=0,digit,sum=0,temp;
[Link]("sum of digit :");
[Link]("e.g. 1234=10");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter Number ?");
String ainput=[Link]();
num=[Link](ainput);
temp=num;
while (num!=0)
{
digit= num-(num/10)*10;
sum=sum+digit;
rev=rev*10+digit;
num=num/10;
}
[Link]("Inputted number is "+ temp);
[Link]("Sum of digit is "+sum);

[Link]("Reverse of" + temp+" is "+ rev);


}
}

2.2.3 do-while loop:


In do-while loop, first attempt of loop should be execute then it check the condition.

Syntax:
do
{
Statement block;
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

While(condition);

In program,when we use the do-while loop, then in very first attempt, it allows us to get enter in loop and
execute that loop and then check the condition.

For example:Write a program to display 1 to 10 numbers using do-while loop.


import [Link].*;
class number
{ public static void main(String args[]) throws Exception
{
int i=1;
[Link]("list of 1 to 10 numbers");
do
{
[Link](i);
i++;
}while(i<=10);
}
}

2.3 Jumps in statement:

Loops perform a set of operations continually until the control variable will not satisfy the condition. But
if we want to break the loop, then Java provides command to jump from one statement to end of loop or
beginning of loop as well as jump out of a loop.
“break” keyword use for exiting from loop and “continue” keyword use for continuing the loop.

Following statements shows the exiting from loop by using “break” statement.
do-while loop:
do
{
………………
………………
if(condition)
{
break;//exit from if loop and do-while loop
}
……………..
……………..
}
While(condition);

Following statements shows the continuing the loop by using “continue” statement.
do-while loop:
do
{
………………
………………
if(condition)
{continue;//continue the do-while loop

}
Shivaji Science College, Nagpur
BSC-II Semester-IV

……………..
……………..
}
While(condition);

2.4 Labelled loop:


We can give label to a block of statements with any valid name.
For example:
// program to demonstrate use of label, break and continue statement
import [Link].*;
class DemoLabel
{
public static void main(String args[]) throws Exception
{
int j,i;
LOOP1:
for(i=1;i<100;i++)
{
[Link]("");
if(i>=10)
{
break;
}
for(j=1;j<100;j++)
{
[Link]("$ ");
if(i==j)
{
continue LOOP1;
}
}
}
[Link](" End of program ");
}
}

Output:
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
End of program

2.5 Classes
A class is a set of objects with similar properties (attributes), common behavior (operations), and common
link to other objects. The objects are variable of type class. A class is a collection of objects of similar type.
Classes are user defined data . Once the class has been defined, we can make any number of objects
Shivaji Science College, Nagpur
BSC-II Semester-IV

belonging to that class. Each object is related with the data of type class with which they are formed. As we
learned that, the classification of objects into various classes is based on its properties (States) and behavior
(methods).
Objects are instances of the Class. Classes and Objects are very much related to each other. Without objects
you can't use a class.

Class Declaration
class classname
{
// variable declaration
dataType1 fieldName1;
dataType2 fieldName2;
.
returnDataType1 methodName1(arguments)
{
//body of method…
}

returnDataType2 methodName2(arguments)
{
//body of method…
}
.
}

2.5.1 Fields Declaration :

Class Rectangle
{
int length;
int breadth;
}

The class Rectangle contains two integer type instance variables.

2.5.2 Methods Declaration :Methods are declared inside the class immediately after the instance variable
declaration. It describes the operations to be performed on data.

returnDataType1 methodName1(arguments)
{
//body of method…
}

Example :
Class Rectangle
{
int length, breadth;
void getData(int x, int y) //method declaration
{
length=x;
breadth=y;
}
Shivaji Science College, Nagpur
BSC-II Semester-IV

2.5.3 Creating Objects:


The new operator creates an object of class and returns reference to that object.

Example :
Rectangle rect1; // declare the object
rect1 = new Rectangle(); // create object
OR
Rectangle rect1 = new Rectangle();

The method Rectangle() is the default constructor of class

2.5.4 Accessing class members using dot operator

We can access the variables by using dot operator.


[Link] = value;
[Link] (parameters);

Now following example shows the use of method.


class DemoAddMethod
{
private int a,b,c;
public void read()
{
a=20;
b=25;
}
public void add()
{
c=a+b;
}
public void show_data()
{
[Link]("C =" +c);
}
public static void main(String args[])
{
DemoAddMethod obj1=new DemoAddMethod ();
[Link]();
[Link]();
obj1.show_data();
}
}

In program,
DemoAddMethod obj1=new DemoAddMethod ();
[Link]();
[Link]();
obj1.show_data();
In the first line we created an object.
Shivaji Science College, Nagpur
BSC-II Semester-IV

The three methods are called by using the dot operator. When we call a method the code
inside its block is executed.
The dot operator is used to call methods or access them.

2.5.5 Creating “main” in a separate class


We can create the main method in a separate class, but during compilation you compile the class with the
“main” method.
class DemoAddMainMethod
{
private int a,b,c;
public void read()
{
a=20;
b=25;
}
public void add()
{
c=a+b;
}
public void show_data()
{
[Link]("C =" +c);
}
}
class DemoAddMainMethod1
{
public static void main(String args[])
{
DemoAddMainMethod obj1=new DemoAddMainMethod ();
[Link]();
[Link]();
obj1.show_data();
}
}
Following program shows the use of dot operator.
class DemoAddDotOperator
{
int a,b,c;

public void add()


{
c=a+b;
}
public void show_data()
{
[Link]("C =" +c);
}
}
class DemoAddDotOperator1
{
public static void main(String args[])
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

DemoAddDotOperator obj1=new DemoAddDotOperator ();


DemoAddDotOperator obj2=new DemoAddDotOperator ();
obj1.a=10;
obj1.b=15;
obj2.a=5;
obj2.b=10
[Link]();
[Link]();
obj1.show_data();
obj2.show_data();
}
}

2.5.6 Methods with parameters

Following program shows the method with passing parameter.

class DemoAddMethodParameter
{
private int a,b,c;
public void read(int x, int y)
{
a=x;
b=y;
}
public void add()
{
c=a+b;
}
public void show_data()
{
[Link]("C =" +c);
}
}

class DemoAddMethodParameter1
{
public static void main(String args[])
{
DemoAddMethodParameter obj1=new DemoAddMethodParameter ();
[Link](30,35);
[Link]();
obj1.show_data();
}
}

2.5.7 Methods with a Return Type

Following program shows the method with their return type.


class DemoAddMethodReturn
{
private int a,b;
Shivaji Science College, Nagpur
BSC-II Semester-IV

public void read(int x, int y)


{
a=x;
b=y;
}
public int add()
{
return(a+b);
}
}

class DemoAddMethodReturn1
{
public static void main(String args[])
{
int c;
DemoAddMethodReturn obj1=new DemoAddMethodReturn ();
[Link](30,35);
c=[Link]();
[Link]("C =" +c);
}
}
2.5.8 Method Overloading

Method overloading means method name will be same but each method have different parameter lists and
different definations

Following program shows the method overloading

class DemoAddMethodOverloading
{
int a=10,b=35,c;

public void add()


{
c=a+b;
[Link]("C =" +c);

}
public void add(int x, int y)
{
a=x;
b=y;
c=a+b;
[Link]("C =" +c);
}

public int add(int x)


{a=x;
return(a+b);
}

Shivaji Science College, Nagpur


BSC-II Semester-IV

class DemoAddMethodOverloading1
{
public static void main(String args[])
{int k;
DemoAddMethodOverloading obj1=new DemoAddMethodOverloading ();
[Link]();
[Link](24,25);
[Link]("Sum =" +[Link](45));
}
}
2.5.9 Passing Objects as Parameters

Objects can even be passed as parameters.

class DemoAddMethodPassingObject
{
private int a,b,c,m;
public void read1(int x, int y)
{
a=x;
b=y;
}
public void add()
{
c=a+b;
[Link]("Sum =" +c);
}

public void read2(DemoAddMethodPassingObject k )


{
a=k.a;
b=k.b;
}

public void mult()


{
m=a*b;
[Link]("Munltiplication =" +m);
}

class DemoAddMethodPassingObject1
{
public static void main(String args[])
{
DemoAddMethodPassingObject obj1=new DemoAddMethodPassingObject();
DemoAddMethodPassingObject obj2=new DemoAddMethodPassingObject();
obj1.read1(30,35);
Shivaji Science College, Nagpur
BSC-II Semester-IV

[Link]();
obj2.read2(obj1);
[Link]();
}
}

2.5.10 Constructor in Java


Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values.
Constructor name must be same as its class name. Constructor does not have return type

[Link] Java Default Constructor


Construructor that have no parameter is known as default constructor.
Syntax :
<class_name>()
{

Example :
we are creating the no argument constructor in the Bike class. It will be invoked at the time of object
creation.
class Bike1
{
Bike1()
{
[Link]("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}

[Link] Java parameterized constructor :


Parameterized constructor is used to provide different values to the distinct objects.
Example :
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{[Link](id+" "+name);
}
public static void main(String args[])
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

Student4 s1 = new Student4(100,"Sunil");


Student4 s2 = new Student4(200,"Anil");
[Link]();
[Link]();
}
}

[Link] Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type.
Example :
class Student5{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}

Student5(int i,String n,int a)


{
id = i;
name = n;
age=a;
}

void display()
{
[Link](id+" "+name+" "+age);
}

public static void main(String args[]){


Student5 s1 = new Student5(100,"Raran");
Student5 s2 = new Student5(200,"Kishore",25);
[Link]();
[Link]();
}
}

Difference between constructor and method in java :

Java Constructor Java Method


1. Constructor is used to initialize the Method is used to expose behavior of an
state of an object object.
2 Constructor must not have return Method must have return type.
type.
3 Constructor is invoked implicitly. Method is invoked explicitly.
4 The java compiler provides a default Method is not provided by compiler in

Shivaji Science College, Nagpur


BSC-II Semester-IV

constructor if you don't have any any case.


constructor.
5 Constructor name must be same as Method name may or may not be same
the class name. as class name.

[Link] Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}

Student6(Student6 s)
{
id = [Link];
name =[Link];
}
void display()
{[Link](id+" "+name);
}

public static void main(String args[])


{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
}
}

[Link] Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another object. In this
case, there is no need to create the constructor.
class Student7
{
int id;
String name;
Student7(int i,String n)
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

id = i;
name = n;
}
Student7()
{
}
void display()
{
[Link](id+" "+name);
}

public static void main(String args[])


{
Student7 s1 = new Student7(150,"Kiran");
Student7 s2 = new Student7();
[Link]=[Link];
[Link]=[Link];
[Link]();
[Link]();
}
}

[Link] Java static keyword :


The static keyword is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the
class.
The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.
• The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees, college name of students etc.
• The static variable gets memory only once in class area at the time of class loading.

//Program of static variable


class Student8{
int rollno;
String name;
static String college ="MY COLLEGE";

Student8(int r,String n){


rollno = r;
name = n;
}
void display ()
{

Shivaji Science College, Nagpur


BSC-II Semester-IV

[Link](rollno+" "+name+" "+college);


}

public static void main(String args[])


{
Student8 s1 = new Student8(100,"Suman");
Student8 s2 = new Student8(200,"Mahesh");

[Link]();
[Link]();
}
}

2) Java static method


If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• static method can access static data member and can change the value of it.
Example :
//Program of changing the common property of all objects(static field).
class Student9
{
int rollno;
String name;
static String college = "MY COOLEGE";
static void change()
{
college = "YOUR COLLEGE";
}

Student9(int r, String n)
{
rollno = r;
name = n;
}

void display ()
{
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[])
{
[Link]();
Student9 s1 = new Student9 (1 ,"Vijay");
Student9 s2 = new Student9 (2 ,"Ganesh");
Student9 s3 = new Student9 (3 ,"Samay");
[Link]();
[Link]();
[Link]();
}
}

Shivaji Science College, Nagpur


BSC-II Semester-IV

//Program to get cube of a given number by static method


class Calculate
{
static int cube(int x)
{
return x*x*x;
}

public static void main(String args[])


{
int result=[Link](5);
[Link](result);
}
}

[Link] Access Control Modifiers :


We can define scope of variable/method/class using the access modifier
There are four types of access modifiers.
1. Private access : Generally variables are declared as private. They can be accessed only by the
methods of that class. Methods are rarely declared as private.
2. Protected access : It is specified for a variable or method in a class. It can be accessed by the
methods of the same class, subclasses in the same package and non subclasses in the same package..
Protected variables and methods can be accessed by all methods of subclasses in different packages.
3. Package access or Friendly access: Default access is the package access. If a variable or method or
class has package access then it can be accessed by all the methods of classes in the same package.
4. Public access : When public is specified for variables, methods or class , It can be accessed by
methods of any class in the same package or different package.

2.6 Array : The array, is a fixed-size sequential collection of elements of the same data type.

2.6.1 Declaration of Array :


To use an array in a program, you must declare a variable to reference the array.
syntax :
dataType[] arrayName;
OR
dataType arrayName[] ;

Example:
double[] salary;
or
double salary[];

2.6.2 Creating Arrays:


You can create an array by using the new operator with the following syntax:
arrayName = new dataType[arraySize];

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement, as shown below:

Syntax :

Shivaji Science College, Nagpur


BSC-II Semester-IV

dataType[] arrayName= new dataType[arraySize];

2.6.3 Initialization of Arrays :

Alternatively you can create arrays as follows:


Syntax :
dataType[] arrayName= {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are start from 0 to [Link]-1.

Example:
Following statement declares an array variable, salary, creates an array of 10 elements of double type and
assigns its reference to salary:
double[] salary= new double[10];

Example:
How to create, initialize and process arrays:
public class TestArray
{
public static void main(String[] args) {
double[] salary = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < [Link]; i++) {
[Link](salary[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += salary[i];
}
[Link]("Total is " + total);
// Finding the largest element
double max = salary[0];
for (int i = 1; i < [Link]; i++) {
if (salary[i] > max) max = salary[i];
}
[Link]("Max is " + max);
}
}

//program to illustrate Array using method


import [Link].*;
class SrArray
{
int a[];
static int sz;
void arraysize(int size)
{sz=size;
a=new int[size];
}

void read() throws IOException


{
Shivaji Science College, Nagpur
BSC-II Semester-IV

InputStreamReader reader=new InputStreamReader([Link]);


BufferedReader in = new BufferedReader(reader);
String text;
for(int i=0;i<sz;i++)
{
[Link](" Enter Array["+ i +"]");
text= [Link]();
a[i]= [Link](text);
}
}

void show_sum()
{ int sum=0;
for(int i=0;i<sz;i++)
sum=sum+a[i];
[Link](" Array sum is "+sum);
}
}

class srarray1
{
public static void main(String args[]) throws IOException
{ SrArray a1;
a1=new SrArray();
int count;
InputStreamReader reader=new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text;
[Link]("\n Enter the number of elements ? ");
text= [Link]();
count= [Link](text);
[Link](count);
[Link]();
a1.show_sum();

Enter the number of elements ?


5
Enter Array[0]
12
Enter Array[1]
33
Enter Array[2]
45
Enter Array[3]
67
Enter Array[4]
89
Array sum is 246
Press any key to continue . . .

//program to Sort Array using bubble sort method


import [Link].*;
class SrArray
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
int a[];
static int sz;

void arraysize(int size)


{sz=size;
a=new int[size];
}

void read() throws IOException


{
InputStreamReader reader=new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text;
for(int i=0;i<sz;i++)
{
[Link](" Enter Array["+ i +"]");
text= [Link]();
a[i]= [Link](text);
}

void bubble_sort()
{
int temp;
for(int i=0;i<sz;i++)
{
for(int j=1;j<sz-i;j++)
{ if (a[j-1]>a[j])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;

}
}
}
}

void show()
{
[Link](" Array is ");
for(int i=0;i<sz;i++)
[Link](a[i]+" ");
[Link]();

}
}

class SrarrayBubbleSort
{
public static void main(String args[]) throws IOException

{ SrArray a1;
Shivaji Science College, Nagpur
BSC-II Semester-IV

a1=new SrArray();
int count;
InputStreamReader reader=new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text;
[Link]("\n Enter the number of elements ? ");
text= [Link]();
count= [Link](text);
[Link](count);
[Link]();
[Link]();
a1.bubble_sort();
[Link]();
}
}

2.6.4 Passing Arrays to Methods:

You can also pass arrays to methods. For example, the following method displays the elements in array:

public static void printArray(int[] salary)


{
for (int i = 0; i < [Link]; i++)
{
[Link](salary[i] + " ");
}
}
You can invoke it by passing an array.
For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});

2.6.5 Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the
reversal of another array:

public static int[] reverse(int[] list)


{
int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}
return result;
}

2.6.6 Two Dimensional Array :

Creation of two dimensional array :

Shivaji Science College, Nagpur


BSC-II Semester-IV

int[][] a = new int[2][4];

This two-dimensional array will have two rows and four columns. This table can store 8 integer values.
2.6.7 Initialization of two dimensional array:
We can declare a two dimensional array and directly store elements at the time of its declaration as:
int marks[][]={{80,89,65,90,87},{69,45,77,88,97},{55,66,77,88,99}};
or
int[][] A = { { 10,20,30,40 },
{ 11,22,-33,66 },
{ 55,-56,78,-45 }
};
2.6.8 Variable Size Arrays :
Java treats multidimensional array as “Arrays of Arrays”. It is possible to declare two dimensional array as
follows :
int x[][] = new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[7];

These statements creates two dimensional array having different lengths for each row.
2.7 Java String Handling :
2.7.1 Java String provides methods that can be performed on a string such as compare, concat, equals,
split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
1. char[] ch={'n','a','g','p','u','r' };
2. String s=new String(ch);
is same as:
1. String s="nagpur";
Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of
characters. String class is used to create string object.
There are two ways to create String object:
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists
in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
2) By new keyword
1. String s=new String("Welcome"); In such case, JVM will create a new string object in normal(non pool) heap
memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
Java String Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};

Shivaji Science College, Nagpur


BSC-II Semester-IV

String s2=new String(ch);//converting char array to string


String s3=new String("example");//creating java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}
}

Output :
java
strings
example
Press any key to continue . . .

2.7.1 Java String Methods : The [Link] class provides a lot of methods to work on string. By the
help of these methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
i) toUpperCase() and toLowerCase() method:
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
[Link]([Link]());//SACHIN
[Link]([Link]());//sachin
[Link](s);//Sachin(no change in original)
ii) trim() method :
The string trim() method eliminates white spaces before and after string.
String s=" Sachin ";
[Link](s);// Sachin
[Link]([Link]());//Sachin

iii) charAt() method:


The string charAt() method returns a character at specified index.
String s="Sachin";
[Link]([Link](0));//S
[Link]([Link](3));//h

iv) valueOf() method


The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char
array into string.
int a=10;
String s=[Link](a);
[Link](s+10);
v) replace() method :
The string replace() method replaces all occurrence of first sequence of character with second sequence
of character.
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=[Link]("Java","Kava");//replaces all occurrences of "Java" to "Kava"
[Link](replaceString);

Shivaji Science College, Nagpur


BSC-II Semester-IV

vi) compareTo() method


The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
• s1 == s2 :0
• s1 > s2 :positive value
• s1 < s2 :negative value

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
vii) concat() method

The java string concat() method combines specified string at the end of this string. It returns combined
string. It is like appending another string.

The signature of string concat() method is given below:


public String concat(String anotherString)

public class ConcatExample{


public static void main(String args[]){
String s1="java string";
[Link]("is immutable");
[Link](s1);
s1=[Link](" is immutable so assign it explicitly");
[Link](s1);
}}

viii) replace() method


The java string replace() method returns a string replacing all the old char or CharSequence to new char or
CharSequence.
There are two type of replace methods in java string.
public String replace(char oldChar, char newChar)
and
public String replace(CharSequence target, CharSequence replacement)

Example :
//Java String replace(char old, char new) method example
public class ReplaceExample1{
public static void main(String args[]){

Shivaji Science College, Nagpur


BSC-II Semester-IV

String s1="javatpoint is a very good website";


String replaceString=[Link]('a','e');//replaces all occurrences of 'a' to 'e'
[Link](replaceString);
}}

ix) substring() method :


The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where start index is
inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts from
1.
There are two types of substring methods in java string.
public String substring(int startIndex)
and
public String substring(int startIndex, int endIndex)
If you don't specify endIndex, java substring() method will return all the characters from startIndex.
Java String substring() method example
public class SubstringExample{
public static void main(String args[]){
String s1="javatpoint";
[Link]([Link](2,4));//returns va
[Link]([Link](2));//returns vatpoint
}}

x) length() method :
This method returns the length of this string.
Syntax : public int length()
import [Link].*;
public class Test{
public static void main(String args[]){
String Str1 = new String("Welcome");
String Str2 = new String("Sunil" );

[Link]("String Length :" );


[Link]([Link]());

[Link]("String Length :" );


[Link]([Link]());
}
}

2.7.2 wrapper classes :


Wrapper class in java provides the mechanism to convert primitive into object and object into [Link]
the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
The object of the wrapper class contains or wraps its respective primitive data type. converting primitive
data types into object is called boxing, and this is taken care by the compiler. therefore while using a
wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper
class. And the Wrapper object will be converted back to a primitive data type, and this process is called
unboxing. The Number class is part of the [Link] package.

Here is an example of boxing and unboxing:

Shivaji Science College, Nagpur


BSC-II Semester-IV

public class Test{


public static void main(String args[]){
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
[Link](x);
}
}
This would produce the following result:15
When x is assigned integer value, the compiler boxes the integer because x is integer object. Later, x is
unboxed so that they can be added as integer.

2.8 Inheritance in Java :


2.8.1 Inheritance is a mechanism of deriving new class from an old class. The new class acquires all the
properties and behaviors of parent object. You can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Syntax :
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
When the class B inherits the contents of class A, the classs A is called base class, super class or parent
class. The class B is called subclass, derived class or child class.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer is the subclass and Employee is the superclass. Relationship between two classes is
Programmer IS-A Employee. It means that Programmer is a type of Employee.
1) Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below flow diagram
shows that class B extends only one class A. Here A is a parent class of B and B would be a child class of
A.

Shivaji Science College, Nagpur


BSC-II Semester-IV

// Example of single level inheritance


Class A
{
public void methodA()
{
[Link]("Base class method");
}
}

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

2) Multilevel Inheritance
In Multilevel inheritance , a new class can inherit from a derived class, thereby making this derived class
the base class for the new class. As you can see in flow diagram C is subclass or child class of B and B is a
child class of A.

Example :

//Program to demonstrate the multilevel inheritance of methods


Class X
{
public void methodX()
{
[Link]("Class X method");
}
}

Class Y extends X
{
Shivaji Science College, Nagpur
BSC-II Semester-IV

public void methodY()


{
[Link]("class Y method");
}
}

Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}

public static void main(String args[])


{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}

3) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In diagram, class B,C and D inherits
the same class A. A is parent class (or base class) of B,C & D.

4) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) from more than one base
class. The problem with “multiple inheritance” is that the derived class will have to manage the dependency
on two base classes. Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.

5) Hybrid Inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. By using interfaces you can
have multiple as well as hybrid inheritance in Java.

Shivaji Science College, Nagpur


BSC-II Semester-IV

//Program to demonstrate the multilevel inheritance of variables


class A
{ int i,j;
}
class B extends A
{
}
class C extends B
{
int k;
}

class InherDemoVariable
{
public static void main(String args[] )
{
C c1=new C();
c1.i=100;
c1.j=200;
c1.k=300;
[Link]("Value of i in class C = "+c1.i);
[Link]("Value of j in class C = "+c1.j);
[Link]("Value of k in class C = "+c1.k);
}
}
//Program to demonstrate the inheritance of variables hiding
class A
{
int i=11;
}

class B extends A
{

class C extends B
{
int i=33;
}
class InherDemoVariableHiding
{
public static void main(String args[] )
{

Shivaji Science College, Nagpur


BSC-II Semester-IV

C c1=new C();
[Link]("Value of i in class C = "+c1.i);
}
}

2.8.2 Super Keyword :


When variable in subclass has the same name as a variable in the super class, the variable defined in
the super class is shadowed(hided). In some situations, we have to access the value of the shadowed
variable, then we have to use the super keyword for accessing the value of the shadowed variable.

//Program to demonstrate the use of super keyword in inheritance


class A
{
String z="Good Morning ";

class B extends A
{

class C extends B
{
String z="Good Evening ";
void show()
{
[Link](super.z);
[Link](z);

}
}

class InherDemoVariableSuper
{
public static void main(String args[] )
{
C c1=new C();
[Link]();

}
}
Output :
Good Morning
Good Evening
Press any key to continue . . .

//Program to demonstrate the use of super keyword in inheritance

Shivaji Science College, Nagpur


BSC-II Semester-IV

class Box
{
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
[Link]("Volume is : " + width * height * depth);
}
}

class InheritanceMatchBox extends Box


{
double weight;
InheritanceMatchBox()
{
}
InheritanceMatchBox(double w, double h, double d, double m)
{
super(w, h, d);
weight = m;
}
public static void main(String args[])
{
InheritanceMatchBox mb1 = new InheritanceMatchBox(10, 10, 10, 10);
[Link]();
[Link]("width of MatchBox 1 is " + [Link]);
[Link]("height of MatchBox 1 is " + [Link]);
[Link]("depth of MatchBox 1 is " + [Link]);
[Link]("weight of MatchBox 1 is " + [Link]);
}
}
Output :
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Press any key to continue . . .
Shivaji Science College, Nagpur
BSC-II Semester-IV

//Program to demonstrate the inheritance of Methods


class A
{
void show1()
{
[Link]("Good Morning ");
}
void show2()
{
[Link]("Good Afternoon");
}
}
class B extends A
{

}
class C extends B
{
void show3()
{
[Link]("Good Evening ");
}
}

class InherDemoMethod
{
public static void main(String args[] )
{
C c1=new C();
c1.show1();
c1.show2();
c1.show3();
}
}

Output:
Good Morning
Good Afternoon
Good Evening
Press any key to continue . . .

2.8.3 Overriding : It will take place when method in subclass and the corresponding method in super
class have the same signature and should have the same return type. Otherwise the complier will display
error message. The compiler picks an overloaded method during the compilation stage itself. This is
called early binding. In overridden method, java virtual machine dynamically select the correct version
of an overridden method to be executed. This is called as late binding(Run time Polymorphism).
Syntax :
super.method_name(argument lists);

//Program to demonstrate the overriding concept


class A
Shivaji Science College, Nagpur
BSC-II Semester-IV

{
void show(String s)
{
[Link]("Class A : "+s);
}
}

class B extends A
{
void show(String s)
{
[Link](s);
[Link]("Class B : "+s);
}
}
class InherDemoOverridingMethod
{
public static void main(String args[] )
{
A a1=new A();
[Link]("Hello");
B b2=new B();
[Link]("Hi");
}
}
Output :
Class A : Hello
Class A : Hi
Class B : Hi
Press any key to continue . . .

2.8.4 Difference between method overloading and method overriding in java


A list of differences between method overloading and method overriding are given below:
Method Overloading Method Overriding
1. Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship
2 In case of method overloading, In case of method overriding, parameter must
parameter must be different. be same.
3 Method overloading is the example of Method overriding is the example of run time
compile time polymorphism. polymorphism.
4 Return type can be same or different in Return type must be same or covariant in
method overloading. But you must method overriding.
have to change the parameter.
5 class OverloadingExample{ class Animal{
static int add(int a,int b){return a+b;} void eat(){[Link]("eating...");}
static int add(int a,int b,int c){return a+b+c;} }
} class Dog extends Animal{

void eat(){[Link]("eating bread...");}


}

Shivaji Science College, Nagpur


BSC-II Semester-IV

2.8.5 ABSTRACT CLASSES


Definition: A class for which we can not create object. An abstract class is a class that is declared as
abstract It may or may not include abstract methods.
An abstract method is a method that is declared without an implementation (without braces, and followed by
a semicolon), like this:
abstract void studtest(int rollno, double testfees);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject
{
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclass, the subclass usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, the subclass must also be declared abstract.
Example :
abstract class GraphicObject
{
int x, y;
...
void moveTo(int newX, int newY)
{
...
}
abstract void draw();
abstract void resize();
}

Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations
for the draw and resize methods:

class Circle extends GraphicObject {


void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {

void draw() {
...
}

void resize() {
...
}
}

Shivaji Science College, Nagpur


BSC-II Semester-IV

2.8.6 FINAL classes : A class that is declared with the final modifier can not be extended.

2.8.7 this keyword : This is a reference variable that refers to the current object.

//example of this keyword


class Student11{
int id;
String name;

Student11(int id,String name){


[Link] = id;
[Link] = name;
}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
[Link]();
[Link]();
}
}

2.9 Interfaces :
Interface is just like class. The difference is that interface define only abstract methods and constants.

Syntax
Interface InterfaceName
{
//variable declaration
static final dataType VariableName = value
//method declaration
returnType methodName1(parameter list)
}

Example :
interface Area
{
final static float pi=3.142f;
float compute(float x, float y)
void show();
}

2.9.1 Difference between class and interface in java


A list of differences between method overloading and method overriding are given below:

Class Interface
1. The members of class can be constant or The members of interface are always declared
variables. as constant.

2 The class definition can contain code All methods in an interface are abstract. Which
Shivaji Science College, Nagpur
BSC-II Semester-IV

for each of its methods means all methods must be empty; no code
implemented.

3 It can be instantiated by declaring It can not be used to declare objects. It can


objects. only be inherited by class
4 It can use various access specifier like It can only use the public access specifier.
public, private, or protected.

2.9.2 Implementing Interfaces :

Interfaces are used as “super classes” whose properties are inherited by classes.
Syntax:
class ClassName implements InterfaceName
{
Body of classname
}
Syntax:
class ClassName extends superclass implements InterfaceName1,…
{
Body of classname
}

Example :
//Program to demonstrate the Interface concept
interface Area
{
static final float pi=3.14F;
float compute(float x, float y);
}

class Rectangle implements Area


{

public float compute(float x, float y)


{
return(x*y);
}
}

class Circle implements Area


{

public float compute(float x, float y)


{
return(pi*x*x);
}
}

Shivaji Science College, Nagpur


BSC-II Semester-IV

class InterfaceTest
{
public static void main(String args[] )
{
Rectangle rect = new Rectangle();
Circle cir= new Circle();
Area area;
area=rect;
[Link]("Area of Rectangle is "+ [Link](10,20));
area=cir;
[Link]("Area of Circle is "+ [Link](10,0));
}
}

Area of Rectangle is 200.0


Area of Circle is 314.0
Press any key to continue . . .

//Program to demonstrate the Multiple Inheritace


interface Sports
{
static final float sportWt=6.0F;
void putWt();
}

class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}

void putNumber()
{
[Link]("Roll No. : "+ rollNumber);
}
}

class Test extends Student


{
float paper1, paper2;
void getMarks(float m1,float m2 )
{
paper1=m1;
Shivaji Science College, Nagpur
BSC-II Semester-IV

paper2=m2;
}
void putMarks()
{
[Link]("Marks Obtained ");
[Link]("Paper 1 : "+ paper1);
[Link]("Paper 2 : "+ paper2);
}
}

class Results extends Test implements Sports


{
float total;
public void putWt()
{
[Link]("Sport Weight : "+ sportWt);
}
void show()
{
total = paper1 + paper2+ sportWt;
putNumber();
putMarks();
putWt();
[Link]("Total Score : "+ total);
}
}
class MultipleInheritanceTest
{
public static void main(String args[] )
{
Results std1 = new Results();
[Link](10);
[Link](45.5F, 55.8F);
[Link]();
}
}

Roll No. : 10

Marks Obtained

Paper 1 : 45.5

Paper 2 : 55.8

Sport Weight : 6.0

Shivaji Science College, Nagpur


BSC-II Semester-IV

Total Score : 107.3

Press any key to continue . .

Shivaji Science College, Nagpur

You might also like