0% found this document useful (0 votes)
6 views29 pages

Java Matrix Addition and Stack Class

The document contains multiple Java programs demonstrating various concepts such as matrix addition, stack operations, employee salary management, point distance calculations, shape drawing with polymorphism, and abstract classes for shapes. Each program includes class definitions, methods for functionality, and example outputs illustrating their usage. The programs cover fundamental programming principles including object-oriented programming, method overloading, and inheritance.

Uploaded by

babysharkchatgpt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

Java Matrix Addition and Stack Class

The document contains multiple Java programs demonstrating various concepts such as matrix addition, stack operations, employee salary management, point distance calculations, shape drawing with polymorphism, and abstract classes for shapes. Each program includes class definitions, methods for functionality, and example outputs illustrating their usage. The programs cover fundamental programming principles including object-oriented programming, method overloading, and inheritance.

Uploaded by

babysharkchatgpt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link];
public class MatrixAddition {

public static void main(String[] args) {


// Create a Scanner object to read input
Scanner sc = new Scanner([Link]);

// Read the dimensions of Matrix 1


[Link]("Enter the number of rows for Matrix 1: ");
int r1 = [Link]();
[Link]("Enter the number of columns for Matrix 1: ");
int c1 = [Link]();

// Read the dimensions of Matrix 2


[Link]("Enter the number of rows for Matrix 2: ");
int r2 = [Link]();
[Link]("Enter the number of columns for Matrix 2: ");
int c2 = [Link]();

// Check if the matrices have the same dimensions


if (r1 != r2 || c1 != c2) {
[Link]("Matrices are not compatible for addition.");
return;
}

// Declare matrices
int[][] m1 = new int[r1][c1];
int[][] m2 = new int[r1][c1];

// Input matrices using methods


[Link]("Enter elements of Matrix 1:");
inputMatrix(m1, r1, c1, sc);

[Link]("Enter elements of Matrix 2:");


inputMatrix(m2, r1, c1, sc);

// Add the two matrices


int[][] result = addMatrices(m1, m2, r1, c1);

// Display the result


[Link]("Resultant Matrix after Addition:");
displayMatrix(result, r1, c1);

// Close the scanner


[Link]();
}

// Method to input a matrix by passing the matrix array as a parameter


public static void inputMatrix(int[][] matrix, int r, int c, Scanner sc) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
matrix[i][j] = [Link]();
}
}
}
// Method to add two matrices
public static int[][] addMatrices(int[][] m1, int[][] m2, int r, int c) {
int[][] result = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
result[i][j] = m1[i][j] + m2[i][j];
}
}
return result;
}

// Method to display a matrix


public static void displayMatrix(int[][] m, int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
[Link](m[i][j] + " ");
}
[Link]();
}
}
}

Output:
Enter the number of rows for Matrix 1: 2
Enter the number of columns for Matrix 1: 3
Enter the number of rows for Matrix 2: 2
Enter the number of columns for Matrix 2: 3
Enter elements of Matrix 1:
123
456
Enter elements of Matrix 2:
789
10 11 12

Resultant Matrix after Addition:


8 10 12
14 16 18
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.

import [Link];
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
// Constructor to initialize the stack
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
// Method to push an element onto the stack
public void push(int value) {
if (top == maxSize - 1) {
[Link]("Stack Overflow! Cannot push " + value);
} else {
stackArray[++top] = value;
[Link]("Pushed " + value + " onto the stack.");
}
}
// Method to pop an element from the stack
public int pop() {
if (top == -1) {
[Link]("Stack Underflow! Cannot pop an element.");
return -1;
}
else
{
[Link]("Popped " + stackArray[top] + " from the stack.");
return stackArray[top--];
}
}
// Method to display the stack
public void display() {
if (top == -1) {
[Link]("Stack is empty.");
} else {
[Link]("Stack elements are:");
for (int i = top; i >= 0; i--) {
[Link](stackArray[i]);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the maximum size of the stack: ");
int size = [Link]();
Stack s = new Stack(size);
int choice, value;
do {
[Link]("\nStack Operations Menu:");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter value to push: ");
value = [Link]();
[Link](value);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice! Please try again.");
}
} while (choice != 4);
[Link]();
}
}

Output:
Enter the maximum size of the stack: 3

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 10
Pushed 10 onto the stack.

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 20
Pushed 20 onto the stack.

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 30
Pushed 30 onto the stack.

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 40
Stack Overflow! Cannot push 40
Stack Operations Menu:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements are:
30
20
10

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Popped 30 from the stack.

Stack Operations Menu:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Popped 20 from the stack.
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.

