You are on page 1of 37

INDIRA GANDHI NATIONAL OPEN

UNIVERSITY
IGNOU

JAVA PROGRAMMING LAB


LABORATORY RECORD BOOK

FOR
BCA COURSE
(BACHELOR OF COMPUTER APPLICATIONS)

For the year 2015

IGNOU

INDIRA GANDHI NATIONAL OPEN


UNIVERSITY
IGNOU

NAME:
Address:
Phone No:
Enrolment No:
Program Title:

BACHELOR OF COMPUTER APPLICATIONS (BCA)

Course Title:

JAVA PROGRAMMING LAB

Semester:

FOUR

Course Code:

BCSL-043

Study Centre:

SACRED HEART COLLEGE, THEVARA

Study Centre Code: 1402


Certified this is the bonafide record for the practicals done with
regard to the above mentioned course and program.

External Examiner
Internal in Charge

IGNOU

CONTENTS
SL.
No

PROGRAM DESCRIPTION

Write a Java Program to define a class, describe its constructor,


overload the constructors and instantiate its object.
Write a Java Program to define a class, define instance methods and
2
overload them and use them for dynamic method invocation.
3
Write a Java Program to demonstrate use of nested class.
Write a Java program to demonstrate usage of String class and its
4
methods.
5
Write a Java Program to implement Vector class and its methods.
Write a Java Program to implement inheritance and demonstrate
6
use of method overriding.
Write a Java Program to implement multilevel inheritance by
7
applying various access controls to its data members and methods.
Write a Java program to demonstrate use of implementing
8
interfaces.
Write Java a program to implement the concept of threading by
9
extending Thread Class.
Write Java a program to implement the concept of Exception
10
Handling by creating user defined exceptions.
Write Java a program using Applet to display a message in the
11
Applet.
Write a Java Program using Applet to demonstrate Keyboard
12
events.
Write a Java Program to display multiplication table of any
13
number.
14 Write a Java program using Applet to create a simple calculator.
Write a Java program to implement matrix operations addition,
15
subtraction, multiplication and transpose.
16 Write a Java program using Applet to create paint like application.
Write a Java program to create a Player class. Inherit the classes
17 Cricket_Player, Football_Player and Hockey_Player from Player
class.
Program: 1
1

PAGE
No.
4
6
7
8
10
12
13
15
16
18
19
20
22
23
26
29
35

Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object :
import java.lang.*;
class studentdemo
{
public static void main(String arg[])
{
student s1=new student();
student s2=new student("JOHN",34266,58,96,84);
IGNOU

student s3=new student(s1);


s1.display();
s2.display();
s3.display();

}
class student
{
String name;
int regno;
int marks1,marks2,marks3;
// null constructor
student()
{
name="RAJU";
regno=12345;
marks1=56;
marks2=47;
marks3=78;
}
// parameterized constructor
student(String n,int r,int m1,int m2,int m3)
{
name=n;
regno=r;
marks1=m1;
marks2=m2;
marks3=m3;
}
// copy constructor
student(student s)
{
name=s.name;
regno=s.regno;
marks1=s.marks1;
marks2=s.marks2;
marks3=s.marks3;
}

}
IGNOU

void display()
{
System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t" +marks2+ "\t" +
marks3);
}

OUTPUT

Program: 2
Write a Java Program to define a class, define instance methods and overload them and
use them for dynamic method invocation.
import java.lang.*;
class add_demo
{
public static void main(String arg[])
{
add obj=new add();
IGNOU

obj.display(10,20);
obj.display(10.2,20.2);

}
}
class add
{
void display(int a,int b)
{
int c=a+b;
System.out.println("THE SUM OF " + a + " & " + b + " IS " + c);
}
void display(double a,double b)
{
double c=a+b;
System.out.println("THE SUM OF " + a + " & " + b + " IS " + c);
}
}
OUTPUT

Program: 3
Write a Java Program to demonstrate use of nested class.
import java.lang.*
class outer
{
int m=10;
class inner
{
int n=20;
IGNOU

void display()
{
System.out.println("m = "+m);
System.out.println("n = "+n);
}
}
}
class nesteddemo
{
public static void main(String arg[])
{
outer outobj=new outer();
outer.inner inobj=outobj.new inner();
inobj.display();
}
}
OUTPUT

Program: 4
Write a Java program to demonstrate usage of String class and its methods.
import java.lang.String;
class stringdemo
{
public static void main(String arg[])
{
String s1=new String("sacret heart college");
String s2="SACRET HEART COLLEGE";
IGNOU

System.out.println(" The string s1 is : " +s1);


System.out.println(" The string s2 is : " +s2);
System.out.println(" Length of the string s1 is : " +s1.length());
System.out.println(" The first accurence of r is at the position : "
+s1.indexOf('r'));
System.out.println(" The String in Upper Case : " +s1.toUpperCase());
System.out.println(" The String in Lower Case : " +s1.toLowerCase());
System.out.println(" s1 equals to s2 : " +s1.equals(s2));
System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
if(result==0)
System.out.println( s1 + " is equal to "+s2);
else if(result>0)
System.out.println( s1 + " is greater than to "+s2);
else
System.out.println( s1 + " is smaller than to "+s2);
System.out.println(" Character at an index of 4 is :" +s1.charAt(4));
String s3=s1.substring(4,12);
System.out.println(" Extracted substring is :"+s3);
System.out.println(" After Replacing e with i in s1 : " + s1.replace('e','i'));
String s4=" This is a book ";
System.out.println(" The string s4 is :"+s4);
System.out.println(" After trim() :"+s4.trim());
}

OUTPUT

IGNOU

Program: 5
IGNOU

Write a Java Program to implement Vector class and its methods .


import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class vectordemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("ONE");
v.addElement("TWO");
v.addElement("THREE");
v.insertElementAt("ZERO",0);
v.insertElementAt("OOPS",3);
v.insertElementAt("FOUR",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector Capacity :"+v.capacity());
System.out.println("The elements of vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object OOPS is found at position :
"+v.indexOf("OOPS"));
v.removeElement("OOPS");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
}

OUTPUT
IGNOU

10

Program: 6

IGNOU

11

Write a Java Program to implement inheritance and demonstrate use of method


overriding.
import java.lang.*;
class AB
{
public static void main(String arg[])
{
B obj=new B();
obj.display();
}
}
class A
{
void display()
{
System.out.println("This is from class A ");
}
}
class B extends A
{
void display()
{
System.out.println("This is from class B ");
}
}
OUTPUT

Program: 7
IGNOU

12

Write a Java Program to implement multilevel inheritance by applying various access


controls to its data members and methods.
import java.io.DataInputStream;
class MultilevelDemo
{
public static void main(String arg[])
{
Result r=new Result();
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}
}
class Student
{
private int rollno;
private String name;
DataInputStream dis=new DataInputStream(System.in);
public void getrollno()
{
try
{
System.out.println("Enter ROLL NO. ");
rollno=Integer.parseInt(dis.readLine());
System.out.println("Enter NAME ");
name=dis.readLine();
}
catch(Exception e){ }
}
void putrollno()
{
System.out.println("ROLL NO ="+rollno);
System.out.println("NAME ="+name);
}
}
class Marks extends Student
{
protected int m1,m2,m3;
void getmarks()
{
try
{
System.out.println("Enter MARKS of three subjects :");
m1=Integer.parseInt(dis.readLine());
m2=Integer.parseInt(dis.readLine());
m3=Integer.parseInt(dis.readLine());
}
IGNOU

13

catch(Exception e) { }
}
void putmarks()
{
System.out.println("Mark of Subject 1 = "+m1);
System.out.println("Mark of Subject 2 = "+m2);
System.out.println("Mark of Subject 3 = "+m3);
}

}
class Result extends Marks
{
private float total;
void compute_display()
{
total=m1+m2+m3;
System.out.println("TOTAL MARKS :" +total);
}
}
OUTPUT

Program: 8

IGNOU

14

Write a program to demonstrate use of implementing interfaces.


import java.lang.*;
class interfacedemo
{
public static void main(String a[])
{
rectangle rect=new rectangle();
circle cir=new circle();
Area A;
A=rect;
System.out.println("Area of rectangle="+A.compute(10,20));
A=cir;
System.out.println("Area of circle="+A.compute(30,0));
}
}
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements Area
{
public float compute(float x,float y)
{
return(pi*x*y);
}
}
class circle implements Area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
OUTPUT

Program: 9

IGNOU

15

Write a program to implement the concept of threading by extending Thread Class.


import java.lang.Thread;
class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}
class A extends Thread
{
public void run()
{
System.out.println("THREAD 'A' STARTED:");
for(int i=1;i<=5;i++)
{
System.out.println("\t FROM THREAD 'A' : i = "+i);
}
System.out.println("EXIT FROM THREAD 'A':");
}
}
class B extends Thread
{
public void run()
{
System.out.println("THREAD 'B' STARTED:");
for(int j=1;j<=5;j++)
{
System.out.println("\t FROM THREAD 'B' : j = "+j);
}
System.out.println("EXIT FROM THREAD 'B':");
}
}
class C extends Thread
{
public void run()
{
System.out.println("THREAD 'C' STARTED:");
for(int k=1;k<=5;k++)
{
System.out.println("\t FROM THREAD 'C': k = "+k);
}
System.out.println("EXIT FROM THREAD 'C':");
}
}
OUTPUT
IGNOU

16

Program: 10

IGNOU

17

Write a program to implement the concept of Exception Handling using predefined


exception.
import java.lang.*;
class Exception_handle
{
public static void main(String argv[])
{
int a=10,b=5,c=5,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);
}
}
OUTPUT

Program: 11
IGNOU

18

Write a program using Applet to display a message in the Applet.


import java.applet.*;
import java.awt.Graphics;
/* <applet code="Appletdemo.class" width=300 height=300> </applet> */
public class Appletdemo extends Applet
{
public void paint(Graphics g)
{
String msg="HELLO!, Welcome to my applet ";
g.drawString(msg,80,150);
}
}
OUTPUT

Program: 12
IGNOU

19

Write a Java Program to demonstrate Keyboard events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KEY EVENTS....READY--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.yellow);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
IGNOU

20

}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
OUTPUT

Program: 13
IGNOU

21

Write a Java Program to display multiplication table of any number.


import java.util.Scanner;
class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("ENTER AN INTEGER TO PRINT IT'S MULTIPLICATION
TABLE: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("MULTIPLICATION TABLE OF "+n+" IS : ");
for ( c = 1 ; c <= 10 ; c++ )
System.out.println(n+" * "+c+" = "+(n*c));
}
}
OUTPUT

Program: 14
IGNOU

22

Write a Java applet program to create a simple calculator. This calculator should
perform +, , *, /. You need to take care of exceptions handling properly in this
program.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
IGNOU

23

add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
IGNOU

24

OP='%';
t1.setText("");

}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}

}
OUTPUT

Program: 15
IGNOU

25

Write a Java program to implement matrix operations addition, subtraction,


multiplication and transpose.
class matrix
{
public static void main(String args[])
{
int i,j,k;
int matrix1 [] []={{1,2,3},{4,5,6},{7,8,9}};
int matrix2 [][]={{10,11,12},{13,14,15},{16,17,18}};
//Matrix A
System.out.println("\n Matrix A:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
System.out.print("\t"+matrix1[i][j]);
System.out.println(" ");
}
//Matrix B
System.out.println("\n Matrix B:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
System.out.print("\t"+matrix2[i][j]);
System.out.println(" ");
}
System.out.println("\n MATRIX OPERATIONS AND RESULTS:");
System.out.println("\n 1. Addition: \n");
int sum [][] = new int [3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum[i][j]=matrix1[i][j]+matrix2[i][j];
System.out.print("\t"+sum[i][j]);
}
System.out.println(" ");
}
System.out.println("2. Substraction");
int diff[][]=new int[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
diff[i][j]=matrix1[i][j]-matrix2[i][j];
IGNOU

26

System.out.print("\t"+diff[i][j]);
}
System.out.println(" ");

}
System.out.println("3. Transpose");
int trans[][]=new int[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
trans[i][j]=matrix1[j][i];
System.out.print("\t"+trans[i][j]);
}
System.out.println(" ");
}
System.out.println("4. Multiplication: ");
int prod[][]=new int[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
prod[i][j]=0;
{
for(k=0; k<3; k++)
prod[i][j]=prod[i][j]+matrix1[i][k]*matrix2[k][j];
}
System.out.print("\t"+prod[i][j]);
}
System.out.println(" ");
}

OUTPUT
IGNOU

27

Program: 16
IGNOU

28

Write a Java program using applet to create paint like application.


