Sei sulla pagina 1di 99

Object Oriented Programming Through Java Laboratory Record

Object Oriented Programming Through Java Lab Record


For
I Yr. MCA II Semester

Compiled by Mrs. G.KALPANA, Asst.Professor in MCA Department

3
2014-2015
[Pick the date]

Department of MASTER OF COMPUTER APPLICATIONS


Chaitanya Bharathi Institute of Technology (Autonomous)
Gandipet, Hyderabad-75.

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 0
Object Oriented Programming Through Java Laboratory Record

INDEX
S.NO PROGRAMME NAME P.NO.

I Basic Programs 4

1)Write java program to print Biggest of 3 Numbers using Logical Operators 4

2) write a java program to print first 10 numbers in fibonacci series 5

3) Write a java program to print Factorial of a given number 6

7
4)Write java program to print the following o/p
8
5) Write a java program to print sum of Sum of Digits
6) Write a java Program for swapping two numbers 9

7)Wrte a java program to print primes up to the given prime number 10

8) Write java program to check given string is a palindrome or not 11

9) wajp to print sum of n terms in the series 1/1! +1/2!+1/3!..... 12

10) Write A Java Program to print Quadratic roots using command line 13
arguments

11) Write a java program to print the names in sorted order using arrays 14

12) Write a java program to print multiplication table using arrays 15

II Method Overloading 18

1)Write a java program to demonstrate method overloading 18

2)Write a java program to find the volume of a Box using method 19


overloading with different number of perameters.

III Constructor overloading : 22

1) Write a java program to illustrate the concept of constructors and its 22


overloading.

2) Write a java program for Rectangle class using constructor overloading 24


with different no. of parameter list

3) Wajp to copy the values of one object into another using constructor. 26

S.NO PROGRAMME NAME P.NO

IV Inheritence 28

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 1
Object Oriented Programming Through Java Laboratory Record

1) Wajp for Rectange class using Simple Inheritance 28

2) Write a Java program to demonstrate multilevel inheritance. 30

3) Write a Java program to implement the following hierarchy and find area 31
and perimeter Abstract

V Method Overriding 35

1)Write a java program for Bank class using Method Overriding. 36

2) Write a java program to demonstrate Method overriding (use super 38


keyword)

VI Dynamic Method Dispatch 39

1)Write a Java program to demonstrate dynamic dispatch. 40

2) Wajp for Bank class using Dynamic Method Dispatch 41

VII Abstract Class: 43

1) Write a Java program to implement a Vehicle Abstract class. 43

2)Wajp to demonstrate the concept of abstract class 46

VIII Packages: 48

1)Write a Java program to demonstrate use of user defined packages. 49

2) write a java package for book class and then import and display the result. 50

3) write a java program to find the cube of a number for various data types 51
using package and then import and display the results.

IX Interfaces: 53

1) Write a Java program to illustrate the multiple inheritance by using 53


Interfaces.

X Super , Static, final key words : 56

1)Write a java program to illustrate the keywords i)super ii)static iii)final 56

S.NO PROGRAMME NAME P.NO

XI Exception handling: 57

1)wajp to demonstrate simple example for exception handling 57

2)Wajp to demonstrate exception handling with multiple catch blocks 58

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 2
Object Oriented Programming Through Java Laboratory Record

3) wajp using NumberFormat exception 60

4)Wajp for user defined exception 61

XII How to make executable jar files in JDK1.3.1? 63

XIII Multithreading 64

1) Write a Java program to demonstrate the concept of daemon threads 64

2) Write a Java program to demonstrate the concept of synchronization by 66


suitable example

3) Write a Java program to demonstrate the concept of Inter thread 68


communication by Suitable example

4) Write a program to demonstrate string tokenizer. 70

XIV) 73
File I/O and Streams
1)Wajp to Demonstration of FileOutputStream and PrintStream classes 74

2) Write a java program to Write bytes to a file 75

3) Write a java program to copy bytes from one file to another. 76

XV Applets 79

1) Wajp for Sum of Two Numbers using Applet 79

2)Wajp for Applet using drawstring(), drawRect() and drawOval() 80

3) Write a Java program to demonstrate banner applet. 81

4) wajp for Bouncing of a Ball using applet 83

XIV 87
AWT: 1 ) Wajp that prints a message by clicking on the button
using AWT events and applets 2) GUI with controls menus
and event handling.

Java lab programmes

I. Basic programs:

1) Write java program to print Biggest of 3 Numbers using Logical Operators

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 3
Object Oriented Programming Through Java Laboratory Record

Importjava.util.*;
class Biggest3
{
public static void main(String args[])
{
int n1, n2, n3, big;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No 1: ");
n1=scan.nextInt();
System.out.print("Please Enter No 2: ");
n2=scan.nextInt();
System.out.print("Please Enter No 3: ");
n3=scan.nextInt();
if(n1>n2 && n1>n3)
big=n1;
else if(n2>n1 && n2>n3)
big=n2;
else
big=n3;
System.out.println("Biggest No: " + big);
}
}
O/P:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 4
Object Oriented Programming Through Java Laboratory Record

2) write a java program to print first 10 numbers in fibonacci series


classFibo
{
public static void main(String args[])
{
inta,b,temp,n;
a=0;
b=1;
for(n=1;n<=10;n++)
{
System.out.println(a);
temp=a+b;
a=b;
b=temp;
}
}
}s

o/p :

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 5
Object Oriented Programming Through Java Laboratory Record

3) Write a java program to print Factorial of a given number


Importjava.util.*;
class Factorial
{
public static void main(String args[])
{ int n, i, fact=1;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter a No.");
n=scan.nextInt();
for(i=n;i>=1;i--)
{
fact=fact*i ;
}
System.out.println("Factorial of " + n + " is " + fact);
}
}
O/P:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 6
Object Oriented Programming Through Java Laboratory Record

4)Write java program to print the following o/p

Following star pattern is printed


*
**
***
****
*****

class Stars
{
Public static voidmain(String[]args)
{
int row, numberOfStars;

for(row =1; row <=10; row++)


{
for(numberOfStars=1;numberOfStars<=row;
numberOfStars++)
{
System.out.print("*");
}
System.out.println();// Go to next line
}
}
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 7
Object Oriented Programming Through Java Laboratory Record

Output of program:

5) Write a java program to print sum of Sum of Digits