import [Link];
class Employee1 {

private int id;


private String name;
private double salary;

public Employee1(int id, String name, double salary) {


[Link] = id;
[Link] = name;
[Link] = salary;
}

public void raiseSalary(double percent) {


if (percent > 0) {
salary += salary * (percent / 100);
} else {
[Link]("Raise percentage must be positive.");
}
}

public void displayEmployeeDetails() {


[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}
}

public class EmployeeDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

Employee1 emp1 = new Employee1(101, "Aarohi", 90000);

[Link]("Before raise:");
[Link]();

// Read the percentage from the user


[Link]("\nEnter the percentage to raise salary: ");
double percentage = [Link]();

// Raise salary by the input percentage


[Link](percentage);

// Display employee details after salary raise


[Link]("\nAfter " + percentage + "% raise:");
[Link]();
// Close the scanner
[Link]();
}
}
Output:
Enter the percentage to raise salary: 10
Before raise:
Employee ID: 101
Employee Name: Aarohi
Employee Salary: 90000.0

Enter the percentage to raise salary: 10

After 10.0% raise:


Employee ID: 101
Employee Name: Aarohi
Employee Salary: 99000.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 constructs a point at the default
location of (0, 0).
● An 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 MyPoint) to test all the methods defined in the
class.

public class MyPoint {


// Instance variables
private int x;
private 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 return x and y in a 2-element int array


public int[] getXY() {
return new int[]{this.x, this.y};
}

// toString method to return a string description of the instance in the format "(x, y)"
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}

// Method to calculate the distance from this point to another point with given coordinates
public double distance(int x, int y) {
int dx = this.x - x;
int dy = this.y - y;
return [Link](dx * dx + dy * dy);
}

// Overloaded distance method to calculate the distance from this point to another MyPoint
instance
public double distance(MyPoint another) {
return distance(another.x, another.y); // Call the distance method with another point's
coordinates
}

// Overloaded distance method to calculate the distance from this point to the origin (0, 0)
public double distance() {
return distance(0, 0); // Call the distance method with (0, 0)
}

// Main method for testing


public static void main(String[] args) {
// Create MyPoint instances
MyPoint point1 = new MyPoint(3, 4);
MyPoint point2 = new MyPoint(7, 9);

// Test toString()
[Link]("Point1: " + [Link]());
[Link]("Point2: " + [Link]());

// Test distance() methods


[Link]("Distance from Point1 to origin: " + [Link]());
[Link]("Distance from Point1 to Point2: " + [Link](point2));
[Link]("Distance from Point1 to (6, 8): " + [Link](6, 8));
}
}

Output:
Point1: (3, 4)
Point2: (7, 9)
Distance from Point1 to origin: 5.0
Distance from Point1 to Point2: 6.4031242374328485
Distance from Point1 to (6, 8): 5.0
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.

// Base class
class Shape {
// Method to draw the shape
void draw() {
[Link]("Drawing a shape.");
}
// Method to erase the shape
void erase() {
[Link]("Erasing a shape.");
}
}

// Subclass for Circle


class Circle extends Shape {
void draw() {
[Link]("Drawing a circle.");
}
void erase() {
[Link]("Erasing a circle.");
}
}

// Subclass for Triangle


class Triangle extends Shape {
void draw() {
[Link]("Drawing a triangle.");
}
void erase() {
[Link]("Erasing a triangle.");
}
}

// Subclass for Square


class Square extends Shape {
void draw() {
[Link]("Drawing a square.");
}
void erase() {
[Link]("Erasing a square.");
}
}

// Main class to demonstrate polymorphism


public class ShapeDemo {
public static void main(String[] args) {
// Creating Shape references pointing to different subclasses
Shape myShape;
// Circle instance
myShape = new Circle();
[Link](); // Calls Circle's draw()
[Link](); // Calls Circle's erase()

[Link]();

// Triangle instance
myShape = new Triangle();
[Link](); // Calls Triangle's draw()
[Link](); // Calls Triangle's erase()

[Link]();

// Square instance
myShape = new Square();
[Link](); // Calls Square's draw()
[Link](); // Calls Square's erase()
}
}

Output:
Drawing a circle.
Erasing a circle.

Drawing a triangle.
Erasing a triangle.

Drawing a square.
Erasing a square.
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.

// Abstract class Shape with abstract methods

