You are on page 1of 27

Adikavi Nannaya University

MSN Campus Kakinada

MCA I Year II Semester

Object Oriented Programming through


Java Lab
Manual

Prepared by
Md R Nadeem
Assistant Professor
Department of Computer Science
Adikavi Nannaya University MSN Campus, Kakinada
Index

S. No. Program Page No.

1 Java program to print quadratic roots using command line

arguments

2 Java program to print multiplication table using arrays

3 Java program to demonstrate method overloading concept

4 Java program to demonstrate Abstract Class

5 Java program to implement Hierarchical Inheritance

6 Java program to demonstrate multiple inheritance by using

Interface.

7 Java program that demonstrates Package in Java

(Java Package for book class and then import and display the

result)

8 Java Program to implement the concept of exception handling by

creating user defined exception

9 Java program to show multi-threaded application.

10 Applet program that finds the factorial of a number

11 Java program that handles all mouse events and shows the event

name at the centre of the window when a mouse event is fired

(Use Adapter classes)

12 Java Program that uses Swing components

2
//Program 1: Java program to print quadratic roots using command line arguments.

public class QuadraticRootsCommandLine


{
public static void main(String[] args)
{
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double c = Double.parseDouble(args[2]);
double root1, root2;
if(a==0)
System.out.println("Not a Quadratic Equation");
else
{
double determinant = b * b - 4 * a * c;
// condition for real and different roots
if(determinant > 0) {
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);
}
// Condition for real and equal roots
else if(determinant == 0) {
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}
// If roots are not real
else {
double realPart = -b / (2 *a);
double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart,
imaginaryPart);
}
}
}
}
3
//Program 2: Java program to print multiplication table using arrays
public class MulTableUsingArray
{
public static void main (String args[])
{
int MulTable[][]=new int[10][10];
int row=1,column=1;
for(int i=0; i<MulTable.length; i++)
{
for(int j=0; j<MulTable[i].length; j++)
{
MulTable[i][j]=row*column;
column=column+1;
}
row=row+1;
column=1;
}
for(int i=0; i<MulTable.length; i++){
for(int j=0; j<MulTable[i].length; j++){
System.out.print(" "+MulTable[i][j]+"\t| ");
}
System.out.print("\n");
}
}
}

4
//Program 3: Java program to demonstrate method overloading concept
class Box
{
int volume(int l,int b,int h)
{
return l*b*h;
}
double volume(double l,double b, double h)
{
return l*b*h;
}
}
public class UseBox
{
public static void main(String args[])
{
Box b=new Box();
System.out.println("Volume of a box with dimensions 6,5,3 is "+ b.volume(6,5,3));
System.out.println("Volume of a box with dimensions 6.2,5.6,3.9 is "+b.volume(6.2,5.6,3.9));
}
}

5
//Program 4: Java program to demonstrate Abstract Class
abstract class Shape
{
double dim1,dim2;
Shape(double dim1)
{
this.dim1=dim1;
}
Shape(double dim1, double dim2)
{
this.dim1=dim1;
this.dim2=dim2;
}
void show()
{
System.out.println("dim1:"+dim1+"\tdim2:"+dim2);
}
abstract double area();
}
class Rectangle extends Shape
{
Rectangle(double dim1, double dim2)
{
super(dim1,dim2);
}
double area()
{
System.out.print("Rectangle area:");
return dim1*dim2;
}
}
class Circle extends Shape
{
Circle(double dim1)
{
6
super(dim1);
}
void show()
{
System.out.println("dim1:"+dim1);
}
double area()
{
System.out.print("Area of Circle:");
return Math.PI*dim1*dim1;
}
}
class Triangle extends Shape
{
Triangle(double dim1,double dim2)
{
super(dim1,dim2);
}
double area()
{
System.out.print("Area of Triangle:");
return 0.5*dim1*dim2;
}
}
class UseShape
{
public static void main(String args[])
{
Shape p;
Rectangle r=new Rectangle(6.2,4.5);
Circle c=new Circle(5.8);
Triangle t=new Triangle(5.1,4.2);
p=r;
p.show();
System.out.println(p.area());
7
p=c;
p.show();
System.out.println(p.area());
p=t;
p.show();
System.out.println(p.area());
}
}