Logic: 513 -> 5+1+3=9

n res n sum
513 0
513%10 3 3
513/10 51 3

51%10 1 4
51/10 5 4
5%10 5 9
5/10 0 9

importjava.util.*;
classSumDigits
{
public static void main(String args[])
{
int n, res,sum=0;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No. = ");

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 8
Object Oriented Programming Through Java Laboratory Record

n=scan.nextInt();
System.out.print("Sum of digits of a number" +n+ "is = "); while(n>0)
{
res=n%10;
n=n/10;
sum=sum+res;
}
System.out.print(+sum);

}
}

o/p:

6) Write a java Program for swapping two numbers

importjava.util.*;
class Swap
{
public static void main(String args[])
{
int n1, n2, temp;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No 1:=");
n1=scan.nextInt();
System.out.print("Please Enter No 2: =");
n2=scan.nextInt();
temp=n1;
n1=n2;
n2=temp;
System.out.println("First No: " + n1);
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 9
Object Oriented Programming Through Java Laboratory Record

System.out.println("Second No: " + n2);

}
}

o/p:

7)Wrte a java program to print primes up to the given prime number

importjava.util.*;
public class Prime
{
public static void main(String args[])
{
inti,j,p=1;
Scanner sc =new Scanner(System.in);
System.out.print("enter a number up to which u want print primes =");
int n=sc.nextInt();
for(i=2;i<=n;i++)
{
p=1;
for(j=2;j<i;j++)
{
if(i%j==0)
{
p=0;
}}
if(p==1)
System.out.println(j);
}
}
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 10
Object Oriented Programming Through Java Laboratory Record

o/p:

8) Write java program to check given string is a palindrome or not

importjava.util.*;
public class Palin
{
public static void main(String args[])
{
System.out.print("enter strings = ");
Scanner sc=new Scanner(System.in);
String s=sc.next();
StringBuffer tmp=new StringBuffer(s);
tmp.reverse();
String str2;
str2=new String(tmp);
if(s.equals(str2))
System.out.println("the given string " + s + " is palindrome");
else
System.out.println("the given string " + s + " is not palindrome");
}
}

O/P:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 11
Object Oriented Programming Through Java Laboratory Record

9) wajp to print sum of n terms in the series 1/1! +1/2!+1/3!.....

importjava.util.Scanner;
classSeriesfact
{
public static void main(String args[])
{
int i;
float sum=0,f=1;
System.out.println("enter number of terms in the series");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(i=1;i<=n;i++)
{ for(f=1;f<=i;f++)
{
f=f*i;
sum=sum + (float)1/f;
}
}
System.out.println("sum of" +n +"terms is = " +sum);
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 12
Object Oriented Programming Through Java Laboratory Record

10) Write A Java Program to print Quadratic roots using command line arguments

importjava.lang.*;
class Quadratic
{
public static void main(String args[])
{
inta,b,c,d;
double r1,r2;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
d=b*b-4*a*c;
if(d==0)
{
r1=r2=-(float)b/(2*a);
System.out.println("the roots are real equal =" +r1 + " and r2 = " +r2);
}
else if(d>0)
{
double t=Math.sqrt(d);
r1=(-b+t)/(2*a);

r2=(+b+t)/(2*a);
System.out.println("the roots are real and distict \n r=" +r1 +" and r2=" +r2);
}
else if(d<0)
{
System.out.println("the roots are imaginary and there is no real solution ");
}
}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 13
Object Oriented Programming Through Java Laboratory Record

11) Write a java program to print the names in sorted order using arrays

import java.lang.*;
class Stringsort
{
static String name[]={"Bombay" , "Madras" ,"Delhi" ,"Pune"};

public static void main(String args[])


{
int size=name.length;
String temp=null;

for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if ( name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
System.out.println("soted names are ");
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 14
Object Oriented Programming Through Java Laboratory Record

o/p

12) Write a java program to print multiplication table using arrays

import java.util.Scanner;
import java.io.*;
import java.lang.*;
class MatrixMul
{
public static void main(String[] args)
{

int i= 0,j=0,k=0,p,q,m,n;
int a[][] = new int[10][10];
int b[][] = new int[10][10],c[][] = new int[10][10];
Scanner sc = new Scanner(System.in);
System.out.print("Enter no of rows in the A matrix= ");
p=sc.nextInt();
System.out.print("Enter a no of columns in the A matrix = ");
q=sc.nextInt();
System.out.print("Enter no of rows in the B matrix= ");
m = sc.nextInt();
System.out.print("Enter no of columns in the B matrix= ");
n = sc.nextInt();
if(q==m)
{
System.out.print ("Enter A matrix values :");
for(i=0;i<p;i++)
{
for(j=0; j<q ;j++)
{
a[i][j] = sc.nextInt() ;
}

}
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 15
Object Oriented Programming Through Java Laboratory Record

System.out.println("\nMatrix A values are ");

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print(" "+a[i][j]) ;
}
System.out.println();
}
System.out.println("Enter matrix B values :");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j] = sc.nextInt() ;
}
}

System.out.println("\nMatrix B values ");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+b[i][j]) ;
}
System.out.println();
}
System.out.println("\n C Matrix is C = A * B Result");
if(q == m)
{
for(i=0;i<p;i++)
{
for(j=0;j<n;j++)
{
c[i][j]= 0 ;
for(k=0;k<q;k++)
{
c[i][j] = c[i][j] + (a[i][k] * b[k][j]) ;
}
}
}
}
// for C matrix Printing

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 16
Object Oriented Programming Through Java Laboratory Record

for(i=0;i<p;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+c[i][j]) ;
}
System.out.println();
}
}else
{
System.out.println("Matrix multiplication not possible");
}
}
}

O/P:

13) Write a java programme for bubble sort using arrays

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

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 17
Object Oriented Programming Through Java Laboratory Record

int[] nums={12,87,9,-4,76,34,890,543,77,02};
int a,b,t;
int size;
size=10;
System.out.print("original array is");
for (int i=0;i<size;i++)
System.out.print(" " +nums[i]);

