UNIT22024
UNIT22024
UNIT22024
Sc
UNIT – II
ARRAYS
Array:
An array is set of similar data items share a common name. The individual values in an
array are called elements. The elements of an array can be of any data type. All the elements in an
array are of the same type. Array elements are variables. A particular value in indicated by writing
a number called index number (or) subscript in brackets after array name. There are two types of
arrays.
1. One-dimensional arrays
2. Multi-dimensional arrays
1. One-dimensional arrays:
A list of items can be given one variable name using only one subscript and such a variable
is called a single-subscripted variable (or) a one-dimensional array.
Declaring of Arrays:
Form1 Examples:
int number[ ];
float average[ ];
Form2 Examples:
int[] counter;
float[ ] marks;
Creation of Arrays:
After declaring an array , we need to create it in the memory. Java allows us to create arrays
using new operator only, as shown below
Example:
number = new int[5];
average = new float[10];
These lines create necessary memory locations for the arrays number and average and
designate them as int and float respectively. Now the variable number refers to an array of 5
integers and average refers to an array of 10 floating point values.
It is also possible to combine the two steps declaration and creation into one as shown
below
Initialization of Arrays:
The final is to put values into the array created. This process is known as initialization .
That is done using the array subscripts as shown below.
Example:
number[ 0 ]= 35;
number[1] = 40;
…………………
…………………
number[4] = 50;
Note that Java creates arrays starting with the subscript of 0 and ends with a value one less
than the size specified.
Unlike C ,Java protects array from overruns and under runs. Typing to access an array
bound its boundaries will generate an error message.
We can also initialize arrays automatically in the same way as the ordinary variables when
they are declared as shown below.
The array initializer is a list of values separated by commas and surrounded by curly braces.
Note that no size is given in this case. The compiler allocates enough space for all the elements
specified in the list.
Example:
int number[ ] = { 35,40,20,50};
Array length:
In Java all arrays store the allocated size in a variable named length. We can obtain the
length of the array a using a.length.
Example:
int size = a.length;
This information will be useful in the manipulation of arrays when their size are not known.
Example1:
class array1
{
Public static void main(String args[ ] )
{
int sum = 0;
int a[ ] = {10,20,3,4,5};
for ( int i = 0;i < 5; i++)
{
sum = sum+a[i];
}
System.out.println(“Total = “+sum);
}
}
Output:
C:/>javac array1.java
C:/>java array1
Total=42
Example2:
(4th lab program)Write a java program to find the searching element in a given array
elements(using java.util.scanner class).
import java.util.Scanner;
class searcharray
{
public static void main(String args[])
{
int n,x,flag=0,i=0;
Scanner dis=new Scanner(System.in);
System.out.println("enter the no.of elements of the array");
n=dis.nextInt();
int a[]=new int[n];
System.out.println("enter the array elements");
for(i=0;i<n;i++)
{
a[i]=dis.nextInt();
}
if(flag==1)
{
System.out.println("Element found at position: "+(i+1));
}
else
{
System.out.println("Element is not found");
}
}
}
Output:
C:/>javac searcharray.java
C:/>java searcharray
Enter the number of elements of the array
4
Enter the array elements
1
2
3
4
Enter the element you want to find
3
Element found at position:3
Example2(repeat):
Write a java program to find the searching element in a given array elements(using
DataInputStream class).
import java.io.*;
class searcharray1
{public static void main(String args[])throws IOException
{
int i,j,x,n,flag=0;
DataInputStream s=new DataInputStream(System.in);
System.out.println("enter the size of the array ");
n=Integer.parseInt(s.readLine());
int a[]=new int[n];
System.out.println("enter the array elements");
for(i=0;i<n;i++)
a[i]=Integer.parseInt(s.readLine());
System.out.println("the array elements are ");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
System.out.println();
if(flag==1)
{
System.out.println("Element found at position: "+(i+1));
}
else
{
System.out.println("Element is not found");
}
}}
Output:
C:/>javac searcharray1.java
C:/>java searcharray1
Enter the size of the array
4
Enter the array elements
1
2
3
4
the array elements are
1 2 3 4
enter the element you want to find
6
Element is not found
Example:
int number[ ] [ ] = ;
number = new int[5][5];
It can also be initialize arrays automatically when they are declared. The syntax is as
follows
Example:-
(5th lab program)Write a java program to find the addition, subtraction and multiplication
of two matrices.
import java.io.*;
class matrixaddsubmultiplication
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int i,j,k,c1,r1,c2,r2;
System.out.println("enter the row and column size of the matrix A");
r1=Integer.parseInt(dis.readLine());
c1=Integer.parseInt(dis.readLine());
System.out.println("enter the row and column size of the matrix B");
r2=Integer.parseInt(dis.readLine());
c2=Integer.parseInt(dis.readLine());
int a[][]=new int[r1][c1];
int b[][]=new int[r2][c2];
int c[][]=new int[r1][c1];
int d[][]=new int[r1][c1];
int e[][]=new int[r1][c2];
System.out.println("enter the matrx A elements");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
a[i][j]=Integer.parseInt(dis.readLine());
System.out.println("enter the matrx B elements");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
b[i][j]=Integer.parseInt(dis.readLine());
System.out.println("Matrix A:=");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
System.out.print(a[i][j]+"\t");
System.out.println("\n");
}
System.out.println("Matrix B:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(b[i][j]+"\t");
System.out.println();
}
if((r1==r2)&&(c1==c2))
{
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
d[i][j]=a[i][j]-b[i][j];
}
System.out.println("Matrix addition:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(c[i][j]+"\t");
System.out.println();
}
System.out.println("Matrix subtraction:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(d[i][j]+"\t");
System.out.println();
}
}
else
System.out.println("The matrix addition is not possible");
if((c1==r2))
{
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
e[i][j]=0;
for(k=0;k<r2;k++)
e[i][j]=e[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("Matrix multiplication:=");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
System.out.print(e[i][j]+"\t");
System.out.println("\n");
}
}
else
System.out.println("The matrix multiplication is not possible");
}
}
Output:
C:/>javac matrixaddsubmultiplication.java
C:/>java matrixaddsubmultiplication
Enter the row and column size of the matrix A
2
2
Enter the row and column size of the matrix B
2
2
Enter the elements of the matrix A
2
2
2
2
Enter the elements of the matrix B
1
1
1
1
Matrix A:=
2 2
2 2
Matrix B:=
1 1
1 1
Matrix addition:=
3 3
3 3
Matrix subtraction:=
1 1
1 1
Matrix multiplication:=
4 4
4 4
COMMAND LINE ARGUMENTS
Java has the facility of command line arguments. Java main method consists array of string
objects .When we run the program, the array will fill with the values of any arguments it was given
in the command line.
class CommandLine
{
public static void main(String[] args)
{
if (args.length > 0)
{
System.out.println(args.length);
}
else
System.out.println("No command line "+
"arguments found.");
}
}
STRINGS
Creating strings:
Definition:
A string is a collection of characters .In Java strings are class objects and implemented
using two classes, namely, String and StringBuffer. A Java string is an instantiated object of the
String class. Java strings as compared to C strings are more reliable and predictable. This is
basically due to C’s lack ok of bounds-checking .A Java string is not a character array and is not
NULL terminated. Strings may be declared and created as follows:
String stringname;
Stringname = new String(“ string”);
Example:
String firstname;
firstname = new String(“ Java ”);
Like arrays , it is possible to get the length of the string using length method of the String class.
int m = firstname.length;
String arrays:
We can also create and use arrays that contain strings. The statement
,
The String class defines number methods that allow us to accomplish a variety of string
manipulation tasks. The String functions are
1. toLowerCase( ):
This function converts the given entire string to lower case.
Syntax: String.toLowerCase( );
Example:
class lower
{
public static void main(String args [ ] )
{
String s1 = new String (“JAVA “);
System.out.println(s1.toLowerCase( ));
}
}
Output: java
2. toUpperCase( ):
Output: JAVA
3. replace ( ):
Output: Java
4. trim ( ):
This function remove white spaces at the beginning and end of the String
Syntax: String .trim( );
Example:
class trim
{
public static void main(String args[])
{
String s1=new String(" JAVA ");
System.out.println("Before trim string length is"+s1.length());
s1=s1.trim();
System.out.println("After trim string length is"+s1.length());
}
}
Output:
Befor trim sting length is 6
After trim string length is 4
5. equals( ):
This function compare two given strings s1 , s2 and returns the Boolean value ‘true’ if
they are equal and the Boolean value ‘false’ otherwise.
Syntax: String1.equals(String2);
Example:
class equal
{
Public static void main( String args[ ] )
{
String s1 = “java”;
String s2 = “java”;
System.out.println( s1.equals(s2));
}
}
Output: true
6. equalsIgnoreCase( ):
This function compare two strings s1 ,s2 and returns the Boolean value ‘true’ if they are
equal otherwise it returns ‘false’ ignoring the case of characters.
Syntax: string1.equalsIgnoreCase(string2)
Example:
class equalignore
{
Public static void main( String args[ ] )
{
String s1 = “java”;
String s2 = “JAVA”;
System.out.println( s1.equalsIgnoreCase(s2));
}
}
Output: true
7. length( ):
This function returns the length of the given string.
Syntax: String.length( );
Example:
class length
{
Public static void main( String args[ ] )
{
String s1=”java”;
int l = s1.length ( );
System.out.println(l);
}
}
Output: 4
8. charAt( ):
This function returns the character at the specified position in the given string.
Syntax: String.charAt(n);
Example:
class ch
{
Public static void main (String args[ ] )
{
String s1 = ” Program”;
char c = s1.charAt(1);
System.out.println(c) ;
}
}
Output: r
9. compareTo( ):
This function compare two strings s1 and s2 and returns negative value if s1<s2 , positive
value if s1>s2 , and returns zero if they are equal.
Syntax: String1.compareTo(String2);
Example:
class compare
{
Public static void main( String args[ ])
{
String s1 = “ java”;
String s2 = “ program”;
if(s1 . compareTo(s2) > 0)
System.out.println(“ String s1 is greater than s2”);
else if(s1.compareTo(s2) < 0)
System.out.println(“ String s2 is greater than s1”);
else
System.out.println(“ S1 is equal to s2”);
}
}
10. concat( ):
Output: javaprogram
11. substring( );
This function returns the substring of the given string.
Syntax: String.substring(n)
Example:
class sub
{
Public static void main( String args[ ] )
{
String s1=”java program”;
String s2= s1.substring(4);
System.out.println(s2);
}
}
Output: program
12.indexOf( ):
This function gives the position of the first occurance of the given character in the string.
Syntax: String.indexOf(‘char’);
Example:
class index
{
Public static void main(String args[ ])
{
String s1=”java”;
int n= s1.indexOf(‘a’);
System.out.println(n);
}
}
Output: 1
13. startsWith( ):
This function determines whether a given string begins with a specified string or not and
returns the Boolean value true if yes other wise false .
Syntax: String.startsWith(String);
Example:
class starts
{
Public static void main( String args[ ] )
{
String s1 = “java”;
System.out.println(s1.startsWith(“ja”));
}
}
Output: true
14. endsWith( ):
This function determines whether a given string ends with a specified string or not and
returns the Boolean value true if yes other wise false .
Syntax: String.endsWith(String);
Example:
class ends
{
Public static void main( String args[ ] )
{
String s1 = “java”;
System.out.println(s1.endsWith(“ja”));
}
}
Output: false
15. toString( ):
System.out.println(a.toString( ));
}
}
Output: 10
class stringclassmethods
{
public static void main(String args[])
{
String s1="priya",s2="darsan",s3="ASN";
System.out.println("length"+s1.length());
System.out.println("concatination"+s1.concat(s2));
System.out.println("uppercase"+s2.toUpperCase());
System.out.println("lowercase "+s3.toLowerCase());
System.out.println("substring(2)"+s1.substring(2));
System.out.println("replace"+s3.replace('N','K'));
System.out.println("end with "+s2.endsWith("n"));
System.out.println("start with "+s1.startsWith("p"));
System.out.println("character at 3 is "+s2.charAt(3));
System.out.println("\nsearching functions");
String s="this is his wish";
System.out.println("length"+s.length());
System.out.println("First occurence of is "+s.indexOf("is"));
System.out.println("last occurence of is"+s.lastIndexOf("is"));
System.out.println("\ncomparison functions\n");
String x="RAVI",y="RAJESH",z="ravi";
int k=x.compareTo(y);
if(k>0)
System.out.println(x+"is big");
else if (k<0)
System.out.println(y+"is big");
else
System.out.println(x+"and "+y+"are equal");
if(x.equals(y))
System.out.println(x+"and "+y+"are equal");
else
System.out.println(x+"and "+y+"are not equal");
if(x.equalsIgnoreCase(z))
System.out.println(x+"and "+z+"are equal");
else
System.out.println(x+"and "+z+"are equal");
}
}
Output:
C:\javac stringclassmethods.java
C:\java stringclassmethods
Length 5
Concatenation priyadarsan
Upper case DARSAN
Lower case asn
Substring(2)iya
Replace ASK
Endswith true
Startwith true
Character at position 3 is s
Searching functions
First occurrence of is 2
Last occurrence of is 13
Comparision functions
RAVI is big
RAVI and RAJESH are not equal
RAVI and ravi are equal
(7th lab program)Write a java program for sorting a given list of names in ascending order.
import java.io.*;
class ascendingnames
{
public static void main(String args[])
{
int i,j,n=4;
String names[]={“srinivas”,”ajay”,”vasu”,”Krishna”};
String temp;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(names[i].compareTo(names[j]) > 0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
System.out.println(“The names in ascending order are”);
for(i=0;i<n;i++)
System.out.println(names[i]);
}
}
Output:
C:>javac ascendingnames.java
C:>java ascendingnames
The names in ascending order are
ajay
krishna
srinavas
vasu
CLASSES, OBJECTS & METHODS
Creating Classes:
A class is a non-primitive data type that contains member variables (data) and
member functions (methods) that operates on the variable. A class is declared by the use
of the class keyword. The general form of class definition is as follows.
datatype methodname1(parameter-list)
{
method body
}
……………………………….
……………………………….
datatype methodname-n(parameter-list)
{
method body;
}
}
The data or variables defined with in a class are called instance variables. The code
is present with in methods. Collection of methods and variables defined with in a class
are called members of class.
Variable declaration:
Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are created
whenever an object of the class is instantiated. we can declare the instance variables
exactly the same way as we declare local variables.
Example:
class Rectangle
{
int length;
int width;
}
Methods declaration:
Methods are declared inside the body of the class but immediately after the
declaration of the instance variables. The general form of the method decleration as
follows
returntype methodname(parameterlist)
{
method-body;
}
Method declaration have four basic parts:
➢ The name of the method(Method prototype)
➢ The type of value the method return
➢ A list of parameters
➢ The body of the method
1. Declare a variable of the class type. At this stage , the variable refers to an object
only.
2. Assigning an actual , physical copy of the object and assign it to that variable by
means of new operator. The new operator dynamically allocates memory for an
object and returns a reference to that object.
null
s1
The second statement assigns the object reference and allocates memory.
s1
sample object
s1
sample object
s2
Accessing class members:
All variables must be assigned values before they are used in our program. All
class members are accessed by means of “dot “operator.
The general format of accessing instance variables of the class by dot operator is
as follows
Syntax : objectname.variablename=value;
where objectname is name of the object , variable name is the name of the instance
variable.
Where object is name of the object, method name is the name of the instance
method that calls with the object and parameter – list is a list of actual values separated
by commas.
Example: void getdata(int x, int y)
{
length=x;
width=y;
}
s1.getdata(10,20);
Example:
(8th lab program) write a java program to calculate area of a rectangle.
class Rectangle
{
int length,width;
void getdata(int x ,int y)
{
length = x;
width = y;
}
int rectArea( )
{
int area = length * width;
return(area);
}
}
class rectarea
{
public static void main(String args[ ])
{
int area1,area2;
Rectangle rect1 = new Recatangle ( );
Rectangle rect2 = new Rectangle ( );
rect1.length=15;
rect1.width = 10;
area1=rect1.length * rect1.wifdth;
rect2.getdata(10,20);
area2=rect2.rectArea( );
System.out.println(“area1 =” +area1);
System.out.println(“area2 =” +area2);
}
}
Output:
C:\>javac rectarea.java
C:\>java rectarea
area1=150
area2=200
CONSTRUCTORS
A constructor is a special method of class , which is invoked automatically,
whenever an object of a class is created. A constructor has the following characteristics :
Example:
class sample
{
int x;
sample()
{
x=10;
}
void show()
{
System.out.println(“x=”+x);
}
}
class defsample
{
public static void main(String args[])
{
sample s=new sample();
s.show();
}
}
output: x=10;
Parameterized Constructor:
A constructor that takes arguments as parameters is called parameterized
constructor. If any constructors are defined by a class with the parameters, java will not
create a default constructor for the class.
Example:
class sample
{
int x;
sample( int k)
{
x=k;
}
void show()
{
System.out.println(“x=”+x);
}
}
class parsample
{
public static void main(String args[])
{
sample s=new sample(25);
s.show();
}
}
output: x=25
Constructor Overloading:
A class can have multiple constructors. This is called constructor overloading. All
the constructors have the same name as corresponding to the class name and they are
differ only in number of arguments or data types or order.
Example:
(9th lab program) Write a java program to demonstrate the constructor overloading.
class sample
{
int x,y;
sample()
{
x=0;
y=0;
}
sample(int a)
{
x=a;
}
sample(int a,int b)
{
x=a;
y=b;
}
void show()
{
System.out.println(“x=”+x+” “ +”y=”+y);
}
}
class sampleover
{
public static void main(String args[])
{
sample s1=new sample();
Example:
static int a ;
static int show( int x, int y);
Example1:
class sample
{
static int c=0;
sample( )
{
c++;
}
System.out.println(“no of objects=”+c);
}
}
class Test
{
public static void main(String args[ ])
{
sample s1 = new sample ( );
sample s2 = new sample ( );
sample s3 = new sample ( );
sample.display();
}
}
output: no of objects 3
this KEYWORD
Java define “this” keyword that can be used inside any method to refer the current
object. “this” always a reference to the object on which method was invoked. “this”
reference is implicitly used to refer to both the instance variables and methods of
current objects.
Example:
class Box
{
int len,dep,hei;
Box(int len, int dep , int hei)
{
this.len = len;
this.dep = dep;
this.hei = hei;
}
int volume( )
{
return (len * dep * hei);
}
}
class thisdemo
{
public static void main(String args[ ])
{
Box obj = new Box(1,2,3);
int x = obj.volume( );
System.out.println(“volume=”+x);
}
}
output: volume = 6;
“this” key word sis also used explicitly refer to the instance variables.
INHERITANCE
Inheritance:
The mechanism of deriving a new class from an old class is called inheritance. A
class that is inherited (old class) is called super class or base class or parent class. The
class that does the inheriting (new class) is called a sub class or derived class or child
class. Inheritance allows a sub classes to inherit all the variables and methods of their
parent classes.
INHERITANCE HIERARCHIES:
Inheritance is classified into different forms.
B
Sub class (or) Derived class (or) Child class
B
DEPARTMENT OF COMPUTER SCIENCE 28 A.S.N.COLLEGE,TENALI
OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc
B C D
A B
B C
The keyword extends signifies that the properties of the super class name are
extended to the subclass name. The sub class will now contain its variables and methods
as well as those of super class. But it is not vice versa.
1).Single Inheritance:
Derivation of a subclass from only one super class is called single Inheritance.
super( x , y);
height = z;
}
int volume ( )
{
return (length * breadth * height );
}
}
class Test
{
public static void main(String args[ ] )
{
BedRoom room1 = new BedRoom (14 , 12 , 10 );
int area1 = room1 . area( );
int volume1 = room1.volume ( );
System.out.println( “Area1=” + area1);
System.out.println(“Volume1 = “ + volume1);
}
}
output: Area1 = 168
Volume1 = 1680
The above program defines a class Room and extends it to another class BedRoom
. Note that BedRoom defines its own data members and methods. The subclass BedRoom
now includes these instance variables, namely, length, breadth and height and two
methods., area and volume.
The constructor in the derived class uses the super keyword to pass values that
are required by the base constructor. The statement
BedRoom room1 = new BedRoom(14 , 12 , 10 );
first calls the BedRoom constructor method, which is in turn calls the Room constructor
method by using the keyword super
Finally the object room1 of the subclass BedRoom calls the method area defined in
the super class as well as the method volume defined in the subclass itself.
‘super’ keyword (or) Subclass Constructor:
A subclass constructor is used to construct the instance variables of both the
subclass and the super class . The subclass constructor uses the keyword super to invoke
the constructor method of the super class. The keyword super is used subject to the
following conditions:
B
Intermediate superclass (or) Father
C
subclass (or) child
import java.io.*;
class company
{
int id;
String cname;
DataInputStream dis=new DataInputStream(System.in);
void cgetdata()throws IOException
{
System.out.println("enter the name of the company");
cname=dis.readLine();
System.out.println("Enter the company ID");
id=Integer.parseInt(dis.readLine());
}
void cshow()
{
System.out.println("The company name is"+cname);
System.out.println("The company ID is"+id);
}
}
double tot=prate*req;
System.out.println("total cose is"+tot);
System.out.println("the remaining products are"+(phand-req));
}
else
{
System.out.println("sorry company does not have the stock");
}
}
}
class multilevelinheritance
{
public static void main(String args[])throws IOException
{
customer c=new customer();
c.cgetdata();
c.pgetdata();
c.custgetdata();
c.cshow();
c.pshow();
c.custshow();
}
}
Output:
C:/>javac multilevelinheritance.java
C:/>java multilevelinheritance
Enter the name of the company
Wipro
Enter the company ID
6797
Enter the product id
4945
Enter the name of the product
LED lamps
Number of products in hand
500
Enter each product cost
30
Enter the name of the customer
Srinivas
Number of required products are
42
The company name is Wipro
B C D
import java.io.*;
class students
{
int ano;
String sname;
DataInputStream dis=new DataInputStream(System.in);
void sgetdata()throws IOException
{
System.out.println("Enter the student name");
sname=dis.readLine();
System.out.println("enter the student admission number");
ano=Integer.parseInt(dis.readLine());
}
void sshow()
{
System.out.println("student admission number is"+ano);
System.out.println("student name is"+sname);
}
}
int rno,year;
String bname;
DataInputStream dis=new DataInputStream(System.in);
void uggetdata()throws IOException
{
System.out.println("enter the student roll number");
rno=Integer.parseInt(dis.readLine());
System.out.println("enter the student year");
year=Integer.parseInt(dis.readLine());
System.out.println("enter the branch name");
bname=dis.readLine();
}
void ugshow()
{
System.out.println("student roll number is "+rno);
System.out.println("the current studying year is "+year);
System.out.println("branch name is "+bname);
}
}
class pg extends students
{
int rno;
String cname,semno;
DataInputStream dis=new DataInputStream(System.in);
void pggetdata()throws IOException
{
System.out.println("enter the student roll number");
rno=Integer.parseInt(dis.readLine());
System.out.println("enter the student course name");
cname=dis.readLine();
System.out.println("enter the current semester");
semno=dis.readLine();
}
void pgshow()
{
System.out.println("student roll number is "+rno);
System.out.println("the current semester is "+semno);
System.out.println("the student couse name is "+cname);
}
}
class hierarchicalinheritance
{
public static void main(String args[])throws IOException
{
ug u=new ug();
pg p=new pg();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("1.Under Graduation");
System.out.println("2.Post Graduation");
System.out.println("enter your choice");
int ch=Integer.parseInt(dis.readLine());
switch(ch)
{
case 1:
u.sgetdata();
u.uggetdata();
u.sshow();
u.ugshow();
break;
case 2:
p.sgetdata();
p.pggetdata();
p.sshow();
p.pgshow();
break;
}
}
}
Output:
C:/>javac hierarchicalinheritance.java
c:/>java hierarchicalinheritance
Derivation of one class from two or more super classes is called Multiple
Inheritance. But java does not support Multiple Inheritance directly. It can be
implemented by using Interface concept.
A B
class student
{
int rno,p1,p2;
void getnumber(int n,int m1,int m2)
{
rno=n;
p1=m1;
p2=m2;
}
void putnumber()
{
System.out.println("Roll number"+rno);
System.out.println("part 1 "+p1);
System.out.println("part 2 "+p2);
}
}
interface sports
{
float sportwt=6.0f;
public void putwt();
}
}
void display()
{
putnumber();
putwt();
System.out.println("total score is "+total);
}
}
class multipleinheritance
{
public static void main(String args[])
{
result r=new result();
r.getnumber(12,90,90);
r.display();
}
}
Output:
C:/>javac multipleinheritance.java
C:/>java multipleinheritance
Rollnumber 12
Part1 90
Part2 90
Sports wt is 6.0
Total score is 186.0
5). Hybrid Inheritance:
Derivation of a class involving more than one form of Inheritance is called Hybrid
Inheritance
B C
class student
{
int rno;
void getnumber(int n)
{
rno=n;
}
void putnumber()
{
System.out.println("Roll number"+rno);
}
}
putmarks();
putwt();
System.out.println("total score is "+total);
}
}
class hybridinheritance
{
public static void main(String args[])
{
result r=new result();
r.getnumber(12);
r.getmarks(27.5f,33.0f);
r.display();
}
}
Output:
C:/>javac hybridinheritance.java
C:/>java hybridinheritance
For controlling the access to the various members of a class we use access
specifiers. Access specifiers determine how a member of the class can be accessed.
Java supplies a rich set of access specifiers, they are:
1. public
2. private
3. protected
4. default
Public:
When a member is specified by the public specifier, then that member can be
access by any other code i.e. from any other class or from any other package ( A
package is nothing but a group of classes). We can access this member in the
same class also.
Private:
When the private specifier assigned to a member, then tat member can be
accessed by only the member of that class, it is accessed only within the class. We
cannot access the private data outside the class, with the class objects also.
Protected:
This type of members is accessed by all the members within the package and
classes in other package that are subclasses for the class. Generally they are
useful when inheritance involved.
Default:
If no specifier is specified, then by default it taken as default specifier. Default specifier
acts as a public with in its own package, but cannot accessed outside of its package. (default is
not a keyword).
final KEYWORD
A final keyword is used for the three purposes. They are
A) final as constant:
A variable can be declared as constant with the keyword final. It must be
initialized while declaring. One we initialized the variable with final keyword it cannot
be modified in the program. This is similar to the const in c/c++.
Example: class A
{
final void show( )
{
System.out.println(“hello”);
}
}
class B extends A
{
void show( ) // error because a final method can not
be overridden
{
System.out.println(“Hai”);
}
}
C) final to prevent inheritance:
A class that is declared as final cannot be inherited in to subclasses.
Example: final class A
{
void show( )
{
System.out.println(“hello”);
}
}
class B extends A // error can not be inherited
{
void show( )
{
System.out.println(“Hai”);
}
}
POLYMORPHISM
Example: A lady can have different characteristics simultaneously. She can be a mother, a
daughter, or a wife, so the same lady possesses different behaviour in different situations.
Polymorphism in Java can be achieved in two ways i.e., method overloading and method overriding.
Polymorphism in Java is mainly divided into two types.
Compile-time polymorphism
Runtime polymorphism
Compile-time polymorphism can be achieved by method overloading, and Runtime polymorphism can
be achieved by method overriding
Note: Two methods differ in only by return type will result in a syntax error.
Example:
(15th lab program) Write a java program to demonstrate the method overloading.
class sample
{
int large(int x, int y)
{
if(x>y)
return x;
else
return y;
}
class check
{
public static void main(String args[ ])
{
sample s=new sample( );
System.out.println(“ largest of two numbers is:”+s.large(10,20));
System.out.println(“ largest of three numbers is:”+s.large(11,22,33));
}
}
A method in a subclass has the same name , type of the variables and order of the
variables as a method in its super class ,then the method in the sub class is said to be
override the method in the super class .The process is called Method overriding. In such
process the method defined by the super class will be hidden.
When the method is called , the method defined the sub class has invoked and
executed instead of the method in the super class .The super reference followed by the
dot( .) operator may be used to access the original super class version of that method from
the sub class.
Example1:
write a java program to demonstrate the method overriding.
class A
{
int i,j;
A( int a, int b)
{
i = a;
j = b;
}
void show( )
{
System.out.println(“i=”+i);
System.out.println(“j=”+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k = c;}
void show( )
{
System.out.println(“k=”+k);
}
}
class Override
{
public static void main9String args[ ]))
{
B obj = new B( 1,2,3);
obj.show( );
}
}
Output:
k=3
Example2:
(16th lab program) Write a java program to demonstrate the method overriding.
class A
{
int i,j;
A( int a, int b)
{
i = a;
j = b;
}
void show( )
{
System.out.println(“i=”+i);
System.out.println(“j=”+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k = c;
}
void show( )
{
super.show( );
System.out.println(“k=”+k);
}
}
class Override1
{
public static void main9String args[ ]))
{
B obj = new B( 1,2,3);
obj.show( );
}
}
Output:
i= 1
j=2
:k=3
class abstractdemo
{
Public static void main(String args[])
{
sub1 s1=new sub1();
sub2 s2=new sub2();
sub3 s3=new sub3();
s1.calculate(2);
s2.calculate(9);
s3.calculate(4);
}
}
Output:
C:/>javac abstractdemo.java
C:/>java abstractdemo
4.0
3.0
64.0