Java OOP and Data Structure Implementations (Matrices, Stacks, Shapes)
Java Programming Assignments and Solutions
1. Matrix Addition using Command Line Arguments
Task: Develop a Java program to add two matrices of suitable order N. The value of N should be read from command line arguments.
Aim: To implement the addition of two matrices of order N using Java Programming, where N is supplied via command line arguments.
public class MatrixAddition {
public static void main(String[] args) {
// Check if the number of command line arguments is correct
if (args.length != 1) {
System.out.println("Usage: java MatrixAddition <order_N>");
return;
}
// Parse the command line argument to get the order N
int N = Integer.parseInt(args[0]);
// Check if N is a positive integer
if (N <= 0) {
System.out.println("Please provide a valid positive integer for the order N.");
return;
}
// Create two matrices of order N
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
// Fill the matrices with some sample values (you can modify this as needed)
fillMatrix(matrix1, 1);
fillMatrix(matrix2, 2);
// Print the matrices
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("\nMatrix 2:");
printMatrix(matrix2);
// Add the matrices
int[][] resultMatrix = addMatrices(matrix1, matrix2);
// Print the result matrix
System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
printMatrix(resultMatrix);
}
// Helper method to fill a matrix with sequential values
private static void fillMatrix(int[][] matrix, int startValue) {
int value = startValue;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = value++;
}
}
}
// Helper method to add two matrices
private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int N = matrix1.length;
int[][] resultMatrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return resultMatrix;
}
// Helper method to print a matrix
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + "\t");
}
System.out.println();
}
}
}
2. Implementing a Fixed-Size Integer Stack in Java
Task: Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a Java main method to illustrate stack operations.
Aim: To implement a stack class and a main method to demonstrate stack operations using Java Programming.
import java.util.Scanner;
public class Stack {
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;
public Stack() {
stackArray = new int[MAX_SIZE];
top = -1;
}
public void push(int value) {
if (top < MAX_SIZE - 1) {
stackArray[++top] = value;
System.out.println("Pushed: " + value);
} else {
System.out.println("Stack Overflow! Cannot push " + value + ".");
}
}
public int pop() {
if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped: " + poppedValue);
return poppedValue;
} else {
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
return -1; // Return a default value for simplicity
}
}
public int peek() {
if (top >= 0) {
System.out.println("Peeked: " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a default value for simplicity
}
}
public void display() {
if (top >= 0) {
System.out.print("Stack Contents: ");
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == MAX_SIZE - 1;
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nStack Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display Stack Contents");
System.out.println("5. Check if the stack is empty");
System.out.println("6. Check if the stack is full");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Is the stack empty? " + stack.isEmpty());
break;
case 6:
System.out.println("Is the stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
scanner.close();
}
}
3. Employee Class Implementation with Salary Increase
Task: Develop the Employee class, which models an employee with an ID, name, and salary. The method raiseSalary(percent) increases the salary by the given percentage. Develop the Employee class and a suitable main method for demonstration.
Aim: To implement the Employee class and a suitable main method using Java Programming.
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);
}
}
4. MyPoint Class: Coordinate Handling and Distance Methods
Task: Implement the MyPoint class to represent a 2D coordinate point, including methods for setting coordinates, retrieving coordinates, and calculating the distance to another point or the origin. Include a TestMyPoint class for demonstration.
public class MyPoint {
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;
}
// Set both x and y
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
// Get x and y in a 2-element int array
public int[] getXY() {
return new int[]{x, y};
}
// Return a string description of the instance in the format "(x, y)"
public String toString() {
return "(" + x + ", " + y + ")";
}
// Calculate distance from this point to another point at (x, y)
public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
// Calculate distance from this point to another MyPoint instance
public double distance(MyPoint another) {
return distance(another.x, another.y);
}
// 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) {
// Creating MyPoint objects using different constructors
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Testing setXY and getXY methods
point1.setXY(1, 2);
System.out.println("Point1 coordinates after setXY: " +
point1.getXY()[0] + "," + point1.getXY()[1]);
// Testing toString method
System.out.println("Point2 coordinates: " + point2.toString());
// Testing distance methods
System.out.println("Distance from Point1 to Point2: " + point1.distance(point2));
System.out.println("Distance from Point2 to Origin: " + point2.distance());
}
}
5. Demonstrating Polymorphism with Shape Subclasses
Task: Develop a Java program to create a class named Shape. Create three subclasses, namely Circle, Triangle, and Square. Each class must have two member functions named draw() and erase(). Demonstrate polymorphism concepts by developing suitable methods, defining member data, and a main program.
Aim: To implement polymorphism concepts using inheritance and method overriding in Java Programming.
class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
public void draw() {
System.out.println("Drawing a " + name);
}
public void erase() {
System.out.println("Erasing a " + name);
}
}
class Circle extends Shape {
private double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(String name, double base, double height) {
super(name);
this.base = base;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}
@Override
public void erase() {
System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}
class Square extends Shape {
private double side;
public Square(String name, double side) {
super(name);
this.side = side;
}
@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}
@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle("Circle", 5.0);
shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);
for (Shape shape : shapes) {
shape.draw();
shape.erase();
System.out.println();
}
}
}
6. Abstract Class Implementation: Area and Perimeter
Task: 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.
Aim: To implement an abstract class Shape with abstract methods in Java Programming.
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
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));
}
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
public class AbstractShapeDemo {
public static void main(String[] args) {
// Creating Circle and Triangle objects
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
// Calculating and displaying area and perimeter
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
System.out.println("\nTriangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}
7. Implementing the Resizable Interface with a Rectangle
Task: 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
@Override
public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}
@Override
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;
}
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();
}
}