System.out.println();

for(a=1;a<size;a++)
for(b=size-1;b>=a;b--)
{
if(nums[b-1]>nums[b])
{
t=nums[b-1];
nums[b-1]=nums[b];
nums[b]=t;
}
}
System.out.print("sorted array is ");
for(int i=0;i<size;i++)
System.out.print(" "+nums[i]);
System.out.println();
}
}

Output:

II. Write a java program to demonstrate classes and objects.

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 18
Object Oriented Programming Through Java Laboratory Record

class Vehicle
{

int pass;
int fcapacity;
int speed;
}
class MainDemo
{
public static void main(String args[])
{
Vehicle carobj=new Vehicle();
Vehicle busobj=new Vehicle();
Vehicle vanobj=new Vehicle();
int distance;
carobj.pass=6;
carobj.fcapacity=26;
carobj.speed=60;
distance=carobj.fcapacity*carobj.speed;
System.out.println("car can carry: "+carobj.pass+" passengers with fuel capacity

"+carobj.fcapacity+"liter and distance it travels"+distance+"km");


busobj.pass=26;
busobj.fcapacity=260;
busobj.speed=40;
distance=busobj.fcapacity*busobj.speed;
System.out.println();
System.out.println("bus can carry "+busobj.pass+" passengers with fuel capacity

"+busobj.fcapacity+"liter and distance it travels "+distance+"km");


vanobj.pass=15;
vanobj.fcapacity=100;
vanobj.speed=80;
distance=vanobj.fcapacity*vanobj.speed;
System.out.println();
System.out.println("van can carry"+vanobj.pass+"passengers with fuel capacity

"+vanobj.fcapacity +"liter and distance it travels "+distance+"km");


}}

Output:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 19
Object Oriented Programming Through Java Laboratory Record

II. Method Overloading


Method overloading means when two or more methods have the same name but a different
signature. Signature of a method is nothing but a combination of its name and the sequence of its
parameter types.
1) Write a java program to demonstrate method overloading

Program:
class OverloadDemo
{
void max(float a, float b)
{
System.out.println("\nmax method with float argument invoked");
if(a>b)
System.out.println(a+" is Greater");
else
System.out.println(b+" is Greater");
}
void max(double a, double b)
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 20
Object Oriented Programming Through Java Laboratory Record

System.out.println("max method with double arg invoked");


if(a>b)
System.out.println(a+" a is Greater");
else
System.out.println(b+" b is Greater");
}
max(long a, long b)
{
System.out.println("\nmax method with long arg invoked");
if(a>b)
System.out.println(a+" a is Greater");
else System.out.println(b+" b is Greater");
}
public static void main(String[] args)
{
OverloadDemo o=new OverloadDemo();
o.max(23L,12L);
o.max(2,3);
o.max(54.0,35f);
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 21
Object Oriented Programming Through Java Laboratory Record

2)Write a java program to find the volume of a Box using method overloading with
different number of perameters.

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 22
Object Oriented Programming Through Java Laboratory Record

class Box

int width,breadth,height;

void getdata(int length)

width=breadth=height=length;

void getdata(int a,int b)

{ width=a;

breadth=height=b;

void getdata(int x,int y, int z)

{ width=x;

breadth=y;

height=z;

int volume()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 23
Object Oriented Programming Through Java Laboratory Record

System.out.println(" ");

return width*breadth*height;

}}

class MainBox

{ public static void main(String args[])

{ int vol;

Box mybox1=new Box();

Box mybox2=new Box();

Box mybox3=new Box();

mybox1.getdata(10,20,30);

vol=mybox1.volume();

System.out.println("volume of my box with 3 perameters is = " +vol);


mybox2.getdata(10,20);

vol=mybox2.volume();

System.out.println("volume of my box with 2 perameters is = " +vol);

mybox3.getdata(5);

vol=mybox3.volume();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 24
Object Oriented Programming Through Java Laboratory Record

System.out.println("volume of my box with 1 perameter is = " +vol);

o/p:

3)Wajp for overloading using variable arguments methods.


class Vararg
{
static void vaTest(int ...v)
{
System.out.println();
System.out.print(" first method invoked :" +"no of args :" +v.length +" and the contents are :");
for(int x:v)
System.out.print(x+ " ");
System.out.println();

}
static void vaTest(boolean ...v)
{
System.out.println();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 25
Object Oriented Programming Through Java Laboratory Record

System.out.print(" second method invoked:" +"no of args :" +v.length +" and the contents are :");
for(boolean x:v)
System.out.print(x+ " ");
System.out.println();
}
static void vaTest(String msg, int ...v)
{
System.out.println();
System.out.print(" third method invoked :" +"the message is :" +msg +"no of args :" +v.length +"
and the contents are :");
for(int x:v)
System.out.print(x+ " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(1,2,3);
vaTest("testing : ",10,20);
vaTest(true,false,false);
}
}

Output:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 26
Object Oriented Programming Through Java Laboratory Record

III. Constructor overloading :

Constructor is a special type of method which is having the same class name that is used to
initialize the object. Constructor is invoked at the time of object creation.

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.
1) Write a java program to illustrate the concept of constructors and its overloading.
import java.lang.*;
class TestOl
{
int hrs,mins,scnds;
TestOl(int h,int m,int s)
{
hrs=h;
mins=m;
scnds=s;
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 27
Object Oriented Programming Through Java Laboratory Record

public TestOl(int h)
{
hrs=h;
mins=0;
scnds=0;
}
public TestOl(int h,int m)
{
hrs=h;
mins=m;
scnds=0;
}
public TestOl()
{
hrs=0;
mins=0;
scnds=0;
}
void primetime()
{
System.out.println("hrs:"+hrs+"\t mins:"+mins+"\t scnds:"+scnds);
}
}
class COverLoad
{
public static void main(String args[])
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 28
Object Oriented Programming Through Java Laboratory Record

TestOl obj1=new TestOl();


obj1.primetime();
TestOl obj2=new TestOl(5);
obj2.primetime();
TestOl obj3=new TestOl(7,6);
obj3.primetime();
}}

Out Put :

2) Write a java program for Rectangle class using constructor overloading with different
no. of parameter list
class Rectangle
{
int length;
int width;
int area()
{
return length*width;
}
void perimeter()
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 29
Object Oriented Programming Through Java Laboratory Record

int p=2*length+2*width;
System.out.println("perimeter of rectangle is " +p);
}
Rectangle()
{
length=2;
width=3;
}
Rectangle(int a)
{
length=width=a;
}
Rectangle(int a, int b)
{
length=a;
width=b;
}
}
class MainForRectangle
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
float area1= r1.area();
System.out.println("area of Rectangle 1 is :" +area1);
r1.perimeter();
System.out.println();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 30
Object Oriented Programming Through Java Laboratory Record

Rectangle r2=new Rectangle(10);


float area2=r2.area();
System.out.println("area of Rectangle 2 is : " +area2);
r2.perimeter();
System.out.println();
Rectangle r3=new Rectangle(20,10);
System.out.println("area of Rectangle 3 is : " +r3.area());
r3.perimeter();
}
}
O/P:

