OOP Lab Manual
OOP Lab Manual
LAB OBJECTIVE
1. Ability to learn and understand the concepts and features of object oriented
programming and the object oriented concept like inheritance and will know how to
a) Constructor
b) Parameterized constructor
c) Method overloading
d) Constructor overloading
a)Constructor is a block of code that initializes the newly created object. A constructor resembles
an instance method in java but it’s not a method as it doesn’t have a return type. In short
constructor and method are different(More on this at the end of this guide). People often refer
constructor as special type of method in Java.
Program:
Output:
BeginnersBook.com
b)
class Example{
//Default constructor
Example(){
System.out.println("Default constructor");
}
/* Parameterized constructor with
* two integer arguments
*/
Example(int i, int j){
Output:
Default constructor
constructor with Two parameters
constructor with Three parameters
constructor with int and String param
c)
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
add(int, float)
add(float, int)
Pgm:
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
d) Constructor Overloading:
class StudentData
{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
System.out.println("Student Name is: "+myobj.getStuName());
System.out.println("Student Age is: "+myobj.getStuAge());
System.out.println("Student ID is: "+myobj.getStuID());
a)
Program:
import java.util.Scanner;
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
OutPut:
Enter a string:
radar
radar is a palindrome
b)
class sorting
{
public static void main(String[] input)
{
int k=input.length;
String temp=new String();
String names[]=new String[k+1];
for(int i=0;i<k;i++)
{
names[i]=input[i];
}
for(int i=0;i<k;i++)
for(int j=i+1;j<k;j++)
{
if(names[i].compareTo(names[j])<0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
System.out.println(“Sorted order is”);
for(int i=0;i<k;i++)
{
System.out.println(names[i]);
}
}
}
OutPut:
sandeep
sai
ravi
hari
c) That reads a line if integers and then displays each integer and the sum of all integers
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
class StringTokenizerEx
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Scanner objScanner = new Scanner(System.in);
System.out.print("\nEnter A Line Of Integers:");
//String line = objScanner.nextLine();
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
System.out.println("\nNumber of tokens : "+st.countTokens());
long sum = 0;
System.out.print("\nTokens are : \n" );
while (st.hasMoreTokens())
{
long i = Long.parseLong(st.nextToken());
System.out.print(i + "\n");
sum = sum + i;
}
System.out.println("\nThe Sum Is :" +sum);
}
}
Output:
Number of tokens: 4
Tokens are:
1 4 23 2
The sum is : 30
a) this
b) super
c) static
d) final
a)
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
OUTPUT :
0 null 0.0
0 null 0.0
b)
class Superclass
{
int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
/* The same variable num is declared in the Subclass
* which is already present in the Superclass
*/
int num = 110;
void printNumber(){
System.out.println(num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output:
110
c)
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
Output:
111 Karan ITS
222 Aryan ITS
d)
class Gfg
{
public static void main(String[] args)
{
// a final reference variable sb
final StringBuilder sb = new StringBuilder("Geeks");
System.out.println(sb);
System.out.println(sb);
}
}
Output:
Geeks
GeeksForGeeks
a) Method Overloading
c) multiple inheritance
d) access specifiers
a)
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
b)
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
}
}
OUTPUT:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
C) Multiple Inheritance
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the baseclass, and the new class is referred to as
the derived class.
A derived class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived classes should be
declared private in the base class.
Program code:
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
Output:
Total area 35
Program code:
/* Program for multiple inheritance*/
#include <iostream>
using namespace std;
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
Output:
Total area: 35
Total paint cost: $2450
d)
Access specifier
Java has defined four types of access specifiers. These are :
1. Public
2. Private
3. Protected
4. Default
package xyz;
import abc.AccessDemo;
package abc;
class AccessDemo
{
default int a = 4;
}
package xyz;
import abc.AccessDemo;
class AccessExample
{
public static void main(String[] args)
{
AccessDemo ad = new AccessDemo();
ad.a = 67; //It is not possible.
}
}
class AccessDemo
{
protected int x = 34;
a)
import java.io.*;
import java.util.*;
class AboutFile{
if(f.exists())
System.out.println("The file " +file_name+ " exists");
else
System.out.println("The file " +file_name+ " does not exist");
if(f.exists()){
if(f.canRead())
System.out.println("The file " +file_name+ " is readable");
else
System.out.println("The file " +file_name+ " is not readable");
if(f.canWrite())
System.out.println("The file " +file_name+ " is writeable");
else
System.out.println("The file " +file_name+ " is not writeable");
}
}
b)
import java.io.*;
class linenum
{
public static void main(String[] args)throws IOException
{
FileInputStream fil;
LineNumberInputStream line;
int i;
try
{
fil=new FileInputStream(args[0]);
line=new LineNumberInputStream(fil);
}
catch(FileNotFoundException e)
{
System.out.println("No such file found");
return;
}
do
{
i=line.read();
if(i=='\n')
{
System.out.println();
System.out.print(line.getLineNumber()+" ");
}
else
System.out.print((char)i);
}while(i!=-1);
fil.close();
line.close();
}
}
Output:
Demo.java
class Demo
1{
2 public static void main(java Demo beta gamma delta)
3{
4 int n = 1 ;
5 System.out.println(“The word is ” + args[ n ] );
6}
C)
import java.io.*;
class wordcount
{
Output:This is II CSE
1 4 32
a) Predefined Exception: The most general of exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
class Ex1
{
void div()
{
int b=10/0;
}
void div1()
{
div();
}
void div2()
{
try
{
div();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
Ex1 e=new Ex1();
e.div2();
}
}
O/P:
Java.lang..ArithmeticException:/by zero
User defined Exception: If you are creating your own Exception that is known as custom
exception or user-defined exception. Java custom exceptions are used to customize the exception
according to user need.
O/P:
MyException
a) Creates three threads. First threads displays “Good Morning “for every one Second, the
second thread displays “Hello” for every two seconds, the third thread Displays “Welcome” for
every three seconds.
b) that correctly implements producer consumer problem using concept of inter
thread communication
a)
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{}
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{}
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
Output:
E:\javamani>java ThreadDemo
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
hello
welcome
good morning
b)
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
Output:
Put:0
Got:0
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
b)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
else
fact=-1;
}
repaint();
}
public void paint(Graphics g)
{
if(fact==-1) {
output.setText("0");
g.drawString("Sorry number exceeds greater than 12",10,100); }
}
}
Output:
9. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +,-,*,/ operations. Add a text field to display the result.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Calculator1" width=300 height=300></applet>*/
public class Calculator1 extends Applet implements ActionListener
{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}
for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
String str=ae.getActionCommand();
if(str.equals("+")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("=")) { str1="";
if(oper.equals("+")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}
else if(oper.equals("-")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q))); }
else if(oper.equals("*")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q))); }
else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
}
else{ t.setText(str1.concat(str));
str1=t.getText();
}
Output:
a)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
b) Key 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="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
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");
}
11. Write a Java program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields num1 and num2. The division of num1 and num2 is
displayed on the result field when the divide button is clicked. If num1 and num2 were not an
integer, the program would throw number format exception. If num2 was zero , the program
would throw an arithmetic exception and display the exception in message dialogue box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Div"width=230 height=250>
</applet>*/
public class Div extends Applet implements ActionListener
{
String msg;
TextField num1,num2,res;Label l1,l2,l3;
Button div;
public void init()
{
l1=new Label("Number 1");
l2=new Label("Number 2");
l3=new Label("result");
num1=new TextField(10);
num2=new TextField(10);
res=new TextField(10);
div=new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("DIV"))
{
String s1=num1.getText();
String s2=num2.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);
if(num2==0)
{
try
{
System.out.println(" ");
}
catch(Exception e)
{
System.out.println("ArithematicException"+e);
}
msg="Arithemetic";
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println("");
}
catch(Exception e)
{
System.out.println("NumberFormat"+e);
}
msg="NumberFormat";
repaint();
}
else
{
int num3=num1/num2;
res.setText(String.valueOf(num3));
}
}
}
public void paint(Graphics g)
{
g.drawString(msg,30,70);
}
}
Output
a)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Signals" width=400 height=250></applet>*/
public class Signals extends Applet implements ItemListener
{
String msg="";
Checkbox stop,ready,go;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
stop = new Checkbox("Stop", cbg, false);
ready = new Checkbox("Ready", cbg, false);
go= new Checkbox("Go", cbg, false);
add(stop);
add(ready);
add(go);
stop.addItemListener(this);
ready.addItemListener(this);
go.addItemListener(this);
msg=cbg.getSelectedCheckbox().getLabel();
g.drawOval(165,40,50,50);
g.drawOval(165,100,50,50);
g.drawOval(165,160,50,50);
if(msg.equals("Stop"))
{
g.setColor(Color.red);
g.fillOval(165,40,50,50);
}
else if(msg.equals("Ready"))
{
g.setColor(Color.yellow);
g.fillOval(165,100,50,50);
}
else
{
g.setColor(Color.green);
g.fillOval(165,160,50,50);
}
}
}
Output:
b)
import java.awt.*;
import java.applet.*;
/*
<applet code="Sujith" width=200 height=200>
</applet>
*/
public class Sujith extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<=250;i++)
{
Color c1=new Color(35-i,55-i,110-i);
g.setColor(c1);
g.drawRect(250+i,250+i,100+i,100+i);
g.drawOval(100+i,100+i,50+i,50+i);
g.drawLine(50+i,20+i,10+i,10+i);
}
}
}
Output: