Java Programming Examples: Matrices, Stacks, OOP, and More

1. Java Program to Add Two Matrices

Code:

import java.util.Scanner;

class AddMatrix {
    public static void main(String args[]) {
        int row, col, i, j;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the number of rows");
        row = in.nextInt();

        System.out.println("Enter the number columns");
        col = in.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] = in.nextInt();
            }
            System.out.println();
        }

        System.out.println("Enter the elements of matrix2");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                mat2[i][j] = in.nextInt();
            }
            System.out.println();
        }

        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");
            }
            System.out.println();
        }
    }
} 

2. Stack Class for Integers

Code:

import java.util.Scanner;

public class Stack {
    final int max = 10;
    int s[] = new int[max];
    int top = -1;

    void push(int ele) {
        if (top >= max - 1) {
            System.out.println("Stack overflow");
        } else {
            s[++top] = ele;
        }
    }

    int pop() {
        int z = 0;
        if (top == -1) {
            System.out.println("Stack underflow");
        } else {
            z = s[top--];
        }
        return z;
    }

    void display() {
        if (top == -1) {
            System.out.println("Stack empty");
        } else {
            for (int i = top; i > -1; i--) {
                System.out.println(s[i] + "");
            }
        }
    }

    public static void main(String args[]) {
        int q = 1;
        Stack m = new Stack();
        System.out.println("Program to perform stack operations");
        Scanner sc = new Scanner(System.in);

        while (q != 0) {
            System.out.println("Enter 1. push 2. pop 3. display");
            System.out.println("Enter your choice");
            int ch = sc.nextInt();

            switch (ch) {
                case 1:
                    System.out.println("Enter the element to be pushed");
                    int ele = sc.nextInt();
                    m.push(ele);
                    break;
                case 2:
                    int popele;
                    popele = m.pop();
                    System.out.println("The popped element is");
                    System.out.println(popele + "");
                    break;
                case 3:
                    System.out.println("Elements in the stack are");
                    m.display();
                    break;
                case 4:
                    q = 0;
                    break;
            }
        }
    }
}

3. Employee Class

Code:

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) {
        salary += salary * (percent / 100);
    }

    public void displayInfo() {
        System.out.println("Employee ID: " + id);
        System.out.println("Employee Name: " + name);
        System.out.println("Employee Salary: $" + salary);
    }

    public static void main(String[] args) {
        Employee employee1 = new Employee(1, "John Doe", 50000.0);
        Employee employee2 = new Employee(2, "Jane Smith", 60000.0);

        System.out.println("Before Salary Raise:");
        employee1.displayInfo();
        employee2.displayInfo();

        // Raise salaries by 10%
        employee1.raiseSalary(10);
        employee2.raiseSalary(10);

        System.out.println("\nAfter Salary Raise:");
        employee1.displayInfo();
        employee2.displayInfo();
    }
}

5. Shape Class and Polymorphism

Code:

class Shape {
    void draw() {
        System.out.println("Drawing a shape");
    }

    void erase() {
        System.out.println("Erasing a shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }

    @Override
    void erase() {
        System.out.println("Erasing a circle");
    }
}

class Triangle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a triangle");
    }

    @Override
    void erase() {
        System.out.println("Erasing a triangle");
    }
}

class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a square");
    }

    @Override
    void erase() {
        System.out.println("Erasing a square");
    }

    public static void main(String[] args) {
        Shape s1 = new Circle();
        Shape s2 = new Triangle();
        Shape s3 = new Square();

        s1.draw();
        s1.erase();
        s2.draw();
        s2.erase();
        s3.draw();
        s3.erase();
    }
}

6. Abstract Shape Class

Code:

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;
    }

    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }

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

class Triangle extends Shape {
    private double sideA;
    private double sideB;
    private double sideC;

    public Triangle(double sideA, double sideB, double sideC) {
        this.sideA = sideA;
        this.sideB = sideB;
        this.sideC = sideC;
    }

    @Override
    public double calculateArea() {
        double s = (sideA + sideB + sideC) / 2;
        return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
    }