3)Write a java program for Subject class using constructor overloading with different no.
of parameter list

class Subject {
String name1,name2;

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 31
Object Oriented Programming Through Java Laboratory Record

Subject()
{
System.out.println();
System.out.println("MCA first year subjects are as follows.");
System.out.println();
}

Subject(String t)
{
name1 = t;
}
Subject(String s1, String s2)
{
name1=s1;
name2=s2;
System.out.print(" "+ name1 +" " +name2);
}
void setName(String t)
{
name1 = t;
}

void getName()
{
System.out.print(" "+name1);
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 32
Object Oriented Programming Through Java Laboratory Record

public static void main(String[] args)


{
Subject cpp = new Subject();
cpp.setName("C++");
cpp.getName();
Subject java = new Subject("Java");
java.getName();
Subject two=new Subject("OR","Mefa");
}
}

Output:

4) Wajp to copy the values of one object into another using constructor.
class Student
{
int id;
String name;
int age;
Student(int i,String n,int a)
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 33
Object Oriented Programming Through Java Laboratory Record

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

Student(Student s)
{
id = s.id;
name =s.name;
age=s.age;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Kalpana",39);
Student s2 = new Student(s1); //copy contents from s1 in to s2
s1.display();
s2.display();
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 34
Object Oriented Programming Through Java Laboratory Record

IV) Inheritance is a mechanism in which one object acquires all the properties and behaviours
of parent object.

The following kinds of inheritance are there in java.

Simple Inheritance : When a subclass is derived simply from it's parent class then this
mechanism is known as simple inheritance.
Multilevel Inheritance: When a subclass is derived from a derived class then this
mechanism is known as the multilevel inheritance
Multiple Inheritance is achieved in java by using Interfaces.

1) Wajp for Rectangle class using Simple Inheritance


class Rectangle
{
int length;
int width;
void area()
{
System.out.println("area of Rectangle is " +(length*width));
}
}
class Cuboid extends Rectangle
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 35
Object Oriented Programming Through Java Laboratory Record

int height;

void volume()
{
System.out.println("Volume of cuboid is " +(length*width*height));
}
}
class Simpleinheritance1
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Cuboid c=new Cuboid();
r.length=10;
r.width=5;
r.area();
c.length=15;
c.width=10;
c.height=5;
c.volume();
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 36
Object Oriented Programming Through Java Laboratory Record

2) Write a Java program to demonstrate multilevel inheritance.

class Name
{
String name="swathi";
int age=20;
}
class Mark extends Name
{
int m1=30,m2=30,m3=30;
}
class Student extends Mark
{
int total;
void calc()
{
total=m1+m2+m3;
}
void show()
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 37
Object Oriented Programming Through Java Laboratory Record

System.out.println("\n NAME: " +name+"\n AGE:"+age+"\n MARK1="+m1+"\n MARK2="


+m2+"\n MARK3="+m3+"\n TOTAL:"+total);
}
}
class MultilevelInheritence
{
public static void main(String args[])
{
Student ob=new Student();
ob.calc();
ob.show();
}
}

o/p:

3) Write a Java program to implement the following hierarchy and find area and
perimeter Abstract

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 38
Object Oriented Programming Through Java Laboratory Record

abstract class shape


{
abstract double calcar();
abstract double calcper();
abstract void display();
}
class circle extends shape
{
double r;
circle(double a)
{
r=a;
}
void display()
{
System.out.println("\nradius="+r);
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 39
Object Oriented Programming Through Java Laboratory Record

double calcar()
{
double arc=(3.14*r*r);
return arc;
}
double calcper()
{
double per=(2*3.14*r);
return per;
}}
class square extends shape
{
double a;
square(double s)
{
a=s;
}
void display()
{
System.out.println("\nside="+a);
}
double calcar()
{
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 40
Object Oriented Programming Through Java Laboratory Record

double ars=a*a;
return ars;
}
double calcper()
{
double per=4*a;

return per;
}}
class triangle extends shape
{
double b,h;
triangle(double p, double q)
{
b=p; h=q;
}
void display()
{
System.out.println("\nbreadth="+b+"\t height="+h);
}
double calcar()
{
double art=(0.5*b*h);
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 41
Object Oriented Programming Through Java Laboratory Record

return art;
}
double calcper()
{
return 0;
} };
class Classhierarchy
{
public static void main(String s[])
{
circle c=new circle(5.2f);
c.display();
System.out.println("\nArea of circle ="+c.calcar());
System.out.println("\nPerimeter of circle ="+c.calcper());
square sq=new square(2.3f);
sq.display();
System.out.println("\nArea of square ="+sq.calcar());
System.out.println("\nPerimeter of square ="+sq.calcper());
triangle t=new triangle(1.3f,4.5f);
t.display();
System.out.println("\nArea of triangle ="+t.calcar());
}}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 42
Object Oriented Programming Through Java Laboratory Record

o/p:

V) Method Overriding: When there are two methods with same name and prototypes in super
class and subclass then it is called Method overriding.

Advantages of Java Method Overriding:

Method Overriding is used to provide specific implementation of a method that is already


provided by its super class.
Method Overriding is used for Runtime Polymorphism

1)Write a java program for Bank class using Method Overriding.

