Nothing Special   »   [go: up one dir, main page]

Java Lab

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

Object Oriented Programming with JAVA

BCS306A

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of
N should be read from command line arguments).
import java.util.Scanner;
class AddMatrix{
public static void main(String[] args) {
int row,col,i,j;
Scanner s=new Scanner(System.in);

System.out.println(“Enter the number of rows:”);


row=s.nextInt();

System.out.println(“Enter the number of columns:”);


col=s.nextInt();

int mat1[][]=new int[row][col];


int mat2[][]=new int[row][col];
int res[][]=new int[row][col];

System.out.println(“Enter the elements of Matrix1:”);


for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
mat1[i][j]=s.nextInt();
}
}

System.out.println(“Enter the elements of Matrix2:”);


for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
mat2[i][j]=s.nextInt();
}
}

for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
res[i][j]=mat1[i][j]+mat2[i][j];
}
}

System.out.println(“Sum of matrices:”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print(res[i][j]+“\t”);

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere1


Object Oriented Programming with JAVA
BCS306A

}
System.out.println();
}
}
}

Output:
Enter the number of rows:
2
Enter the number of columns:
2
Enter the elements of Matrix1:
1234
Enter the elements of Matrix2:
5678
Sum of matrices:
6 8
10 12

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


Develop a JAVA main method to illustrate Stack operations.
public class Stack {
private int maxSize;
private int[] stackArray;
private int top;

// Constructor to initialize the stack


public Stack(int size) {
this.maxSize = size;
this.stackArray = new int[maxSize];
this.top = -1;
}

// Method to push an element onto the stack


public void push(int value) {
if (isFull()) {
System.out.println("Stack is full. Cannot push element.");
return;
}
top++;
stackArray[top] = value;
}

// Method to pop an element from the stack


public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop element.");
return -1;
}
int poppedValue = stackArray[top];
top--;
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere2
Object Oriented Programming with JAVA
BCS306A

return poppedValue;
}
// Method to peek the top element of the stack without removing it
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty. No element to peek.");
return -1;
}
return stackArray[top];
}

// Method to check if the stack is empty


public boolean isEmpty() {
return (top == -1);
}

// Method to check if the stack is full


public boolean isFull() {
return (top == maxSize - 1);
}

// Method to display the elements in the stack


public void displayStack() {
System.out.print("Stack (top to bottom): ");
for (int i = top; i >= 0; i--) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


Stack stack = new Stack(5);

stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);

stack.displayStack(); // Display stack elements

System.out.println("Popped element: " + stack.pop()); // Pop an element

System.out.println("Top element: " + stack.peek()); // Peek top element

stack.displayStack(); // Display stack elements after operations


}
}

Output:
Stack (top to bottom): 50 40 30 20 10
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere3
Object Oriented Programming with JAVA
BCS306A

Popped element: 50
Top element: 40
Stack (top to bottom): 40 30 20 10
3. A class called Employee, which models an employee with an ID, name and salary,
is designed as shown in the following class diagram. The method raiseSalary
(percent) increases the salary by the given percentage. Develop the Employee class
and suitable main method for demonstration.
public 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 + ", Name: " + name + ", Salary: $" + salary;
}

public static void main(String[] args) {


// Creating an Employee object
Employee employee = new Employee(1, "John Doe", 50000.0);

// Displaying employee details


System.out.println("Initial Employee Details:");
System.out.println(employee);

// Raising salary by 10%


employee.raiseSalary(10);

// Displaying updated employee details


System.out.println("\nEmployee Details after Salary Raise:");
System.out.println(employee);
}
}

Output:

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere4


Object Oriented Programming with JAVA
BCS306A

Initial Employee Details:


Employee ID: 1 Name: John Doe Salary: $50000.0
John Doe's salary raised by 10%. New salary: $55000.0
Employee Details after Salary Raise:
Employee ID: 1 Name: John Doe Salary: $55000.0
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.
public class MyPoint
{
int x;
int y;

//Default Constructor
public MyPoint()
{
this.x = 0;
this.y = 0;
}

//Overloaded Constructor
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}

//Method to set both x and y


public void setXY(int x, int y)
{
this.x = x;
this.y = y;
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere5


Object Oriented Programming with JAVA
BCS306A

//Method to get both x and y in a 2-element int array


public int[] getXY()
{
int[] coordinates={x,y};
return coordinates;
}
// toString Method to return a string description of the instance
public String toString()
{
return "(" + x + ", " + y + ")";
}

//Method to calculate distance from this point to another point


public double distance(int x, int y)
{
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}

// Overloaded Method to calculate distance from this point to another


MyPoint instance
public double distance(MyPoint another)
{
return distance(another.x, another.y);
}

// Another Overloaded Method to calculate distance from this point to the


origin (0,0)
public double distance()
{
return distance(0,0);
}
}

class testmypoint{
public static void main(String[] args){
MyPoint point1=new MyPoint(3,4);
MyPoint point2=new MyPoint(6,8);

System.out.println("Point1:"+point1);
System.out.println(("Point2:"+point2);

System.out.println("Distance between Point 1and Point


2:"+point1.distance(point2));
System.out.println("Distance from Point 1to the origin:"+point1.distance());
point1.setXY(1,2);
System.out.println("Point 1 coordinates after setXY:"+point1. toString
());
}
}
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere6
Object Oriented Programming with JAVA
BCS306A

Output:
Point 1: (3,4)
Point 1: (6,8)
Distance between Point 1and Point 2: 5.0
Distance from Point 1to the origin: 5.0
Point 1 coordinates after setXY: (1,2)

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.
public class Shape{
void draw()
{
System.out.println("Drawing Shape");

void erase()
{
System.out.println("erasing Shape");
}

class Circle extends Shape{


void draw()
{
System.out.println("Drawing Circle");

void erase()
{
System.out.println("erasing Circle");
}
}

class Triangle extends Shape{


void draw()
{
System.out.println("Drawing Triangle");
}

void erase()
{
System.out.println("erasing Triangle");
}
}
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere7
Object Oriented Programming with JAVA
BCS306A

class Square extends Shape{


void draw()
{
System.out.println("Drawing Square");
}

void erase()
{
System.out.println("erasing Square");
}
}

class method{
public static void main(String args[]){
Shape c=new Circle();
Shape t=new Triangle();
Shape s=new Square();
c.draw();
c.erase();
t.draw();
t.erase();
s.draw();
s.erase();
}
}

Output:
Drawing Circle
erasing Circle
Drawing Triangle
erasing Triangle
Drawing Square
erasing Square

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


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

abstract class Shape {


// Abstract methods to calculate area and perimeter
public abstract double calculateArea();
public abstract double calculatePerimeter();
}

class Circle extends Shape {


private double radius;

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere8


Object Oriented Programming with JAVA
BCS306A

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Implementing abstract methods


public double calculateArea() {
return Math.PI * radius * radius;
}
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shape {


private double side1, side2, side3;

// Constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

// Implementing abstract methods


public double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

public double calculatePerimeter() {


return side1 + side2 + side3;
}
}

public class ShapeDemo {


public static void main(String[] args) {
// Creating instances of Circle and Triangle
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);

// Displaying area and perimeter of Circle


System.out.println("Circle:");
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());
System.out.println();

// Displaying area and perimeter of Triangle

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere9


Object Oriented Programming with JAVA
BCS306A

System.out.println("Triangle:");
System.out.println("Area: " + triangle.calculateArea());
System.out.println("Perimeter: " + triangle.calculatePerimeter());
}
}

Output:
Circle:
Area: 1.99
Perimeter: 31.42
Triangle:
Area: 6.0
Perimeter: 12.0

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.

// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Rectangle class implementing Resizable interface


class Rectangle implements Resizable {
private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

// Implementation of Resizable interface


public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}

public void resizeHeight(int height) {


this.height = height;
System.out.println("Resized height to: " + height);
}

// Additional methods for Rectangle class


public int getWidth() {
return width;

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere10


Object Oriented Programming with JAVA
BCS306A

public int getHeight() {


return height;
}

public void displayInfo() {


System.out.println("Rectangle: Width = " + width + ", Height = " + height);
}
}

// Main class to test the implementation


public class ResizeDemo {
public static void main(String[] args) {
// Creating a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);

// Displaying the original information


System.out.println("Original Rectangle Info:");
rectangle.displayInfo();

// Resizing the rectangle


rectangle.resizeWidth(15);
rectangle.resizeHeight(8);

// Displaying the updated information


System.out.println("\nUpdated Rectangle Info:");
rectangle.displayInfo();
}
}

Output:
Original Rectangle Info:
Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 8

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8

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 Outer {

void display() {
System.out.println("Outer class display method");
}

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere11


Object Oriented Programming with JAVA
BCS306A

class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args) {
// Create an instance of the Outer class
Outer outer = new Outer();

// Call the display method of the Outer class


outer.display();

// Create an instance of the Inner class (nested inside Outer)


Outer.Inner inner = outer.new Inner();

// Call the display method of the Inner class


inner.display();
}
}
}
Output:
Outer class display method
Inner class display method

9. Develop a JAVA program to raise a custom exception (user defined exception)


for DivisionByZero using try, catch, throw and finally.

// Custom exception class


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

public class CustomExceptionDemo {


// Method to perform division and throw custom exception if denominator is
zero
static double divide(int numerator, int denominator) throws
DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Cannot divide by zero!");
}
return (double) numerator / denominator;
}

public static void main(String[] args) {


int numerator = 10;
int denominator = 0;
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere12
Object Oriented Programming with JAVA
BCS306A

try {
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}

Output:
Exception caught: Cannot divide by zero!
Finally block executed
10. Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.
Package mypack
// Inside a folder named 'mypack'
package mypack;

public class MyPackageClass {


public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}

// New utility method


public static int addNumbers(int a, int b) {
return a + b;
}
}

Now, let’s create the main program in a different file outside the mypack folder:
PackageDemo class using mypack Package
// Main program outside the mypack folder
import mypack.MyPackageClass;
//import mypack.*;

public class PackageDemo {


public static void main(String[] args) {
// Creating an instance of MyPackageClass from the mypack package
MyPackageClass myPackageObject = new MyPackageClass();

// Calling the displayMessage method from MyPackageClass


myPackageObject.displayMessage();

// Using the utility method addNumbers from MyPackageClass


int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere13


Object Oriented Programming with JAVA
BCS306A

}
}

To compile and run this program, you need to follow these steps:
Organize your directory structure as follows:

Output:
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8

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).

class MyRunnable implements Runnable {


private volatile boolean running = true;

@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId()
+"
is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}

public void stopThread() {


running = false;
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
// Create five instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere14
Object Oriented Programming with JAVA
BCS306A

MyRunnable myRunnable3 = new MyRunnable();


MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();

// Create five threads and associate them with MyRunnable instances


Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);

// Start the threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();

// Sleep for a while to allow the threads to run


try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop the threads gracefully


myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
}
}

Output:
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.

12. Develop a program to 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.

class MyThread extends Thread {


// Constructor calling base class constructor using super
public MyThread(String name) {
super(name);

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere15


Object Oriented Programming with JAVA
BCS306A

start(); // Start the thread in the constructor


}

// The run method that will be executed when the thread starts
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread
interrupted.");
}
}
}
}

public class ThreadConcurrentExample {


public static void main(String[] args) {
// Create an instance of MyThread
MyThread myThread = new MyThread("Child Thread");

// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread
interrupted.");
}
}
}
}

Output:
main Thread Count: 1
Child Thread Count: 1
main Thread Count: 2
Child Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5

Dr. Azizkhan F Pathan, Dept. of IS&E, JIT, Davangere16

You might also like