abstract class Shape {

// Abstract methods to calculate area and perimeter

abstract double calculateArea();

abstract double calculatePerimeter();

// Subclass Circle that extends Shape

class Circle extends Shape {

private double radius;

// Constructor to initialize the radius


public Circle(double radius) {

[Link] = radius;

// Implement calculateArea for Circle

double calculateArea() {

return [Link] * radius * radius;

// Implement calculatePerimeter for Circle

double calculatePerimeter() {

return 2 * [Link] * radius;

// Subclass Triangle that extends Shape

class Triangle extends Shape {

private double side1, side2, side3;

// Constructor to initialize the sides of the triangle

public Triangle(double side1, double side2, double side3) {

this.side1 = side1;

this.side2 = side2;

this.side3 = side3;
}

// Implement calculateArea for Triangle (using Heron's formula)

double calculateArea() {

double s = (side1 + side2 + side3) / 2;

return [Link](s * (s - side1) * (s - side2) * (s - side3));

// Implement calculatePerimeter for Triangle

double calculatePerimeter() {

return side1 + side2 + side3;

// Main class to test the functionality

public class Main {

public static void main(String[] args) {

// Create a Circle object with radius 5

Shape c = new Circle(5);

[Link]("Circle:");

[Link]("Area: " + [Link]());

[Link]("Perimeter: " + [Link]());


// Create a Triangle object with sides 3, 4, and 5

Shape t = new Triangle(3, 4, 5);

[Link]("\nTriangle:");

[Link]("Area: " + [Link]());

[Link]("Perimeter: " + [Link]());

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

// Define the Resizable interface


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

// Implement the Rectangle class


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

// Constructor
public Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}

// Implement resizeWidth method from Resizable interface


public void resizeWidth(int width) {
if (width > 0) {
[Link] = width;
[Link]("Width resized to: " + [Link]);
} else {
[Link]("Invalid width. It must be greater than 0.");
}
}

// Implement resizeHeight method from Resizable interface


public void resizeHeight(int height) {
if (height > 0) {
[Link] = height;
[Link]("Height resized to: " + [Link]);
} else {
[Link]("Invalid height. It must be greater than 0.");
}
}

// Method to display rectangle's dimensions


public void displayDimensions() {
[Link]("Rectangle [Width = " + width + ", Height = " + height + "]");
}
}

// Main class to test the Rectangle class


public class Main {
public static void main(String[] args) {
// Create a Rectangle object
Rectangle r = new Rectangle(10, 20);
[Link]("Original dimensions:");
[Link]();

// Resize width and height


[Link]("\nResizing dimensions:");
[Link](15);
[Link](25);
[Link]();

// Attempt invalid resize


[Link]("\nAttempting invalid resize:");
[Link](-5);
[Link](0);
}
}

Output:
Original dimensions:
Rectangle [Width = 10, Height = 20]

Resizing dimensions:
Width resized to: 15
Height resized to: 25
Rectangle [Width = 15, Height = 25]

Attempting invalid resize:


Invalid width. It must be greater than 0.
Invalid height. It must be greater than 0.
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.
// Outer class
class OuterClass {
//Outer class method
void display() {
[Link]("This is the display method of the Outer class.");
}
class InnerClass {
//Inner class method
void display() {
[Link]("This is the display method of the Inner class.");
}
}
}
public class MainClass {
public static void main(String[] args) {
// Creating an instance of the outer class
OuterClass out = new OuterClass();
[Link](); // Calling the outer class's display method

// Creating an instance of the inner class


[Link] in = [Link] InnerClass();
[Link](); // Calling the inner class's display method
}
}

Output:
This is the display method of the Outer class.
This is the display method of the Inner class.
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
import [Link];
// Custom Exception for Division by Zero
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String s) {
super(s);
}
}
public class DivisionByZeroDemo {
public static double divide(int n, int d) throws DivisionByZeroException {
if (d == 0) {
throw new DivisionByZeroException("Error: Division by 0 is not allowed.");
}
return (double) n / d;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int num, denom;
try {
// Read numerator
[Link]("Enter the numerator: ");
num = [Link]();
// Read denominator
[Link]("Enter the denominator: ");
denom = [Link]();
// Attempt division
double result = divide(num, denom);
[Link]("Result: " + result);
}
catch (DivisionByZeroException e) {
// Handle custom exception
[Link]([Link]());
}
catch (Exception e) {
// Handle other input errors
[Link]("Error: Invalid input. Please enter integers only.");
}
finally {
[Link]("Execution completed. Thank you!");
[Link]();
}
}
}

Output:
If denominator = 0:
Error: Division by zero is not allowed.
Execution completed. Thank you!

If denominator = 5:
Result: 2.0
Execution completed. Thank you!
10. Develop a JAVA program to create a package
named mypack and import & implement it in a
suitable class.

package myPack;
// This class is part of the mypack package and handles message-related operations.
public class Message {
public void showMessage(String name) {
[Link]("Hello, " + name + "! Welcome to the myPack package!");
}
}

package myPack;
// This class provides basic mathematical operations.
public class MathOperations {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
import [Link]; // Import the Message class
import [Link]; // Import the MathOperations class

public class PackageDemo {


public static void main(String[] args) {
// Using the Message class
Message m = new Message();
[Link]("Acharya");

// Using the MathOperations class


MathOperations mo = new MathOperations();
int sum = [Link](10, 20);
int product = [Link](5, 4);

[Link]("Addition Result: " + sum);


[Link]("Multiplication Result: " + product);
}
}
Output:

Hello, Acharya! Welcome to the mypack package!


Addition Result: 30
Multiplication Result: 20
Factorial of 5: 120

You might also like