    @Override
    public double calculatePerimeter() {
        return sideA + sideB + sideC;
    }

    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());
    }
}

7. Resizable Interface and Rectangle

Code:

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;
    }

    @Override
    public void resizeWidth(int width) {
        this.width = width;
    }

    @Override
    public void resizeHeight(int height) {
        this.height = height;
    }

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

    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(10, 20);

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

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

        System.out.println("Resized Rectangle:");
        rectangle.display();
    }
}

8. Inner and Outer Classes

Code:

class Outer {
    void display() {
        System.out.println("This is the outer class display function.");
    }

    class Inner {
        void display() {
            System.out.println("This is the inner class display function.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Outer outerObject = new Outer();
        Outer.Inner innerObject = outerObject.new Inner();

        outerObject.display();
        innerObject.display();
    }
}

9. Custom Exception for Division by Zero

Code:

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

public class CustomExceptionDemo {
    public static void main(String[] args) {
        int numerator = 10;
        int denominator = 0;

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

    public static int divide(int numerator, int denominator) throws DivisionByZeroException {
        if (denominator == 0) {
            throw new DivisionByZeroException("Division by zero is not allowed.");
        }
        return numerator / denominator;
    }
}

10. Creating and Using a Package

1. Create the Package:

your_project_directory/
├── mypack/
│   └── MyClass.java
└── OtherProjectFiles...

2. Create a Java Class in the Package:

package mypack;

public class MyClass {
    public void displayMessage() {
        System.out.println("Hello from mypack.MyClass!");
    }
}

3. Create a Class to Import and Use the Package:

import mypack.MyClass;

public class MainClass {
    public static void main(String[] args) {
        MyClass myObj = new MyClass();
        myObj.displayMessage();
    }
}

4. Compile and Run the Program:

javac mypack/MyClass.java
javac MainClass.java

// Then, run the program using the `java` command:
java MainClass 

11. Threads using Runnable Interface

Code:

class MyRunnable implements Runnable {
    public void run() {
        try {
            System.out.println("Thread is running.");
            Thread.sleep(500);
            System.out.println("Thread has completed.");
        } catch (InterruptedException e) {
            System.out.println("Thread was interrupted.");
        }
    }
}

public class SimpleThreadExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        thread1.start();
        thread2.start();
    }
}

12. MyThread Class with Constructor and Start

Code:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
        start();
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Child Thread: " + getName() + " - Count: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.err.println("Child thread interrupted.");
            }
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread myThread = new MyThread("MyThread");

        for (int i = 1; i <= 5; i++) {
            System.out.println("Main Thread - Count: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.err.println("Main thread interrupted.");
            }
        }
    }
}

13. Autoboxing and Unboxing

Code:

public class AutoboxingUnboxingDemo {
    public static void main(String[] args) {
        Integer num1 = 42; // Autoboxing
        Double num2 = 3.14; // Autoboxing
        Boolean flag = true; // Autoboxing

        int intValue = num1; // Unboxing
        double doubleValue = num2; // Unboxing
        boolean booleanValue = flag; // Unboxing

        System.out.println("Sum: " + (num1 + num2)); // Auto-unboxing for addition

        java.util.ArrayList<Integer> numbers = new java.util.ArrayList<>();
        numbers.add(10); // Autoboxing
        numbers.add(20); // Autoboxing
        numbers.add(30); // Autoboxing

        for (Integer number : numbers) {
            int value = number; // Unboxing
            System.out.println("Value: " + value);
        }
    }
}

14. Primitive Types and Type Promotion

Code:

public class TypePromotionDemo {
    public static void main(String[] args) {
        int intValue = 10;
        long longValue = 20L;
        float floatValue = 3.14f;
        double doubleValue = 2.71828;

        double result1 = intValue + longValue; // int promoted to long, then long to double
        float result2 = floatValue + longValue; // long promoted to float
        double result3 = floatValue + doubleValue; // float promoted to double

        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);
        System.out.println("Result 3: " + result3);
    }
}