Beruflich Dokumente
Kultur Dokumente
IFTM UNIVERSITY
School of Computer Science & Applications
(BCA 551)
LAB MANUAL
(Session :2019-20)
INDEX
I Basic Programs 4
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
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
II Method Overloading 18
3) Wajp to copy the values of one object into another using constructor. 26
IV Inheritence 28
3) Write a Java program to implement the following hierarchy and find area 31
and perimeter Abstract
V Method Overriding 35
VIII Packages: 48
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
XI Exception handling: 57
XIII Multithreading 64
XIV) 73
File I/O and Streams
1)Wajp to Demonstration of FileOutputStream and PrintStream classes 74
XV Applets 79
XIV 87
AWT: 1 ) Wajp that prints a message by clicking on the button using AWT
2) Wajp to demonstrate Grid Layout manager using AWT
3) GUI with controls menus and event handling using SWING
I. Basic programs:
Importjava.util.*;
class Biggest3
n1=scan.nextInt();
n2=scan.nextInt();
n3=scan.nextInt();
big=n1;
big=n2;
else
big=n3;
O/P:
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 :
Importjava.util.*;
class Factorial
{ int n, i, fact=1;
n=scan.nextInt();
for(i=n;i>=1;i--)
fact=fact*i ;
O/P:
class Stars
{
Public static voidmain(String[]args)
{
int row, numberOfStars;
Output of program:
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;
}
}
o/p:
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);
System.out.println("Second No: " + n2);
}
}
o/p:
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);
}
}
}
o/p:
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:
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:
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:
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"};
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]);
}
}
}
o/p
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() ;
}
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 matrxi B values :");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j] = sc.nextInt() ;
}
}
}
}
}
}
// for C matrix Printing
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:
Program:
class OverloadDemo
if(a>b)
System.out.println(a+" is Greater");
else
System.out.println(b+" is Greater");
if(a>b)
System.out.println(a+" a is Greater");
else
System.out.println(b+" b is Greater");
max(long a, long b)
if(a>b)
System.out.println(a+" a is Greater");
o.max(23L,12L);
o.max(2,3);
o.max(54.0,35f);
o/p:
2)Write a java program to find the volume of a Box using method overloading with different
number of perameters.
class Box
int width,breadth,height;
width=breadth=height=length;
{ width=a;
breadth=height=b;
{ width=x;
breadth=y;
height=z;
int volume()
System.out.println(" ");
return width*breadth*height;
}}
class MainBox
{ int vol;
mybox1.getdata(10,20,30);
vol=mybox1.volume();
vol=mybox2.volume();
mybox3.getdata(5);
vol=mybox3.volume();
o/p:
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;
hrs=h;
mins=m;
scnds=s;
public TestOl(int h)
hrs=h;
mins=0;
scnds=0;
hrs=h;
mins=m;
scnds=0;
public TestOl()
hrs=0;
mins=0;
scnds=0;
void primetime()
class OverLoad
obj1.primetime();
obj2.primetime();
obj3.primetime();
}}
O/P:
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()
int p=2*length+2*width;
Rectangle()
length=10;
width=10;
Rectangle(int a)
length=width=a;
Rectangle(int a, int b)
length=a;
width=b;
class MainForRectangle
r1.length=5;
r1.width=5;
System.out.println(" ");
r1.perimeter();
r2.perimeter();
r3.perimeter();
float area2=r2.area();
System.out.println(" ");
O/P:
3) Wajp to copy the values of one object into another using constructor.
class Student
int id;
String name;
int age;
id = i;
name = n;
age=a;
Student(Student s)
id = s.id;
name =s.name;
age=s.age;
void display()
s1.display();
s2.display();
o/p:
IV) Inheritance is a mechanism in which one object acquires all the properties and behaviours
of parent object.
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
class Rectangle
int length;
int width;
void area()
int height;
void volume()
class Simpleinheritance1
r.length=10;
r.width=5;
r.area();
c.length=15;
c.width=10;
c.height=5;
c.volume();
o/p:
class Name
String name="swathi";
int age=20;
int m1=30,m2=30,m3=30;
int total;
void calc()
total=m1+m2+m3;
void show()
class MultilevelInheritence
ob.calc();
ob.show();
o/p:
3) Write a Java program to implement the following hierarchy and find area and perimeter
Abstract
};
double r;
circle(double a)
r=a;
void display()
System.out.println("\nradius="+r);
double calcar()
double arc=(3.14*r*r);
return arc;
double calcper()
double per=(2*3.14*r);
return per;
}}
double a;
square(double s)
a=s;
void display()
System.out.println("\nside="+a);
double calcar()
double ars=a*a;
return ars;
double calcper()
double per=2*a;
return per;
}}
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);
return art;
double calcper()
return 0;
} };
class Classhierarchy
c.display();
sq.display();
t.display();
}}
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.
class Bank
int getRateOfInterest()
return 0;
int getRateOfInterest()
return 8;
int getRateOfInterest()
return 7;
int getRateOfInterest()
return 9;
class Test{
o/p:
class Sup
int x;
this.x=x;
void display()
}}
int y;
sub(int x,int y)
super(x);
this.y=y;
void display()
}}
class TestOverride
obj.display();
}}
o/p:
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.
Program:
Square(double side)
length=side;
return length*length;
}}
Circle(double radius)
length=radius;
return PI*length*length;
}}
Shape sh;
sh=sq;
sh=circ;
}}
o/p:
class Bank
int getRateOfInterest()
return 0;
int getRateOfInterest()
return 8;
int getRateOfInterest()
return 7;
int getRateOfInterest()
return 9;
class DynamicDispatch{
o/p:
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.
}}
}}
class VehicleDemo
v.wheels();
v.seating();
v.brakes();
v1.wheels();
v1.seating();
v1.brakes();
}}
o/p:
int length;
int width;
length=a;
this.width=width;
super(length,width);
void area()
int height;
super(length,width);
this.height=height;
void area()
void volume()
class Mainforshape
r.area();
c.area();
c.volume();
Shape s;
s=r;
s.area();
s=c;
s.area();
o/p:
VIII) 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 pack;
import pack.Sum;
class PackDemo
s.getSum(10,20);
}}
o/p:
2) write a java package for book class and then import and display the result.
package packagetest;
int book_no,book_id,book_pages;
book_no=a;
book_id=b;
book_pages=c;
import packagetest.Book;
class BookReader
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.
package mathematics;
return(n*n*n);
return(n*n*n);
return(n*n*n);
return(n*n*n);
import mathematics.Mathmethods;
//import java.io.*;
import java.util.Scanner;
class Cube
//int a=20;
int a=m.nextInt();
int b = Mathmethods.Cube(a);
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.
import java.lang.*;
import java.io.*;
interface Exam
void percent_cal();
class Student
String name;
int roll_no,mark1,mark2;
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
void display()
}}
super(n,r,m1,m2);
int total=(mark1+mark2);
float percent=total*100/200;
void display()
super.display();
}}
class MultipleInheritenceDemo
R.display();
R.percent_cal();
}}
o/p:
class Super
static int b;
int c=100;
void display()
System.out.println("Static Variable="+b);
s.display();
}}
o/p:
import java.lang.*;
class Error2
int a=10;
int b=5;
int c=5;
int x,y;
try
x=a/(b-c);
catch (ArithmeticException e)
System.out.println("division by zero");
y=a/(b+c);
System.out.println("y=" +y);
o/p:
class ExcHandling
int a[]={5,10};
int b=5;
try
int x=a[2]/(b-a[0]);
catch(ArithmeticException e)
System.out.println("div by zero");
catch(ArrayIndexOutOfBoundsException e)
int y=a[1]/a[0];
o/p:
import java.lang.Exception;
class ExHan2
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;
continue;
count=count +1;
o/p:
InsufBalance(String s)
super(s);
class Mainbalance
int bal=5000;
try
int withdraw=Integer.parseInt(s[0]);
if(bal<withdraw)
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:
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)
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.
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:
int i;
for(i=0;i<5;i++);
System.out.println(this.getName()+" "+i);
d.setName("\nDAEMON THREAD");
d1.setName("NORMAL THREAD");
d.setPriority(Thread.MIN_PRIORITY);
d.start();
d1.start();
o/p:
class Addition
int a=99,b=1;
System.out.println("c="+(a+b));
try
Thread.sleep(3000);
System.out.println("After Sleep()");
catch (InterruptedException e)
Addition obj1;
public Synchro(Addition a)
obj1=a;
t1.start();
t2.start();
t3.start();
obj1.add();
System.out.println("ThreadNameis"+Thread.currentThread(). getName());
class TestSynchro
o/p:
for(int i=0;i<20;i++)
System.out.println(getName()+":"+i);
System.out.println("main started");
td.setName("Thread1");
td1.setName("Thread2");
td.start();
td1.start();
td.yield();
System.out.println("Main Exited");
o/p:
import java.util.StringTokenizer;
import java.io.*;
class StringTockenizerDemo
String str=br.readLine();
int a,sum=0;
String s;
while(st.hasMoreTokens())
s=st.nextToken();
a=Integer.parseInt(s);
sum=sum+a;
o/p:
import java.io.*;
System.out.println("Start A");
System.out.println("Exit A");
System.out.println("Start B");
System.out.println("Exit B");
System.out.println("Start C");
System.out.println("Exit C");
System.out.println("Start D");
System.out.println("Thread A l :"+l);
System.out.println("Exit D");
}}
class threadtest
{ new A().start();
new B().start();
new C().start();
new D().start();
}}
o/p:
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.
import java.io.*;
class FileOutput
{
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");
o/p:
import java.io.*;
class WriteBytes
byte cities[]={'D','E','L','H','I','\n','C','H','E','N','N','A','I','\n','L','O','N','D','O','N','\n'};
FileOutputStream outfile=null;
try
outfile=new FileOutputStream("city.txt");
outfile.write (cities);
outfile.close( );
catch(IOException ioe)
System.out.println(ioe);
System.exit(-1);
o/p:
import java.io.*;
class CopyBytes
FileInputStream infile=null;
FileOutputStream outfile=null;
byte byteRead;
try
outfile=new FileOutputStream("out.dat");
do
byteRead=(byte)infile.read( );
outfile.write(byteRead);
while(byteRead !=-1);
catch(FileNotFoundException e)
catch(IOException e)
System.out.println(e.getMessage( ));
try
infile.close( );
outfile.close( );
catch(IOException e)
{ }
o/p:
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.
import java.awt.*;
import java.applet.*;
int a=100;
int b=200;
g.drawString( s, 200,100);
}}
o/p:
import java.awt.*;
import java.applet.*;
g.drawString("Hello World",20,20);
g.drawRect(40,40,30,50);
g.drawOval(150,150,40,50);
}}
o/p:
import java.awt.*;
import java.applet.*;
Thread t ;
boolean b;
setBackground(Color.gray);
setForeground(Color.yellow);
t = new Thread(this);
b = false; t.start();
char ch;
for( ; ; )
try
repaint();
Thread.sleep(250);
ch = str.charAt(0);
catch(InterruptedException e)
{}
g.drawRect(1,1,300,150);
g.setColor(Color.green);
g.fillRect (1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}}
o/p:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
class Ball
int x,y,radius,dx,dy;
Color BallColor;
this.x=x;
this.y=y;
this.radius=radius;
this.dx=dx;
this.dy=dy;
BallColor=bColor;
}}
Ball redBall;
redBall=new Ball(250,80,50,2,4,Color.red);
t.start();
g.setColor(redBall.BallColor);
setBackground(Color.pink);
//g.setcolor(redBall.BallColor);
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);
{ while(true)
try
displacementOperation(redBall);
Thread.sleep(20);
repaint();
catch(Exception e)
ball.dy=-ball.dy; } ball.y=ball.y+ball.dy;
o/p:
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
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
5. {
6. Button b;
7. TextField tf;
9. {
11. tf.setBounds(30,40,150,20);
12.
14. b.setBounds(80,150,60,50);
15.
16. add(b);add(tf);
17. b.addActionListener(this);
18.
19. setLayout(null);
20. }
21.
23. {
24. tf.setText("Welcome");
25. }
26. }
In the above example, we have created all the controls in init() method because it is invoked only
once.
myapplet.html
1. <html>
2. <body>
4. </applet>
5. </body>
6. </html>
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet
{
static final int n = 4;
public void init()
{
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
Output:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
3) Write a Java program to demonstrate an application involving GUI with controls menus and
event handling.
import javax.swing.*;
public SwingMenu()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
filemenu.add(new JSeparator());
editmenu.add(new JSeparator());
fileItem3.add(new JSeparator());
editItem2.add(new JSeparator());
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);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}}
o/p: