ASHFAK JAVA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

DEPARTMENT OF COMPUTER SCIENCE G ENGINEERING

PRACTICAL COMPONENT OF

Object Oriented Programming With Java


COURSE CODE: BCS306A
III SEMESTER

STUDENT NAME: KA
MOHAMMAD ASHFA
USN: CS-DIP-03
ACADEMIC YEAR: 2024-2025

Course Material Prepared by Course Material Approved by


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

This is to Certify that Mr. / Miss. KA MOHAMMAD ASHFAK


USN CS-D IP -0 3
has satisfactorily completed the practical component of IPCC course

BCS306A, Object Oriented Programming With Java for the III

Semester B.E. Program during the Academic Year 2024-25.

Sessional Marks

Max. Marks: 25 Marks Awarded:


INDEX

Sl no Program name Page no Marks Staff signature


awarded

1 Develop a Java program to add matices of 1


suitable order N

2 Develop a program to illustrate stack 3


operations

3 Develop a program with a class called 7


employee and suitable main method for
demonstration

4 Develop a java program with class “My 9


point” which models a 2D point with x and y
coordinates

5 Develop a java program to demonstrate 13


polymorphism concepts

6 Develop a java program to create abstract 16


class with abstract methods

7 Develop a java program to demonstrate 19


interface concepts

8 Develop a java program to create an outer 21


class & inner class

9 Develop a java program to raise custom 22


exception using try,catch,throw,and finally

10 Develop a java program to create a package 26


& implement in a suitable class

11 Program to illustrate creation of threads 28

12 Program to create a class Mythread and call 29


the base class constructor using super.
OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 1:

Develop a JAVA program to add TWO matrices of suitable order N (The value
of N should be read from command line arguments).

package add;
import java.util.Scanner;
public class Add
{
public static void main(String[] args)
{
int m, n;
Scanner scan = new Scanner (System.in);
System.out.print(“Enter the number of rows in the matrix:”);
m = scan.nextInt();
System.out.print(“Enter the number of columns in the matrix:”);
n = scan.nextInt();
int a[][] = new int[m][n];
int b[][] = new int[m][n];
int c[][] = new int[m][n];
System.out.println(“Enter all the elements of first matrix:”);
for (int i = 0; i<m; i++)
{
for (int j = 0; j<n; j++)
{
a[i][j] = scan.nextInt();
}
}
System.out.println(“”);
System.out.println(“Enter all the elements of second matrix:”);
for (int i = 0; i<m; i++)
{
for (int j = 0; j<n; j++)
{
b[i][j] = scan.nextInt();
}
}

{
for (int j = 0; j<n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}

DEPARTMENT OF CSE, KVGCE SULLIA Page 1


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

System.out.println(“Matrix after addition:”);


for (int i = 0; i &lt; m; i++)
{
for (int j = 0; j &lt; n; j++)
{
System.out.print(c[i][j]+””);
}
System.out.println(“”);
}
}
}

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 2


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 2:

Develop a stack class to hold a maximum of 10 integers with suitable methods.


Develop a JAVA main method to illustrate Stack operations.

package stackdemo;
import java.util.Scanner;
class Stack
{
int s[]=new int[10];
int top=-1;
int size=3;
void push(int i)
{
if(top==size-1)
System.out.println("Stack Overflow");
else
{
s[++top]=i;
}
}
void pop()
{
if(top==-1)
{
System.out.println("Stack Underflow");

}
else

{
System.out.println("Popped Element="+s[top]);

DEPARTMENT OF CSE, KVGCE SULLIA Page 3


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

top--;
}
}
void display()
{
if(top==-1)
{
System.out.println("Stack is Empty\n");
}
else
{
System.out.println("Stack elements are:\n");
for(int i=top;i>=0;i--)
System.out.println(s[i]);
}
}
}
public class Stackdemo{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
Stack stk=new Stack();
for(;;)
{
System.out.println("\n----Stack Operstions ----- ");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Display");
System.out.println("4.Exit");
System.out.println("Enter your choice:\n");
int choice=scan.nextInt();
switch(choice)
{
DEPARTMENT OF CSE, KVGCE SULLIA Page 4
OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

case 1:
System.out.println("Enter the element to push");
stk.push(scan.nextInt());
break;
case 2:stk.pop();
break;
case 3:stk.display();
break;
case 4:System.exit(0);
default:
System.out.println("Invalid choice\n");
break;
}
}
}
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 5


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

DEPARTMENT OF CSE, KVGCE SULLIA Page 6


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 3:
A class called employee which models an employee with an ID, name and
salary, as shown in the following class diagram. The method raise
salary(percent) increases the salary by the given percentage. Develop the
employee class and suitable math method for demonstration.

package employeedemo1;
import java.util.*;
class Employee{
private int id;
private String name;
private double salary;
public Employee(int id,String name,double salary){
this.id=id;
this.name=name;
this.salary=salary;
}
public void raisesalary(double percent){
if(percent>0){
double raiseAmount=salary*(percent/100);
salary+=raiseAmount;
System.out.println(name+"'s salary raised by"+percent+"%New salary:"+salary);
}else{
System.out.println("Invalid percentage salary remains unchanged");
}
}
public String toString(){
return "Employee ID:"+id+"\n Name:"+name+"\n salary:"+salary;
}
}
public class EmployeeDemo1 {
public static void main(String[] args) {

DEPARTMENT OF CSE, KVGCE SULLIA Page 7


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

Scanner sc=new Scanner(System.in);


Employee emp=new Employee(1,"John Doe",50000.0);
System.out.println("Initial Employee Details:");
System.out.println(emp);
System.out.println("Enter the percentage to raise the salary:");
double percent=sc.nextDouble();
emp.raisesalary(percent);
System.out.println("\nEmployee Details after salary Raise:");
System.out.println (emp);
}
}

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 8


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 4:
A class called MyPoint, which models a 2D point with x and y coordinates, is
designed as follows:

● Two instance variables x (int) and y (int).

● A default (or "no-arg") constructor that construct a point at the default location
of (0,0).

● A overloaded constructor that constructs a point with the given x and y


coordinates.

● A method setXY() to set both x and y.

● A method getXY() which returns the x and y in a 2-element int array.

● A toString() method that returns a string description of the instance in the


format "(x,y)".

● A method called distance(int x, int y) that returns the distance from this point
to another point at the

given (x, y) coordinates

● An overloaded distance(MyPoint another) that returns the distance from this


point to the given MyPoint instance (called another)

● Another overloaded distance() method that returns the distance from this point
to the origin (0,0)

Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the

methods defined in the class

package pointdemo;

class MyPoints{

int x;

int y;

DEPARTMENT OF CSE, KVGCE SULLIA Page 9


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

public MyPoints()

this.x=0;

this.y=0;

public MyPoints(int m,int n)

this.x=m;

this.y=n;

public void setXY(int m,int n)

this.x=m;

this.y=n;

public int[] getXY()

int[] coordinates={this.x,this.y};

return coordinates;

public String toString()

return"(" +this.x +"," +this.y +")";

public double distance(int m,int n)

DEPARTMENT OF CSE, KVGCE SULLIA Page 10


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

int Xdiff=this.x-m;

int Ydiff=this.y-n;

return Math.sqrt(Xdiff*Xdiff+Ydiff*Ydiff);

public double distance(MyPoints another)

return distance(another.x,another.y);

public double distance()

return distance(0,0);

public class PointDemo {

public static void main(String[] args) {

MyPoints point1=new MyPoints();

MyPoints point2=new MyPoints(6,8);

System.out.println("point1:"+point1);

System.out.println("point2:"+point2);

point1.setXY(3,4);

System.out.println("point1 after setXY:"+point1);

int[] coordinates=point2.getXY();

System.out.println("coordinate of point2:("+coordinates[0]+","+coordinates[1]+")");

System.out.println("Distance between "+point1+"and (0,0):"+point1.distance());

DEPARTMENT OF CSE, KVGCE SULLIA Page 11


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

System.out.println("Distance between "+point1+"and"+point2+":"+point1.distance(point2));

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 12


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 5:

Develop a JAVA program to create a class named shape. Create three sub classes
namely: circle, triangle and square, each class has two member functions named
draw () and erase (). Demonstrate polymorphism concepts by developing
suitable methods, defining member data and main program. Shape.java

public class Shape


{
public void draw()
{
System.out.println(&quot;Drawing a shape&quot;);
}
public void erase()
{
System.out.println(&quot;Erasing a shape&quot;);
}
}
class Circle extends Shape
{
public void draw()
{
System.out.println(&quot;Drawing a circle&quot;);
}
public void erase()
{
System.out.println(&quot;Erasing a circle&quot;);
}
}
class Triangle extends Shape
{

DEPARTMENT OF CSE, KVGCE SULLIA Page 13


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

public void draw()


{
System.out.println(&quot;Drawing a triangle&quot;);
}
public void erase()
{
System.out.println(&quot;Erasing a triangle&quot;);
}
}
class Square extends Shape
{
Public void draw()
{
System.out.println(&quot;Drawing a square&quot;);
}
public void erase()
{
System.out.println(&quot;Erasing a square&quot;);
}
}
Class Main
{
public static void main(String[] args)
{
Circle c = new Circle();
Triangle t = new Triangle();
Square s = new Square();
System.out.println(&quot;Using Circle object:&quot;); c.draw(); c.erase();
System.out.println(&quot;\nUsing Triangle object:&quot;); t.draw(); t.erase();
System.out.println(&quot;\nUsing Square object:&quot;); s.draw(); s.erase();
}
}
DEPARTMENT OF CSE, KVGCE SULLIA Page 14
OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 15


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 6:

Develop a JAVA program to create an abstract class Shape with abstract


methods calculateArea() and calculatePerimeter(). Create subclasses Circle and
Triangle that extend the Shape class and implement the respective methods to
calculate the area and perimeter of each shape.

public abstract class Shape


{
public abstract double calculateArea();
public abstract double calculatePerimeter();
}
class Circle extends Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double calculateArea()
{
return Math.PI * Math.pow(radius, 2);
}
public double calculatePerimeter()
{
return 2 * Math.PI * radius;
}
}
class Triangle extends Shape
{
private double side1, side2, side3;
public Triangle(double side1, double side2, double side3)

DEPARTMENT OF CSE, KVGCE SULLIA Page 16


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double calculateArea()
{
double s = (side1 + side2 + side3) / 2;
Object Oriented Programming with JAVA[BCS306A]
Santhosh T, Asst. Prof, Dept. of IS&E, BIET 18
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public double calculatePerimeter()
{
return side1 + side2 + side3;
}
}
class Main {
public static void main(String[] args)
{
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
System.out.println("Circle - Area: " + circle.calculateArea());
System.out.println("Circle - Perimeter: " +
circle.calculatePerimeter());
System.out.println("Triangle - Area: " +
triangle.calculateArea());
System.out.println("Triangle - Perimeter: " +
triangle.calculatePerimeter());
}
}

DEPARTMENT OF CSE, KVGCE SULLIA Page 17


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 18


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 7:
Develop a JAVA program to create an interface Resizable with methods
resizeWidth(int width) and resizeHeight(int height) that allow an object to be
resized. Create a class Rectangle that implements the Resizable interface and
implements the resize methods.

interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}
class Rectangle implements Resizable
{
private int width;
private int height;
public Rectangle(int width, int height)
{
this.width = width;
this.height = height;
}
public void resizeWidth(int newWidth)
{
this.width = newWidth;
}
public void resizeHeight(int newHeight)
{
this.height = newHeight;
}
public void display()
{
System.out.println("Rectangle width: " + width + ", height: " + height);
}
DEPARTMENT OF CSE, KVGCE SULLIA Page 19
OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

public static void main(String[] args)


{
Rectangle rectangle = new Rectangle(5, 10);
rectangle.display();
rectangle.resizeWidth(8);
rectangle.resizeHeight(15);
rectangle.display();
}
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 20


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 8:
Develop a JAVA program to create an outer class with a function display.
Create another class inside the outer class named inner with a function called
display and call the two functions in the main class.

class Outerclass
{
void display()
{
System.out.println("Outer class display method.");
}
class Innerclass
{
void display()
{
System.out.println("Inner class display method.");
}
}
public static void main(String[] args)
{
Outerclass outer = new Outerclass();
outer.display();
Outerclass.Innerclass inner = outer.new Innerclass();
inner.display();
}
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 21


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 9:
Develop a JAVA program to raise a custom exception (user defined exception)
for DivisionByZero using try, catch, throw and finally.

public class CustomDivision


{
public static void main(String[] args)
{
int numerator = 10;
int denominator = 0;
try
{
if (denominator == 0)
{
throw new DivisionByZeroException("Division by zero is not allowed!");
}
int result = numerator / denominator;
System.out.println("Result: " + result);
}

catch (DivisionByZeroException e)
{
System.err.println("Error: " + e.getMessage());
}

finally
{
System.out.println("This block always executes,
regardless of exceptions.");
}

DEPARTMENT OF CSE, KVGCE SULLIA Page 22


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

}
}
class DivisionByZeroException extends Exception
{
public DivisionByZeroException(String message)
{
super(message);
}
}

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 23


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 9:
Develop a JAVA program to raise a custom exception (user defined exception)
for DivisionByZero using try, catch, throw and finally.

public class CustomDivision


{
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try
{
if (denominator == 0)
{
throw new DivisionByZeroException("Division by zero is not allowed!");
}
int result = numerator / denominator;
System.out.println("Result: " + result);
}
catch (DivisionByZeroException e)
{
System.err.println("Error: " + e.getMessage());
}
finally
{
System.out.println("This block always executes,
regardless of exceptions.");
}
}
}
class DivisionByZeroException extends Exception

DEPARTMENT OF CSE, KVGCE SULLIA Page 24


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

{
public DivisionByZeroException(String message)
{
super(message);
}
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 25


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 10:


Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.

Package: mypack
Class name: MyClass
package mypack;
public class MyClass
{
public void display()
{
System.out.println("This is a method from the mypack package!"); }
}
Example.java
import mypack.MyClass;
public class Example
{
public static void main(String[] args)
{
MyClass obj = new MyClass();
obj.display(); // Access the method from the imported package }
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 26


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 11:


Write a program to illustrate creation of threads using runnable class. (start
method start each of the newly created thread. Inside the run method there is
sleep() for suspend the thread for 500 milliseconds).

Mythread.java
public class Mythread implements Runnable
{
public void run()
{
for (int i = 1; i<= 5; i++)
{
System.out.println(Thread.currentThread().getName()+" i is " + i); try
{
//sleep current thread for 500 ms
Thread.sleep(500);
}
catch (InterruptedException e)
{
//print the exception message if occurred System.out.println(e.getMessage());
}
}
}
}
class ThreadExample
{
public static void main(String[] args)
{
Mythread myThread = new Mythread();
//thread 1

DEPARTMENT OF CSE, KVGCE SULLIA Page 27


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

Thread t1 =new Thread(myThread);


//thread2
Thread t2 =new Thread(myThread);
//thread 3
Thread t3 =new Thread(myThread);
//starting all 3 threads now
t1.start();
t2.start();
t3.start();
}
}
OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 28


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

LAB EXPERIMENT 12:


Create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts
after this. It can be observed that both main thread and created child thread are
executed concurrently.

TestMyThread.java
public class TestMyThread
{
public static void main(String args[])
{
new MyThread();
try
{
for( int k = 5; k > 0; k--)
{
System.out.println ("Running main thread :" + k); Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
}
System.out.println ("Exiting main thread . . ."); }
}
class MyThread extends Thread
{
MyThread()
{
super("Using Thread class");
System.out.println("Child thread:" + this);

DEPARTMENT OF CSE, KVGCE SULLIA Page 29


OBJECT ORIENTED PROGRAMMING IN JAVA BCS306A

start();
}
public void run()
{
try
{
for ( int i =5; i > 0; i--)
{
System.out.println("Child thread" + i);
Thread.sleep (500);
}
}
catch (InterruptedException e)
{
}
System.out.println("exiting child thread …"); }
}

OUTPUT:

DEPARTMENT OF CSE, KVGCE SULLIA Page 30

You might also like