8
//Program 5: Program to implement Hierarchical Inheritance

class A
{
public void OverrideMethod()
{
System.out.println("Super class method");
}
}
class B extends A
{
public void OverrideMethod()
{
System.out.println("Sub class B's Overridden Method");
}
}
class C extends A
{
public void OverrideMethod()
{
System.out.println("Sub class C's Overridden Method");
}
}
public class ABC
{
public static void main(String args[])
{
A o;
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();

o=obj1;
o.OverrideMethod(); //calling super class method

9
o=obj2;
o.OverrideMethod(); //calling A method from subclass object

o=obj3;
o.OverrideMethod(); //calling A method from subclass object
}
}

10
//Program 6: Java program to demonstrate multiple inheritance by using Interface.
//A class can implement multiple interfaces. In this case the implementing class must define the
combined methods of all interfaces it implements
interface Call1
{
void callMe1();
}
interface Call2
{
void callMe2();
void callMe3();
}
class Client1 implements Call1,Call2
{
public void callMe1()
{
System.out.println("Call1 interface implemented by client");
System.out.println("Call1'1 callMe1()");
}
public void callMe2()
{
System.out.println("Call2 interface implemented by client");
System.out.println("Call2's callMe2()");
}
public void callMe3()
{
System.out.println("Call3 interface implemented by client");
System.out.println("Call3's callMe3()");
}
}
public class UseClient1
{
public static void main(String args[])
{
Client1 c=new Client1();
11
c.callMe1();
c.callMe2();
c.callMe3();

Call1 cc1=c;
Call2 cc2=c;
cc1.callMe1();
cc2.callMe2();
cc2.callMe3();
}
}

12
//Program 7: Java program that demonstrates Package in Java

//(Java Package for book class and then import and display the result)
//Create a folder “Book” in the current working folder and save the following file with in the Book folder

package book;

public class Book

String name;

String author;

double price;

public Book(String name,String author,double price)

this.name=name;

this. author=author;

this. price=price;

public void display()

System.out.println("Name of the Book:"+name);

System.out.println("Name of the Author:"+author);

System.out.println("Name of the Price:"+price);

//Create the following file in the parent of Book folder, import the package “book”

import java.util.Scanner;

import book.*;

public class UseBook

13
public static void main(String args[])

String name, author;

double price;

Scanner in=new Scanner(System.in);

System.out.println("Enter the name of the book");

name=in.nextLine();

System.out.println("Enter Author");

author=in.nextLine();

System.out.println("Enter Price");

price=in.nextDouble();

Book b=new Book(name,author,price);

b.display();

14
//Program 8: Program to implement the concept of exception handling by creating user
defined exception

class StackFullException extends Exception


{
StackFullException()
{
super("Stack Full");
}
public String toString()
{
return "Stack is full";
}
}
class StackEmptyException extends Exception
{
StackEmptyException()
{
super("Stack Empty");
}
public String toString()
{
return "Stack is empty";
}
}
class MyStack
{
int a[];
int top,size;
MyStack(int s)
{
a=new int[s];
size=s;
top=0;
}
15
public void push(int n) throws StackFullException
{
if(top>size-1)
throw new StackFullException();
a[top]=n;
top++;
}
public void pop() throws StackEmptyException
{
if(top==0)
throw new StackEmptyException();
top--;
System.out.println(a[top]);
}
}
public class StackTest
{
public static void main(String args[])
{
MyStack s=new MyStack(3);
try
{
s.push(10);
s.push(20);
s.push(30);
s.push(40);
}
catch(Exception e)
{
System.out.println(e.toString());
}
try
{
s.pop();
s.pop();
16
s.pop();
s.pop();
}
catch(StackEmptyException e)
{
//System.out.println(e);
System.out.println(e.toString());
}
}
}

17
//Program 9: Java program to show multi-threaded application

class ChildThread implements Runnable


{
String name;
Thread t;
ChildThread(String tname)
{
name=tname;
t=new Thread(this,name);
System.out.println("Child Thread-->"+t);
t.start();
}
public void run()
{
try
{
for(int i=1;i<=3;i++)
System.out.println(name+"-->"+i);
Thread.sleep(250);
}
catch(InterruptedException e)
{}
}
}
public class MultiThreadDemo
{
public static void main(String args[])
{
System.out.println("in the main");
ChildThread ct1=new ChildThread("One");
new ChildThread("Two");
new ChildThread("Three");
System.out.println("In the main again");
System.out.println("Child Thread ct1:"+ct1.t.isAlive());
18
try
{
for(int i=1;i<=3;i++)
System.out.println("Main Thread-->"+i);
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println("Main therad exiting");
System.out.println("Child Thread ct1:"+ct1.t.isAlive());
}
}

19
//Program 10: Applet program that finds the factorial of a number
/*
<applet code="Factorial.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Factorial extends Applet implements ActionListener
{
Button b;
TextField tf1,tf2;
public void init()
{
Button b=new Button("Calculate Factorial");
Label l1=new Label("Enter a Number:");
Label l2=new Label("Factorial of Number:");
tf1=new TextField(20);
tf2=new TextField(20);
b.addActionListener(this);
add(l1);
add(tf1);
add(l2);
add(tf2);
add(b);
}
public void actionPerformed(ActionEvent e)
{
int f=1;
String s=tf1.getText();
int n=Integer.parseInt(s);
if(n==0)
f=1;
else
for(int i=1;i<=n;i++)
20
f=f*i;
tf2.setText(Integer.toString(f));
}
}

21
//Program 11: Java program that handles all mouse events and shows the event name at the
center of the window when a mouse event is fired (Use Adapter classes)

// Mouse Events demo


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseEventsDemo" width=200 height=100>
</applet>
*/
public class MouseEventsDemo extends Applet
{
String str="";
public void init()
{
addMouseListener(new MyMouseAdapter());
addMouseMotionListener(new MyMouseMotionAdapter());
}
public void paint(Graphics g)
{
int h=this.getHeight();
int w=this.getWidth();
g.drawString(str,w/2,h/2);
}
class MyMouseAdapter extends MouseAdapter // Inner class
{
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
str="Mouse Clicked";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
22
{
str="Mouse Entered";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
str="Mouse Exited";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
str="Mouse Pressed";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
str="Mouse Released";
repaint();
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter // Inner class
{
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
str="Mouse Dragged";
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
str="Mouse Moved";
23
repaint();
}
}
}

24
//Program 12: Java program that uses Swing Components
import javax.swing.*;
import java.awt.*;
import java.awt. event.*;
public class SwingArithmeticOperations extends JFrame implements ActionListener
{
JButton compute=new JButton("Compute");
JTextField fn,sn,s,d,p,q,r;
public SwingArithmeticOperations()
{
super("Swing Components Demo");
Container c=getContentPane();
JLabel ao=new JLabel("Arithmetic Operations");
c.add(ao,"North");
JPanel tp=new JPanel();
tp.setLayout(new GridLayout(7,2));
fn=new JTextField();
sn=new JTextField();
s=new JTextField();
s.setEnabled(false);
d=new JTextField();
d.setEnabled(false);

p=new JTextField();
p.setEnabled(false);

q=new JTextField();
q.setEnabled(false);

r=new JTextField();
r.setEnabled(false);

tp.add(new JLabel("First Number"));


tp.add(fn);
tp.add(new JLabel("Second Number"));
25
tp.add(sn);
tp.add(new JLabel("SUM"));
tp.add(s);
tp.add(new JLabel("DIFFERENCE"));
tp.add(d);
tp.add(new JLabel("PRODUCT"));
tp.add(p);
tp.add(new JLabel("QUOTIENT"));
tp.add(q);
tp.add(new JLabel("REMAINDER"));
tp.add(r);
c.add(tp,"Center");
c.add(compute,"South");
compute.addActionListener(this);
setSize(500,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
int a=Integer.parseInt(fn.getText());
int b=Integer.parseInt(sn.getText());
String str=""+(a+b);
s.setText(str);
str=""+(a-b);
d.setText(str);
str=""+(a*b);
p.setText(str);
if(b==0)
{
str="Division not possible";
q.setText(str);
r.setText(str);
}
else
26
{
str=""+(a/b);
q.setText(str);
str=""+(a%b);
r.setText(str);
}
}
public static void main(String args[])
{
new SwingArithmeticOperations();
}
}

27

You might also like