import java.awt.event.*;
import java.awt.*;
import java.applet.*;
import java.util.Vector;
public class DrawTest extends Applet
{
DrawPanel panel;
DrawControls controls;
public void init()
{
setLayout(new BorderLayout());
panel = new DrawPanel();
controls = new DrawControls(panel);
add("Center", panel);
add("South",controls);
}
public void destroy()
{
remove(panel);
remove(controls);
}
public static void main(String args[])
{
Frame f = new Frame("DrawTest");
DrawTest drawTest = new DrawTest();
drawTest.init();
drawTest.start();
f.add("Center", drawTest);
f.setSize(300, 300);
f.show();
}
public String getAppletInfo()
{
return "A simple drawing program.";
}
}
class DrawPanel extends Panel implements MouseListener, MouseMotionListener
{
public static final int LINES = 0;
public static final int POINTS = 1;
int mode = LINES;
Vector lines = new Vector();
Vector colors = new Vector();
int x1,y1;
int x2,y2;
public DrawPanel()
IGNOU

29

{
setBackground(Color.white);
addMouseMotionListener(this);
addMouseListener(this);

}
public void setDrawMode(int mode)
{
switch (mode)
{
case LINES:
case POINTS:
this.mode = mode;
break;
default:
throw new IllegalArgumentException();
}
}
public void mouseDragged(MouseEvent e)
{
e.consume();
switch (mode)
{
case LINES:
x2 = e.getX();
y2 = e.getY();
break;
case POINTS:
default:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x1 = e.getX();
y1 = e.getY();
break;
}
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
e.consume();
switch (mode)
{
case LINES:
x1 = e.getX();
y1 = e.getY();
x2 =-1;
break;
case POINTS:
IGNOU

30

default:
colors.addElement(getForeground());
lines.addElement(new Rectangle(e.getX(), e.getY(),-1,-1));
x1 = e.getX();
y1 = e.getY();
repaint();
break;
}
}
public void mouseReleased(MouseEvent e)
{
e.consume();
switch (mode)
{
case LINES:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x2 =-1;
break;
case POINTS:
default:
break;
}
repaint();
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void paint (Graphics g)
{
int np = lines.size();
/* draw the current lines */
g.setColor(getForeground());
for (int i=0; i < np; i++)
{
Rectangle p = (Rectangle)lines.elementAt(i);
g.setColor((Color)colors.elementAt(i));
if (p.width !=-1)
{
g.drawLine(p.x, p.y, p.width, p.height);
}
else
{
g.drawLine(p.x, p.y, p.x, p.y);
IGNOU

31

}
}
if (mode == LINES)
{
g.setColor(getForeground());
if (x2 !=-1)
{
g.drawLine(x1, y1, x2, y2);
}
}

}
class DrawControls
extends Panel implements ItemListener
{
DrawPanel target;
public DrawControls(DrawPanel target)
{
this.target = target;
setLayout(new FlowLayout());
setBackground(Color.lightGray);
target.setForeground(Color.red);
CheckboxGroup group = new CheckboxGroup();
Checkbox b;
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.red);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.green);
add(b = new Checkbox(null,group, false));
b.addItemListener(this);
b.setForeground(Color.blue);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.pink);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.orange);
add(b = new Checkbox(null, group, true));
b.addItemListener(this);
b.setForeground(Color.black);
target.setForeground(b.getForeground());
Choice shapes = new Choice();
shapes.addItemListener(this);
shapes.addItem("Lines");
shapes.addItem("Points");
shapes.setBackground(Color.lightGray);
add(shapes);
IGNOU

32

}
public void paint(Graphics g)
{
Rectangle r = getBounds();
g.setColor(Color.lightGray);
g.draw3DRect(0, 0, r.width, r.height, false);
int n = getComponentCount();
for(int i=0; i<n; i++)
{
Component comp = getComponent(i);
if (comp instanceof Checkbox)
{
Point loc = comp.getLocation();
Dimension d = comp.getSize();
g.setColor(comp.getForeground());
g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1);
}
}
}
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() instanceof Checkbox)
{
target.setForeground(((Component)e.getSource()).getForeground());
}
else if (e.getSource() instanceof Choice)
{
String choice = (String) e.getItem();
if (choice.equals("Lines"))
{
target.setDrawMode(DrawPanel.LINES);
}
else if (choice.equals("Points"))
{
target.setDrawMode(DrawPanel.POINTS);
}
}
}

OUTPUT
IGNOU

33

Program 17
IGNOU

34

Write a program in Java to create a Player class. Inherit the classes Cricket_Player,
Football_Player and Hockey_Player from Player class.
class main_player
{
public static void main (String args[])
{
cricket_player c=new cricket_player("AMEER","CRICKET",25);
football_player f=new football_player("ARUN", "FOOTBALL", 28);
hockey_player h=new hockey_player("RAM","HOCKEY",24);
c.show();
f.show();
h.show();
}
}
class player
{
String name;
int age;
player(String n, int a)
{
name=n;
age=a;
}
void show()
{
System.out.println("\n");
System.out.println("Player name: "+name);
System.out.println("Age :"+age);
}
}
class cricket_player extends player
{
String type;
cricket_player (String n, String t, int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type :"+type);
}
}
class football_player extends player
IGNOU

35

String type;
football_player (String n, String t, int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}

class hockey_player extends player


{
String type;
hockey_player (String n, String t, int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}

OUTPUT
IGNOU

36

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

IGNOU

37

You might also like