class Bank
{
int getRateOfInterest()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 43
Object Oriented Programming Through Java Laboratory Record

{
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class Test{
public static void main(String args[]){
SBI s=new SBI();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 44
Object Oriented Programming Through Java Laboratory Record

ICICI i=new ICICI();


AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
o/p:

2) Write a java program to demonstrate Method overriding (use super keyword)

class Sup
{
int x;
Sup (int x) //constructor
{
this.x=x;
}
void display()
{
System.out.println("x in Super= "+x);

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 45
Object Oriented Programming Through Java Laboratory Record

}}
class sub extends Sup
{
int y;
sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("\nX in Super Class="+x);
System.out.println("Y in Sub Class="+y);
}}
class TestOverride
{
public static void main(String naren[])
{
sub obj=new sub(100,200);
obj.display();
}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 46
Object Oriented Programming Through Java Laboratory Record

VI) Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

1)Write a Java program to demonstrate dynamic dispatch.


Program:
abstract class Shape
{
protected final static double PI = 22.0/7.0;
protected double length;
public abstract double area();
}
class Square extends Shape
{
Square(double side)
{
length=side;
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 47
Object Oriented Programming Through Java Laboratory Record

public double area()


{
return length*length;
}}
class Circle extends Shape
{
Circle(double radius)
{
length=radius;
}
public double area()
{
return PI*length*length;
}}
public class DynamicDispatch
{
public static void main(String[] args)
{
Shape sh;
Square sq = new Square(10.0);
Circle circ = new Circle(10.0);
sh=sq;
System.out.println("\n Area of Square = " + sh.area());
sh=circ;
System.out.println("Area of circle = " + sh.area());
}}
o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 48
Object Oriented Programming Through Java Laboratory Record

2) Wajp for Bank class using Dynamic Method Dispatch


class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 49
Object Oriented Programming Through Java Laboratory Record

}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class DynamicDispatch{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
Bank b=new Bank();
Bank r;
r=b;
r.getRateOfInTerest();
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 50
Object Oriented Programming Through Java Laboratory Record

VII) Abstract Class: Abstraction is the mechanism of exhibiting the necessary things by
hiding the unnecessary things.
An abstract class is a class that may have at least one abstract method.(ie without body)
we cannot create an object for abstract class. Abstract class may have reference variables
but may not have memory for it.
1) Write a Java program to implement a Vehicle Abstract class.
/* Write a Java program to implement an Vehicle Abstract class.*/
abstract class Vehicle
{
public abstract void wheels();
public abstract void seating();
public abstract void brakes();
}
class Car extends Vehicle
{
public void wheels()
{
System.out.println("\nCar Has Four Wheels");
}
public void seating()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 51
Object Oriented Programming Through Java Laboratory Record

{
System.out.println("Car Has Four Seating Capacity");
}
public void brakes()
{
System.out.println("Car Has Power Brakes\n");
}}
class Bike extends Vehicle
{
public void wheels()
{
System.out.println("Bike Has Two Wheels");
}
public void seating()
{
System.out.println("Bike Has Two Seating Capacity");
}
public void brakes()
{
System.out.println("Bike Has Disk Brakes");
}}
class VehicleDemo
{
public static void main(String args[])
{
Vehicle v=new Car();
Vehicle v1=new Bike();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 52
Object Oriented Programming Through Java Laboratory Record

v.wheels();
v.seating();
v.brakes();
v1.wheels();
v1.seating();
v1.brakes();
}}

o/p:

2)Wajp to demonstrate the concept of abstract class


abstract class Shape
{
int length;
int width;
Shape(int a, int width)
{
length=a;
this.width=width;
}

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 53
Object Oriented Programming Through Java Laboratory Record

abstract void area();


}
class Rectangle extends Shape
{
Rectangle(int length, int width)
{
super(length,width);
}
void area()
{
System.out.println("area of reactange is " +(length*width));
}
}
class Cuboid extends Shape
{
int height;
Cuboid(int length, int width, int height)
{
super(length,width);
this.height=height;
}
void area()
{
System.out.println("Surface area of cuboid is "
+(2*length*width+2*width*height+2*height*length));
}
void volume()
{
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 54
Object Oriented Programming Through Java Laboratory Record

System.out.println("volume of cuboid is"+(length*width*height));


}
}
class Mainforshape
{
public static void main(String args[])
{
Rectangle r=new Rectangle(10,20);
r.area();
Cuboid c=new Cuboid(5,10,15);
c.area();
c.volume();
Shape s;
s=r;
s.area();
s=c;
s.area();
}
}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 55
Object Oriented Programming Through Java Laboratory Record

VIII) Packages:

A package is a group of similar types of classes, interfaces and sub-packages.

Package can be categorized in two form, built-in package and user-defined package.

Advantage of Package :

Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provids access protection.

Package removes naming collision.

1)Write a Java program to demonstrate use of user defined packages.


I) // save below file Sum.java
package pack;
public class Sum
{
public void getSum(int a,int b)
{
System.out.println("\nSum Of Two Numbers"+a+" and "+b+"="+(a+b));
}
}

II) // save below file PackDemo.java


import pack.Sum;
class PackDemo
{

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 56
Object Oriented Programming Through Java Laboratory Record

public static void main(String[] args)


{
Sum s=new Sum();
s.getSum(10,20);
}}

o/p:

2) write a java package for book class and then import and display the result.
1) // Save below file Book.java
package packagetest;
public class Book
{
int book_no,book_id,book_pages;
public Book(int a,int b, int c)
{
book_no=a;
book_id=b;
book_pages=c;
}
public void book_info()
{
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 57
Object Oriented Programming Through Java Laboratory Record

System.out.println("The Book No"+book_no);


System.out.println("The Book Id "+book_id);
System.out.println("The Book Pages"+book_pages);
}
}
2. //Save below file BookMain.java

import packagetest.Book;
class BookReader
{
public static void main(String[] args)
{
Book b=new Book(12,15,86);
b.book_info();
}
}
o/p:

3) write a java program to find the cube of a number for various data types using package
and then import and display the results.
//1.program to create package

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 58
Object Oriented Programming Through Java Laboratory Record

package mathematics;
public class Mathmethods
{
public static float Cube(float n)
{
return(n*n*n);
}
public static int Cube(int n)
{
return(n*n*n);
}
public static double Cube(double n)
{
return(n*n*n);
}
public static long Cube(long n)
{
return(n*n*n);
}
}
//2. program to import
import mathematics.Mathmethods;
//import java.io.*;
import java.util.Scanner;
class Cube
{
public static void main(String S[])

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 59
Object Oriented Programming Through Java Laboratory Record

{
//int a=20;
Scanner m=new Scanner(System.in);
System.out.println("the given number is ");
int a=m.nextInt();
Mathmethods mm = new Mathmethods();
int b = Mathmethods.Cube(a);
System.out.println("cube is " +b);
}
}

o/p:
javac d . Mathmethods.java
javac Cube.java
java Cube

IX ) MultipleInheritance:

we cannot use multiple inheritance means one class cannot be inherited from more than one
classes. To use this process, Java provides an alternative approach known as Interface.

Interface:

An Interface is usually a kind of class. Interface contain only Abstract methods and Final
variable. A java class cannot be a sub class of more than one class, but a class can implements
more than one Interfaces.
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 60
Object Oriented Programming Through Java Laboratory Record

1) Write a Java program to illustrate the multiple inheritance by using Interfaces.

import java.lang.*;
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("\nName of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}}
class Result extends Student implements Exam

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 61
Object Oriented Programming Through Java Laboratory Record

{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}}
class MultipleInheritenceDemo
{
public static void main(String args[])
{
Result R = new Result("Anoop reddy",12,93,84);
R.display();
R.percent_cal();
}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 62
Object Oriented Programming Through Java Laboratory Record

X) Super , Static, final key words


1)Write a java program to illustrate the keywords i)super ii)static iii)final
class Super
{
static final int a=20;
static int b;
int c=100;
}
class SuperDemo extends Super
{
void display()
{
System.out.println("\nFinal Variable=" +super.a);
System.out.println("Super class Variable=" +super.c);
System.out.println("Static Variable="+b);
}
public static void main(String[] args)
{
SuperDemo s=new SuperDemo();
s.display();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 63
Object Oriented Programming Through Java Laboratory Record

}}

o/p:

XI) Exception handling: Exception is an abnormal condition.The exception handling is one of


the powerful mechanism provided in java. It provides the mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

1)wajp to demonstrate simple example for exception handling

import java.lang.*;

class Error2

public static void main(String args[])

int a=10;

int b=5;

int c=5;

int x,y;

try

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 64
Object Oriented Programming Through Java Laboratory Record

x=a/(b-c);

catch (ArithmeticException e)

System.out.println("division by zero");

y=a/(b+c);

System.out.println("y=" +y);

o/p:

2)Wajp to demonstrate exception handling with multiple catch blocks

class ExcHandling

public static void main(String ar[])

int a[]={5,10};

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 65
Object Oriented Programming Through Java Laboratory Record

int b=5;

try

int x=a[2]/(b-a[0]);

catch(ArithmeticException e)

System.out.println("div by zero");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("Array out of bound Error");

int y=a[1]/a[0];

System.out.println("y value is " +y);

o/p:

3) wajp using NumberFormat exception

import java.lang.Exception;

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 66
Object Oriented Programming Through Java Laboratory Record

class ExHan2

public static void main(String args[])

int invalid=0,number,count=0;

for(int i=0;i<args.length;i++)

try

number=Integer.parseInt(args[i]);

catch(NumberFormatException e)

invalid=invalid + 1;

System.out.println("\n Invalid Number= " +args[i]);

continue;

count=count +1;

System.out.println("\n Valid Number= " +count);

System.out.println("\n Invalid Number= " +invalid);

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 67
Object Oriented Programming Through Java Laboratory Record

4)Wajp for user defined exception

class InsufBalance extends Exception

InsufBalance(String s)

super(s);

class Mainbalance

public static void main(String s[])

int bal=5000;

try

int withdraw=Integer.parseInt(s[0]);

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 68
Object Oriented Programming Through Java Laboratory Record

if(bal<withdraw)

InsufBalance i= new InsufBalance("No susch bance exist");

throw i;

else

bal=bal-withdraw;

System.out.println("balance is "+bal);

catch(InsufBalance i)

System.out.println(i);

catch(Exception e)

System.out.println(e);

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 69
Object Oriented Programming Through Java Laboratory Record

XII) How to make executable jar files in JDK1.3.1?

Instructions for creating an Executable .jar file

Make or modify the Manifest.Mf to yourManifest.MF

1) Your Class name with main is the class name without .class exentension.
2) No extra spaces following the your class name with main.

Manifest-Version:1.0
Main-Class: YourClassNameWithMain
Created-by:1.2(Sun Microsystems Inc.)
On Command line : type the following
jar cvfm YourJarFileName.jar YourManifest.MF*
(or)

Jar cvfm yourJarFileName.jar YourManifest.MF C classes yourClassPath

Drag-drop the YourJarFileName.jar to your desktop double click it, it runs if your p rogram only
has System.out.println(whatever); statements, it will displaynothing. The same will happen
when you run it using java at commandline.

Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file
similar to zip utility, and more Java.

You need some windows code to see it run.


You can use it on any machine installed JDK

Create a folder name it anything.Make that folder your current directory

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 70
Object Oriented Programming Through Java Laboratory Record

Put all your files turning in that directory. Be sure to put your html file, if there is one
At your dos prompt, while you are in the directory that you created , type in:
jar cvf Prj02.jar*

This will take ALL the files in the directory including subdirectories and place them in a .jar file
Prj02 that can be replaced by any of your desired jar file name.

To test it, you can extract the contents of jar file by typing:
jar xvf Prj02.jar

XIII) Multithreading:

Multithreading is a conceptual programming paradigm where a program(process) is


divided into 2 or more sub programs(processes) , which can be implemented at the same time in
parallel.

1) Write a Java program to demonstrate the concept of daemon threads

class DaemonThread extends Thread

int i;

public void run()

for(i=0;i<5;i++);

System.out.println(this.getName()+" "+i);

public static void main(String[] args)

DaemonThread d=new DaemonThread();

DaemonThread d1=new DaemonThread();

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 71
Object Oriented Programming Through Java Laboratory Record

d.setName("\nDAEMON THREAD");

d1.setName("NORMAL THREAD");

d.setPriority(Thread.MIN_PRIORITY);

d.start();

d1.start();

o/p:

2) Write a Java program to demonstrate the concept of synchronization by suitable


example

class Addition

synchronized void add()

int a=99,b=1;

System.out.println("c="+(a+b));

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 72
Object Oriented Programming Through Java Laboratory Record

try

Thread.sleep(3000);

System.out.println("After Sleep()");

catch (InterruptedException e)

class Synchro extends Thread

Addition obj1;

public Synchro(Addition a)

obj1=a;

Thread t1=new Thread(this);

Thread t2=new Thread(this);

Thread t3=new Thread(this);

t1.start();

t2.start();

t3.start();

public void run()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 73
Object Oriented Programming Through Java Laboratory Record

obj1.add();

System.out.println("ThreadNameis"+Thread.currentThread(). getName());

class TestSynchro

public static void main(String[] args)

Addition d=new Addition();

Synchro s=new Synchro(d);

o/p:

3) Write a Java program to demonstrate the concept of Inter thread communication by


Suitable example

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 74
Object Oriented Programming Through Java Laboratory Record

public class ThreadDemo2 extends Thread

public void run()

for(int i=0;i<20;i++)

System.out.println(getName()+":"+i);

public static void main(String[] args)

System.out.println("main started");

ThreadDemo2 td=new ThreadDemo2();

ThreadDemo2 td1=new ThreadDemo2();

td.setName("Thread1");

td1.setName("Thread2");

td.start();

td1.start();

td.yield();

System.out.println("Main Exited");

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 75
Object Oriented Programming Through Java Laboratory Record

4) Write a program to demonstrate string tokenizer.

import java.util.StringTokenizer;

import java.io.*;

class StringTockenizerDemo

public static void main(String naren[]) throws IOException

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 76
Object Oriented Programming Through Java Laboratory Record

System.out.println("Enter All String Digits with Spaces");

String str=br.readLine();

StringTokenizer st=new StringTokenizer(str);

int a,sum=0;

String s;

while(st.hasMoreTokens())

s=st.nextToken();

a=Integer.parseInt(s);

sum=sum+a;

System.out.println("Sum of The given Integers"+sum);

o/p:

5) Example of MultiThreads using Thread Class

import java.io.*;

class A extends Thread

public void run()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 77
Object Oriented Programming Through Java Laboratory Record

System.out.println("Start A");

for(int i=1; i<=5; i++) System.out.println("Thread A i :"+i);

System.out.println("Exit A");

class B extends Thread

public void run()

System.out.println("Start B");

for(int j=1; j<=5; j++) System.out.println("Thread B j :"+j);

System.out.println("Exit B");

class C extends Thread

public void run()

System.out.println("Start C");

for(int k=1; k<=5; k++) System.out.println("Thread C k :"+k);

System.out.println("Exit C");

class D extends Thread

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 78
Object Oriented Programming Through Java Laboratory Record

public void run()

System.out.println("Start D");

for(int l=1; l<=5; l++)

System.out.println("Thread A l :"+l);

System.out.println("Exit D");

class threadtest

public static void main(String S[])throws IOException

new A().start();

new B().start();

new C().start();

new D().start();

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 79
Object Oriented Programming Through Java Laboratory Record

XIV) File I/O and Streams:

A file is a collection of related records placed in a particular area on disk. Storing and managing
data using files is known as file processing which includes creating,updating files and
manipulation of data.Reading and writing of data in a file can be done at the level of bytes or
characters or fields.

Input refers to the flow of data into a program and output means the flow of data out of a
program. A stream in java is a path along which data flows. The java.io package contains a large
number of stream classes that provide capabilities for processing all type of data.

1) Wajp to Demonstration of FileOutputStream and PrintStream classes

import java.io.*;

class FileOutput

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 80
Object Oriented Programming Through Java Laboratory Record

public static void main(String args[])


{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream


p = new PrintStream( out );

p.println ("This is written to a file myFile.txt");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}

o/p:

2) Wajp to Write bytes to a file

import java.io.*;

class WriteBytes

public static void main(String args[])

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 81
Object Oriented Programming Through Java Laboratory Record

// declare and initialize a byte array

byte cities[]={'D','E','L','H','I','\n','C','H','E','N','N','A','I','\n','L','O','N','D','O','N','\n'};

//create an output file stream

FileOutputStream outfile=null;

try

//connect the outfile stream to city.txt

outfile=new FileOutputStream("city.txt");

//write data to the stream

outfile.write (cities);

outfile.close( );

catch(IOException ioe)

System.out.println(ioe);

System.exit(-1);

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 82
Object Oriented Programming Through Java Laboratory Record

3) Wajp to copy bytes from one file to another

//copy bbytes from one to another

import java.io.*;

class CopyBytes

public static void main(String args[])

//declare input and output file streams

FileInputStream infile=null;

FileOutputStream outfile=null;

//declare a varible to hold a byte

byte byteRead;

try

//Connect infile to in.dat

infile = new FileInputStream("in.dat");

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 83
Object Oriented Programming Through Java Laboratory Record

//Connect outfile to in.dat

outfile=new FileOutputStream("out.dat");

//Reading bytes from in.dat and writing to out.dat

do

byteRead=(byte)infile.read( );

outfile.write(byteRead);

while(byteRead !=-1);

catch(FileNotFoundException e)

System.out.println("File not fopund");

catch(IOException e)

System.out.println(e.getMessage( ));

finally //close files

try

infile.close( );

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 84
Object Oriented Programming Through Java Laboratory Record

outfile.close( );

catch(IOException e)

{ }

o/p:

XV) GUI and Event driven programming

Applets: Applets are small java programs that are primarily used in internet computing. They
can be transported over the internet from one computer to another and run using applet viewer or
any web browser.

Applets can perform arithmetic operations, display graphics, play sounds, accept user input ,
create animation, and play interactive games.

1) Wajp for Sum of Two Numbers using Applet

import java.awt.*;

import java.applet.*;

/*Coding of HTML File <applet code = abc1.class width= 200 height=200> </applet> */
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 85
Object Oriented Programming Through Java Laboratory Record

public class abc1 extends Applet

public void paint(Graphics g)

int a=100;

int b=200;

int sum = a+b;

String s = "The Sum is :" + String.valueOf(sum);

g.drawString( s, 200,100);

}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 86
Object Oriented Programming Through Java Laboratory Record

2)Wajp for Applet using drawstring(), drawRect() and drawOval() methods

import java.awt.*;

import java.applet.*;

/*<applet code= "Objectdraw.class" height=400 width=400> </applet>*/

public class Objectdraw extends Applet

public void paint(Graphics g)

g.drawString("Hello World",20,20);

g.drawRect(40,40,30,50);

g.drawOval(150,150,40,50);

}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 87
Object Oriented Programming Through Java Laboratory Record

3) Write a Java program to demonstrate banner applet.

import java.awt.*;

import java.applet.*;

/*<HTML> <BODY> <APPLET CODE = "SampleBanner" WIDTH = "460" HEIGHT =


"220"></APPLET> </BODY> </HTML> */

public class SampleBanner extends Applet implements Runnable

String str = "This is a simple Banner developed by Class Naren ";

Thread t ;

boolean b;

public void init()

setBackground(Color.gray);

setForeground(Color.yellow);

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 88
Object Oriented Programming Through Java Laboratory Record

public void start()

t = new Thread(this);

b = false; t.start();

public void run ()

char ch;

for( ; ; )

try

repaint();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

catch(InterruptedException e)

{}

} public void paint(Graphics g)

g.drawRect(1,1,300,150);

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 89
Object Oriented Programming Through Java Laboratory Record

g.setColor(Color.green);

g.fillRect (1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}}

o/p:

4) wajp for Bouncing of a Ball using applet

import java.applet.Applet;

import java.awt.Color;

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 90
Object Oriented Programming Through Java Laboratory Record

import java.awt.Graphics;

/*<applet code= "Bounce.class" height=900 width=900> </applet>*/

class Ball

int x,y,radius,dx,dy;

Color BallColor;

public Ball(int x,int y,int radius,int dx,int dy,Color bColor)

this.x=x;

this.y=y;

this.radius=radius;

this.dx=dx;

this.dy=dy;

BallColor=bColor;

}}

public class Bounce extends Applet implements Runnable

Ball redBall;

public void init()

redBall=new Ball(250,80,50,2,4,Color.red);

Thread t=new Thread(this);

t.start();

public void paint(Graphics g)

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 91
Object Oriented Programming Through Java Laboratory Record

g.setColor(redBall.BallColor);

setBackground(Color.pink);

//g.setcolor(redBall.BallColor);

g.fillOval(redBall.x, redBall.y, redBall.radius,redBall.radius);

g.drawLine(150,400,50,500);

g.drawLine(150,400,450,400);

g.drawLine(50,500,350,500);

g.drawLine(450,400,350,500);

g.drawRect(50,500,20,100);

g.drawRect(330,500,20,100);

g.drawLine(450,400,450,500);

g.drawLine(430,500,450,500);

g.drawLine(430,500,430,420);

public void run()

{ while(true)

try

displacementOperation(redBall);

Thread.sleep(20);

repaint();

catch(Exception e)

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 92
Object Oriented Programming Through Java Laboratory Record

public void displacementOperation(Ball ball)

if(ball.y >= 400 || ball.y <= 0)

ball.dy=-ball.dy; } ball.y=ball.y+ball.dy;

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 93
Object Oriented Programming Through Java Laboratory Record

XVI) Abstract WindowToolkit(AWT):

Awt contains numerous classes and methods that allow you to create and manage
windows. A common use of the AWT is in applets , its is also used to sreate stand-alone windows
that run in a GUI environment , such as Windows.

1) Wajp that prints a message by clicking on the button


using AWT events and applets

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<html>

<body>

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 94
Object Oriented Programming Through Java Laboratory Record

<applet code="EventApplet.class" width="300" height="300">

</applet>

</body>

</html> */

public class EventApplet extends Applet implements ActionListener

Button b;

TextField tf;

public void init()

tf=new TextField();

tf.setBounds(30,40,150,20);

b=new Button("Click");

b.setBounds(80,150,60,50);

add(b);add(tf);

b.addActionListener(this);

setLayout(null);

public void actionPerformed(ActionEvent e)

tf.setText("Welcome");

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 95
Object Oriented Programming Through Java Laboratory Record

output:

2) Write a Java program to demonstrate an application involving GUI with controls menus
and event handling.

import javax.swing.*;

public class SwingMenu

public static void main(String[] args)

SwingMenu s = new SwingMenu();

public SwingMenu()

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 96
Object Oriented Programming Through Java Laboratory Record

JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and seprator


Component");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenuBar menubar = new JMenuBar();

JMenu filemenu = new JMenu("File");

filemenu.add(new JSeparator());

JMenu editmenu = new JMenu("Edit");

editmenu.add(new JSeparator());

JMenuItem fileItem1 = new JMenuItem("New");

JMenuItem fileItem2 = new JMenuItem("Open");

JMenuItem fileItem3 = new JMenuItem("Close");

fileItem3.add(new JSeparator());

JMenuItem fileItem4 = new JMenuItem("Save");

JMenuItem editItem1 = new JMenuItem("Cut");

JMenuItem editItem2 = new JMenuItem("Copy");

editItem2.add(new JSeparator());

JMenuItem editItem3 = new JMenuItem("Paste");

JMenuItem editItem4 = new JMenuItem("Insert");

filemenu.add(fileItem1); filemenu.add(fileItem2);

filemenu.add(fileItem3); filemenu.add(fileItem4);

editmenu.add(editItem1);

editmenu.add(editItem2);

editmenu.add(editItem3);

editmenu.add(editItem4);

menubar.add(filemenu);

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 97
Object Oriented Programming Through Java Laboratory Record

menubar.add(editmenu);

frame.setJMenuBar(menubar);

frame.setSize(400,400);

frame.setVisible(true);

}}

o/p:

Faculty name : G.kalpana Course: M.C.A Year/Sem : I st


year /2nd sem 98

Potrebbero piacerti anche