summary refs log tree commit diff stats
path: root/java/code
diff options
context:
space:
mode:
authorSudipto Mallick <>2024-01-02 02:12:16 +0000
committerSudipto Mallick <>2024-01-02 02:12:16 +0000
commita70e0a59817ce06a3dd23b3750ae16ee6660deaf (patch)
tree0843bf4d30edf22c9c4c27ff4887351c85993ccd /java/code
parent63c589e826829c5f47f95a5642531e02b2b2c8f7 (diff)
downloadzadania-a70e0a59817ce06a3dd23b3750ae16ee6660deaf.tar.gz
Add Java assignments to the repository
.gitignore: The build files, files left by editors like *~ and the PDF
documents for the assignments are to be ignored for the purposes of
version control.

README.rst: Rewrite, with one line description in Chinese.

java/alist.txt: List of assignments, sorted in the order of the list of
assignments, with the ones with completed documentation marked with `#`.

java/buildall: Script that will build all of the assignments into one
PDF file; to be rehauled for the final document.

code/*.java: The Java source code for the assignments.

dbld: Script that builds a PDF document for a single assignment.

index.typ: The list of assignments, subject to update for further
refinement and inclusion of yet more assignments.

jbld: Script that compiles code for a single Java assignment.

output/*.typ: Typst file containing the output (sessions) obtained from
running the individual Java assignments.

state.sql: Future alternative to `alist.txt`, under development.

template.typ: The Typst template used across all of assignment,
containing common code for the uniform styling, such as page border.

text/*.typ: Typst file documenting each Java assignment.

vendor/Java.sublime-syntax: Updated Sublime Text syntax file for Java,
used for newer syntax features, such as `var`, not yet available in
syntaxes shipped with Typst.

vendor/gr.tmTheme: A grayscale TextMate theme to be used for code in the
documents generated by Typst suitable for black and white printing.

wltd: Difference between the files in `code/` and `text/`, and `code/`
and `output`; need to be rewritten along with `state.sql`.
Diffstat (limited to 'java/code')
-rw-r--r--java/code/AddTwoNumbers.java81
-rw-r--r--java/code/ArraySearch.java130
-rw-r--r--java/code/ArraySort.java113
-rw-r--r--java/code/BankAccountExample.java155
-rw-r--r--java/code/ComplexCalculations.java43
-rw-r--r--java/code/ConeCalculations.java55
-rw-r--r--java/code/CylinderCalculations.java52
-rw-r--r--java/code/FindNumberInArray.java72
-rw-r--r--java/code/MatrixOperations.java172
-rw-r--r--java/code/SingletonExample.java23
-rw-r--r--java/code/StaticExecution.java30
-rw-r--r--java/code/StringOperations.java112
-rw-r--r--java/code/StudentsArray.java91
13 files changed, 1129 insertions, 0 deletions
diff --git a/java/code/AddTwoNumbers.java b/java/code/AddTwoNumbers.java
new file mode 100644
index 0000000..3c1b3e8
--- /dev/null
+++ b/java/code/AddTwoNumbers.java
@@ -0,0 +1,81 @@
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Scanner;
+import java.util.InputMismatchException;
+
+class Number {
+    private double value;
+    Number(double n) {
+        value = n;
+    }
+    double valueOf() {
+        return value;
+    }
+}
+
+class ArithmeticOperations {
+    static Number add(Number a, Number b) {
+        return new Number(a.valueOf() + b.valueOf());
+    }
+}
+
+class AddTwoNumbers {
+    static void process(double a, double b) {
+        Number n1 = new Number(a), n2 = new Number(b);
+        System.out.println(n1.valueOf() + " + " + n2.valueOf() + " = " +
+            ArithmeticOperations.add(n1, n2).valueOf());
+    }
+}
+
+class AddTwoNumbersCLI extends AddTwoNumbers {
+    public static void main(String args[]) {
+        if (args.length != 2) {
+            System.err.println("Usage: AddTwoNumbersCLI first-number second-number");
+            System.exit(1);
+        }
+        try {
+            System.out.println("Taking input from CLI arguments:");
+            var v1 = Double.parseDouble(args[0]);
+            var v2 = Double.parseDouble(args[1]);
+            process(v1, v2);
+        } catch (NumberFormatException e) {
+            System.err.println("Invalid numbers");
+        }
+    }
+}
+
+class AddTwoNumbersScan extends AddTwoNumbers {
+    public static void main(String args[]) {
+        try {
+            System.out.println("Taking input using java.util.Scanner:");
+            var sc = new Scanner(System.in);
+            System.out.print("Enter first number: ");
+            var v1 = sc.nextDouble();
+            System.out.print("Enter second number: ");
+            var v2 = sc.nextDouble();
+            process(v1, v2);
+        } catch (InputMismatchException e) {
+            System.err.println("Invalid numbers");
+        }
+    }
+}
+
+class AddTwoNumbersBuf extends AddTwoNumbers {
+    public static void main(String args[]) {
+        try {
+            System.out.println("Taking input using java.io.BufferedReader:");
+            var r = new BufferedReader(new InputStreamReader(System.in));
+            System.out.print("Enter first number: ");
+            var v1 = Double.parseDouble(r.readLine());
+            System.out.print("Enter second number: ");
+            var v2 = Double.parseDouble(r.readLine());
+            process(v1, v2);
+        } catch (NumberFormatException e) {
+            System.err.println("Invalid numbers");
+        } catch (IOException e) {
+            System.err.println("I/O error occured while reading input.");
+        }
+    }
+}
+
diff --git a/java/code/ArraySearch.java b/java/code/ArraySearch.java
new file mode 100644
index 0000000..a9fab5e
--- /dev/null
+++ b/java/code/ArraySearch.java
@@ -0,0 +1,130 @@
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.InputMismatchException;
+import java.util.function.BiFunction;
+
+class Array {
+    private double[] arr;
+    Array() throws Exception {
+        takeInput();
+    }
+    void takeInput() throws Exception {
+        Scanner sc = new Scanner(System.in);
+        System.out.print("Enter the length: ");
+        int size = sc.nextInt();
+        if (size < 0)
+            throw new Exception("Array length can not be negative");
+        arr = new double[size];
+        System.out.print("Enter the array elements: ");
+        for (int i = 0; i < size; i++)
+            arr[i] = sc.nextDouble();
+    }
+    void display() {
+        System.out.print("The array elements are:");
+        for (int i = 0; i < arr.length; i++)
+            System.out.print(" " + arr[i]);
+        System.out.println();
+    }
+    double get(int i) throws IndexOutOfBoundsException {
+        return arr[i];
+    }
+    void set(int i, double val) throws IndexOutOfBoundsException {
+        arr[i] = val;
+    }
+    void sort() {
+        Arrays.sort(arr);
+    }
+    int size() { return arr.length; }
+}
+
+class ArrayOperations {
+    static int linearSearch(Array arr, double item) {
+        int size = arr.size();
+        for (int i = 0; i < size; i++) {
+            if (arr.get(i) == item)
+                return i;
+        }
+        return -1;
+    }
+    static int binarySearch(Array arr, double item) {
+        int size = arr.size();
+        int leftIndex = 0, rightIndex = size - 1;
+        while (leftIndex <= rightIndex) {
+            int midIndex = leftIndex + (rightIndex - leftIndex) / 2;
+            double midValue = arr.get(midIndex);
+            if (item == midValue) {
+                return midIndex;
+            } else if (item < midValue) {
+                rightIndex = midIndex - 1;
+            } else {
+                leftIndex = midIndex + 1;
+            }
+        }
+        return -1;
+    }
+}
+
+class ArraySearch {
+    static void menu() {
+        System.out.println(
+            "Menu:\n" +
+            " 1. Re-enter array\n" +
+            " 2. Display array elements\n" +
+            " 3. Perform linear search\n" +
+            " 4. Perform binary search\n" +
+            " 5. Exit\n");
+    }
+    static void performSearch(Scanner sc, Array arr, BiFunction<Array, Double, Integer> searcher) {
+        arr.display();
+        System.out.print("Enter the element to find: ");
+        double elem = sc.nextDouble();
+        int idx = searcher.apply(arr, elem);
+        if (idx == -1) {
+            System.out.println("The element " + elem + " was not found in the array.");
+        } else {
+            System.out.println("The element " + elem + " was found in the array at position " + (idx + 1) + ".");
+        }
+    }
+    public static void main(String[] args) {
+        Scanner sc = new Scanner(System.in);
+        System.out.println("Menu-driven program of array searching\n");
+        System.out.println("Enter the array:");
+        Array arr = null;
+        while (true) {
+            try {
+                if (arr == null) arr = new Array();
+                menu();
+                System.out.print("Enter your choice: ");
+                int choice = sc.nextInt();
+                switch (choice) {
+                case 1:
+                    arr.takeInput();
+                    arr.display();
+                    break;
+                case 2:
+                    arr.display();
+                    break;
+                case 3:
+                    performSearch(sc, arr, ArrayOperations::linearSearch);
+                    break;
+                case 4:
+                    System.out.println("Array is sorted before binary search.");
+                    arr.sort();
+                    performSearch(sc, arr, ArrayOperations::binarySearch);
+                    break;
+                case 5:
+                    System.out.println("Bye.");
+                    return;
+                default:
+                    System.out.println("Invalid choice, try again.");
+                }
+            } catch (InputMismatchException e) {
+                System.err.println("Error: Invalid input, try again");
+                sc.nextLine();
+            } catch (Exception e) {
+                System.err.println("Error: " + e.getMessage());
+            }
+        }
+    }
+}
+
diff --git a/java/code/ArraySort.java b/java/code/ArraySort.java
new file mode 100644
index 0000000..9bee74e
--- /dev/null
+++ b/java/code/ArraySort.java
@@ -0,0 +1,113 @@
+import java.util.Scanner;
+import java.util.InputMismatchException;
+import java.util.function.Consumer;
+
+class Array {
+    private double[] arr;
+    Array() throws Exception { takeInput(); }
+    void takeInput() throws Exception {
+        Scanner sc = new Scanner(System.in);
+        System.out.print("Enter the length: ");
+        int size = sc.nextInt();
+        if (size < 0)
+            throw new Exception("Invalid length, can not be negative");
+        arr = new double[size];
+        System.out.print("Enter the array elements: ");
+        for (int i = 0; i < size; i++)
+            arr[i] = sc.nextDouble();
+    }
+    void display() {
+        System.out.print("The array elements are:");
+        for (int i = 0; i < arr.length; i++)
+            System.out.print(" " + arr[i]);
+        System.out.println();
+    }
+    double get(int i) { return arr[i]; }
+    void set(int i, double val) { arr[i] = val; }
+    int size() { return arr.length; }
+}
+
+class ArrayOperations {
+    static void bubbleSort(Array arr) {
+        int n = arr.size();
+        for (int i = 0; i < n - 1; i++) {
+            for (int j = 0; j < n - i - 1; j++) {
+                double x = arr.get(j), xp = arr.get(j + 1);
+                if (x > xp) {
+                    arr.set(j, xp);
+                    arr.set(j + 1, x);
+                }
+            }
+        }
+    }
+    static void selectionSort(Array arr) {
+        int n = arr.size();
+        for (int i = 0; i < n - 1; i++) {
+            int minidx = i;
+            for (int j = i + 1; j < n; j++)
+                if (arr.get(j) < arr.get(minidx))
+                    minidx = j;
+            double tmp = arr.get(minidx);
+            arr.set(minidx, arr.get(i));
+            arr.set(i, tmp);
+        }
+    }
+}
+
+class ArraySort {
+    static void menu() {
+        System.out.println(
+            "Menu:\n" +
+            " 1. Re-enter array\n" +
+            " 2. Display array elements\n" +
+            " 3. Perform bubble sort\n" +
+            " 4. Perform selection sort\n" +
+            " 5. Exit\n");
+    }
+    static void performSort(Array arr, Consumer<Array> sorter) {
+        System.out.print("Before sorting: ");
+        arr.display();
+        sorter.accept(arr);
+        System.out.print("After sorting: ");
+        arr.display();
+    }
+    public static void main(String[] args) {
+        Scanner sc = new Scanner(System.in);
+        System.out.println("Menu-driven program of array operations\n");
+        System.out.println("Enter the array:");
+        Array arr = null;
+        while (true) {
+            try {
+                if (arr == null) arr = new Array();
+                menu();
+                System.out.print("Enter your choice: ");
+                int choice = sc.nextInt();
+                switch (choice) {
+                case 1:
+                    arr.takeInput();
+                    arr.display();
+                    break;
+                case 2:
+                    arr.display();
+                    break;
+                case 3:
+                    performSort(arr, ArrayOperations::bubbleSort);
+                    break;
+                case 4:
+                    performSort(arr, ArrayOperations::selectionSort);
+                    break;
+                case 5:
+                    System.out.println("Bye.");
+                    return;
+                default:
+                    System.err.println("Invalid choice, try again.");
+                }
+            } catch (InputMismatchException e) {
+                System.err.println("Error: Invalid input, try again");
+            } catch (Exception e) {
+                System.err.println("Error: " + e.getMessage());
+            }
+        }
+    }
+}
+
diff --git a/java/code/BankAccountExample.java b/java/code/BankAccountExample.java
new file mode 100644
index 0000000..487a564
--- /dev/null
+++ b/java/code/BankAccountExample.java
@@ -0,0 +1,155 @@
+import java.util.ArrayList;
+import java.util.Scanner;
+
+class BankAccount {
+    String name, address;
+    long accountNo;
+    double balance;
+    BankAccount(String name, String address, long accountNo, double balance) {
+        this.name = name;
+        this.address = address;
+        this.accountNo = accountNo;
+        this.balance = balance;
+    }
+    static BankAccount takeInput(Scanner sc) {
+        System.out.println("Enter details of bank account:");
+        System.out.print("  Name: ");
+        String name = sc.nextLine();
+        System.out.print("  Address: ");
+        String address = sc.nextLine();
+        System.out.print("  Account No.: ");
+        long accountNo = sc.nextLong();
+        System.out.print("  Balance: ");
+        double balance = sc.nextDouble();
+        sc.skip("\n");
+        return new BankAccount(name, address, accountNo, balance);
+    }
+    long getAccountNo() { return accountNo; }
+    double getBalance() { return balance; }
+    void deposit(double amount) throws IllegalArgumentException {
+        if (amount < 0.0)
+            throw new IllegalArgumentException(
+                    "Can not deposit negative amount of money. Use withdraw() instead.");
+        balance += amount;
+    }
+    static String formatBalance(double value) { return String.format("%.2f", value); }
+    void withdraw(double amount) throws Exception {
+        if (amount < 0.0)
+            throw new IllegalArgumentException(
+                    "Can not withdraw negative amount of money. Use deposit() instead.");
+        else if (amount > balance)
+            throw new Exception(
+                "Available balance: " + formatBalance(balance) +
+                " but tried to withdraw: " + formatBalance(amount) +
+                " with the shortfall of " + formatBalance(amount - balance));
+        balance -= amount;
+    }
+    void display() {
+        System.out.println(
+            "Customer details: \n" +
+            "  Name: " + name + "\n" +
+            "  Address: " + address + "\n" +
+            "  Account Number: " + accountNo + "\n" +
+            "  Balance: " + formatBalance(balance) + "\n");
+    }
+    static BankAccount lookup(ArrayList<BankAccount> acs, long accountNo) {
+        for (var ac : acs) {
+            if (ac.getAccountNo() == accountNo) return ac;
+        }
+        return null;
+    }
+}
+
+class BankAccountExample {
+    static void menu() {
+        System.out.println(
+            "Menu:\n" +
+            " 1. Create bank account\n" +
+            " 2. Display bank account details\n" +
+            " 3. Deposit money\n" +
+            " 4. Withdraw money\n" +
+            " 5. Exit\n");
+    }
+    static BankAccount findAccount(Scanner sc, ArrayList<BankAccount> accounts) {
+        System.out.print("Enter account number: ");
+        long accountNo = sc.nextLong();
+        sc.skip("\n");
+        var ac = BankAccount.lookup(accounts, accountNo);
+        if (ac == null) {
+            System.out.println("Could not find a bank account with the given account number.");
+            System.out.println("Try again.\n");
+            return null;
+        }
+        return ac;
+    }
+    public static void main(String[] args) {
+        Scanner sc = new Scanner(System.in);
+        System.out.println("Menu-driven program for operating bank accounts:");
+        var accounts = new ArrayList<BankAccount>();
+        while (true) {
+            menu();
+            System.out.print("Enter your choice: ");
+            int choice = sc.nextInt();
+            sc.skip("\n");
+            double amount;
+            BankAccount ac;
+            switch (choice) {
+            case 1:
+                ac = BankAccount.takeInput(sc);
+                if (BankAccount.lookup(accounts, ac.getAccountNo()) != null) {
+                    System.out.println("An account already exists with the same account number.");
+                    System.out.println("Can not create account, try again.");
+                    continue;
+                }
+                accounts.add(ac);
+                break;
+            case 2:
+                ac = findAccount(sc, accounts);
+                if (ac == null) continue;
+                ac.display();
+                break;
+            case 3:
+                ac = findAccount(sc, accounts);
+                if (ac == null) continue;
+                System.out.print("Enter the amount to deposit: ");
+                amount = sc.nextDouble();
+                try {
+                    double balanceBefore = ac.getBalance();
+                    ac.deposit(amount);
+                    double balanceAfter = ac.getBalance();
+                    System.out.println("Operation successful.");
+                    System.out.println(
+                        "Balance:\n" +
+                        "  before: " + BankAccount.formatBalance(balanceBefore) + "\n" +
+                        "  after: " + BankAccount.formatBalance(balanceAfter) + "\n");
+                } catch (Exception e) {
+                    System.out.println("Error: " + e.getMessage());
+                }
+                break;
+            case 4:
+                ac = findAccount(sc, accounts);
+                if (ac == null) continue;
+                System.out.print("Enter the amount to withdraw: ");
+                amount = sc.nextDouble();
+                try {
+                    double balanceBefore = ac.getBalance();
+                    ac.withdraw(amount);
+                    double balanceAfter = ac.getBalance();
+                    System.out.println("Operation successful.");
+                    System.out.println(
+                        "Balance:\n" +
+                        "  before: " + BankAccount.formatBalance(balanceBefore) + "\n" +
+                        "  after: " + BankAccount.formatBalance(balanceAfter) + "\n");
+                } catch (Exception e) {
+                    System.out.println("Error: " + e.getMessage());
+                }
+                break;
+            case 5:
+                System.out.println("Bye.");
+                return;
+            default:
+                System.out.println("Invalid choice, try again");
+            }
+        }
+    }
+}
diff --git a/java/code/ComplexCalculations.java b/java/code/ComplexCalculations.java
new file mode 100644
index 0000000..5ce056f
--- /dev/null
+++ b/java/code/ComplexCalculations.java
@@ -0,0 +1,43 @@
+import java.util.Scanner;
+import java.util.InputMismatchException;
+
+class Complex {
+    double real, imag;
+    Complex(double r, double i) {
+        real = r;
+        imag = i;
+    }
+    @Override
+    public String toString() {
+        return real + (imag > 0.0 ? " + " : " - ") + Math.abs(imag) + "i";
+    }
+}
+
+class ComplexOperations {
+    static Complex add(Complex a, Complex b) {
+        return new Complex(a.real + b.real, a.imag + b.imag);
+    }
+}
+
+class ComplexCalculations {
+    static Complex takeComplexInput() {
+        var sc = new Scanner(System.in);
+        System.out.print("  Enter real part: ");
+        var real = sc.nextDouble();
+        System.out.print("  Enter imaginary part: ");
+        var imaginary = sc.nextDouble();
+        return new Complex(real, imaginary);
+    }
+    public static void main(String args[]) {
+        try {
+            System.out.println("First complex number:-");
+            var x = takeComplexInput();
+            System.out.println("Second complex number:-");
+            var y = takeComplexInput();
+            System.out.println("(" + x + ") + (" + y + ") = " + ComplexOperations.add(x, y));
+        } catch (InputMismatchException e) {
+            System.err.println("Invalid number given as input");
+        }
+    }
+}
+
diff --git a/java/code/ConeCalculations.java b/java/code/ConeCalculations.java
new file mode 100644
index 0000000..1b8e64c
--- /dev/null
+++ b/java/code/ConeCalculations.java
@@ -0,0 +1,55 @@
+import java.util.Scanner;
+import java.util.InputMismatchException;
+
+class Cone {
+    double radius, height;
+    Cone(double r, double h) {
+        radius = r;
+        height = h;
+    }
+    double volume() {
+        return Math.PI * radius * radius * height / 3.0;
+    }
+    double surfaceArea() {
+        return Math.PI * radius * (radius + Math.sqrt(height * height + radius * radius));
+    }
+    void display() {
+        System.out.println("A cone with radius " + radius + " units and height " + height + " units has surface area " + surfaceArea() + " square units and volume " + volume() + " cubic units.");
+    }
+}
+
+class ConeCalculationsCLI {
+    public static void main(String args[]) {
+        if (args.length != 2) {
+            System.err.println("Usage: ConeCalculationsCLI radius height");
+            System.exit(1);
+        }
+        try {
+            var radius = Double.parseDouble(args[0]);
+            var height = Double.parseDouble(args[1]);
+            var c = new Cone(radius, height);
+            c.display();
+        } catch (NumberFormatException e) {
+            System.err.println("Invalid number given as input");
+            System.exit(1);
+        }
+    }
+}
+
+class ConeCalculationsScan {
+    public static void main(String args[]) {
+        try {
+            var sc = new Scanner(System.in);
+            System.out.print("Enter radius: ");
+            var radius = sc.nextDouble();
+            System.out.print("Enter height: ");
+            var height = sc.nextDouble();
+            var c = new Cone(radius, height);
+            c.display();
+        } catch (InputMismatchException e) {
+            System.err.println("Invalid number given as input");
+            System.exit(1);
+        }
+    }
+}
+
diff --git a/java/code/CylinderCalculations.java b/java/code/CylinderCalculations.java
new file mode 100644
index 0000000..fac5457
--- /dev/null
+++ b/java/code/CylinderCalculations.java
@@ -0,0 +1,52 @@
+import java.util.Scanner;
+import java.util.InputMismatchException;
+
+class Cylinder {
+    double radius, height;
+    Cylinder(double r, double h) {
+        radius = r;
+        height = h;
+    }
+    double volume() {
+        return Math.PI * radius * radius * height;
+    }
+    double surfaceArea() {
+        return 2 * Math.PI * radius * height * (radius + height);
+    }
+    void display() {
+        System.out.println("A cylinder with radius " + radius + " units and height " + height + " units, has volume of " + volume() + " cubic units and surface area of " + surfaceArea() + " square units.");
+    }
+}
+
+class CylinderCalculationsCLI {
+    public static void main(String args[]) {
+        if (args.length != 2) {
+            System.err.println("Usage: CylinderCalculationsCLI radius height");
+            System.exit(1);
+        }
+        try {
+            var radius = Double.parseDouble(args[0]);
+            var height = Double.parseDouble(args[1]);
+            var cy = new Cylinder(radius, height);
+            cy.display();
+        } catch (NumberFormatException e) {
+            System.err.println("Invalid numbers");
+        }
+    }
+}
+
+class CylinderCalculationsScan {
+    public static void main(String args[]) {
+        try {
+            var sc = new Scanner(System.in);
+            System.out.print("Enter radius: ");
+            var radius = sc.nextDouble();
+            System.out.print("Enter height: ");
+            var height = sc.nextDouble();
+            var cy = new Cylinder(radius, height);
+            cy.display();
+        } catch (InputMismatchException e) {
+            System.err.println("Invalid numbers");
+        }
+    }
+}
diff --git a/java/code/FindNumberInArray.java b/java/code/FindNumberInArray.java
new file mode 100644
index 0000000..2bf7f1a
--- /dev/null
+++ b/java/code/FindNumberInArray.java
@@ -0,0 +1,72 @@
+import java.util.Scanner;
+import java.util.InputMismatchException;
+
+class Number {
+    private double value;
+    Number(double n) {
+        value = n;
+    }
+    double valueOf() {
+        return value;
+    }
+    @Override
+    public boolean equals(Object o) {
+        if (o instanceof Number) {
+            return value == ((Number)o).valueOf();
+        }
+        return false;
+    } 
+}
+
+class NumberArray {
+    Number[] array;
+    NumberArray(double arr[]) {
+        array = new Number[arr.length];
+        for (int i = 0; i < arr.length; i++) {
+            array[i] = new Number(arr[i]);
+        }
+    }
+    int find(Number n) {
+        for (int i = 0; i < array.length; i++) {
+            if (array[i].equals(n)) {
+                return i;
+            }
+        }
+        return -1;
+    }
+    void display() {
+        System.out.print("An array of numbers with " + array.length + " elements:");
+        for (int i = 0; i < array.length; i++) {
+            System.out.print(" " + array[i].valueOf());
+        }
+        System.out.println();
+    }
+}
+
+class FindNumberInArray {
+    public static void main(String args[]) {
+        try {
+            var sc = new Scanner(System.in);
+            System.out.print("Enter length: ");
+            var length = sc.nextInt();
+            var arr = new double[length];
+            System.out.print("Enter array elements: ");
+            for (int i = 0; i < length; i++) {
+                arr[i] = sc.nextDouble();
+            }
+            var narr = new NumberArray(arr);
+            System.out.print("Given: ");
+            narr.display();
+            System.out.print("Enter element to find in array: ");
+            var num = new Number(sc.nextDouble());
+            var pos = narr.find(num);
+            if (pos == -1) {
+                System.out.println("Could not find the number " + num.valueOf() + " in the array.");
+                return;
+            }
+            System.out.println("The number " + num.valueOf() + " was found in the array at position " + (pos + 1) + ".");
+        } catch (InputMismatchException e) {
+            System.err.println("Invalid number given as input");
+        }
+    }
+}
diff --git a/java/code/MatrixOperations.java b/java/code/MatrixOperations.java
new file mode 100644
index 0000000..9cc6768
--- /dev/null
+++ b/java/code/MatrixOperations.java
@@ -0,0 +1,172 @@
+import java.util.ArrayList;
+import java.util.Scanner;
+import java.util.InputMismatchException;
+import java.util.function.BinaryOperator;
+
+class Matrix {
+    private int rows, cols;
+    private float mat[][];
+    Matrix(int r, int c) {
+        rows = r;
+        cols = c;
+        mat = new float[rows][cols];
+    }
+    int rows() { return rows; }
+    int cols() { return cols; }
+    float get(int i, int j) { return mat[i][j]; }
+    void set(int i, int j, float v) { mat[i][j] = v; }
+    void input(Scanner sc) {
+        for (int i = 0; i < rows; i++) {
+            for (int j = 0; j < cols; j++) {
+                mat[i][j] = sc.nextFloat();
+            }
+        }	
+    }
+    void display() {
+        for (int i = 0; i < rows; i++) {
+            for (int j = 0; j < cols; j++) {
+                System.out.format(mat[i][j] + "\t");
+            }
+            System.out.println();
+        }
+    }
+}
+
+class MatrixOperations {
+    static Matrix add(Matrix x, Matrix y) throws IllegalArgumentException {
+        int xr = x.rows(), xc = x.cols(), yr = y.rows(), yc = y.cols();
+        if (!((xr == yr) && (xc == yc))) {
+            throw new IllegalArgumentException("Incompatible matrix arguments for addition");
+        }
+        Matrix s = new Matrix(xr, yc);
+        for (int i = 0; i < xr; i++) {
+            for (int j = 0; j < yc; j++) {
+                var v = x.get(i, j) + y.get(i, j);
+                s.set(i, j, v);
+            }
+        }
+        return s;
+    }
+    static Matrix subtract(Matrix x, Matrix y) throws IllegalArgumentException {
+        int xr = x.rows(), xc = x.cols(), yr = y.rows(), yc = y.cols();
+        if (!((xr == yr) && (xc == yc))) {
+            throw new IllegalArgumentException("Incompatible matrix arguments for subtraction");
+        }
+        Matrix d = new Matrix(xr, yc);
+        for (int i = 0; i < xr; i++) {
+            for (int j = 0; j < yc; j++) {
+                var v = x.get(i, j) - y.get(i, j);
+                d.set(i, j, v);
+            }
+        }
+        return d;
+    }
+    static Matrix multiply(Matrix x, Matrix y) throws IllegalArgumentException {
+        int xr = x.rows(), xc = x.cols(), yr = y.rows(), yc = y.cols();
+        if (xc != yr) {
+            throw new IllegalArgumentException("Incompatible matrix arguments for multiplication");
+        }
+        Matrix p = new Matrix(xr, yc);
+        for (int i = 0; i < xr; i++) {
+            for (int j = 0; j < yc; j++) {
+                float v = 0;
+                for (int k = 0; k < xc; k++) {
+                    v += x.get(i, k) * y.get(k, j);
+                }
+                p.set(i, j, v);
+            }
+        }
+        return p;
+    }
+}
+
+class MatrixOperationsCLI {
+    static void menu() {
+        System.out.println(
+            "Menu options:\n" +
+            " 1. Matrix input\n" +
+            " 2. Matrix display\n" +
+            " 3. Matrix addition\n" +
+            " 4. Matrix subtraction\n" +
+            " 5. Matrix multiplication\n" +
+            " 6. Exit");
+    }
+    static Matrix takeMatrix(Scanner sc) {
+        System.out.print("Enter number of rows and columns: ");
+        var rows = sc.nextInt();
+        var cols = sc.nextInt();
+        var m = new Matrix(rows, cols);
+        System.out.println("Enter the matrix elements: ");
+        m.input(sc);
+        return m;
+    }
+    static void displayMatrix(Scanner sc, ArrayList<Matrix> ms) {
+        var size = ms.size();
+        System.out.print("Enter which matrix to display " +
+                         "(out of " + size + " matrices): ");
+        var index = sc.nextInt() - 1;
+        if (index < 0 || index > size) {
+            System.err.println("Invalid index of matrix");
+            return;
+        }
+        System.out.println("The matrix " + (index + 1) + ":");
+        ms.get(index).display();
+    }
+    static void operate(Scanner sc, ArrayList<Matrix> ms, String opName, BinaryOperator<Matrix> op) {
+        var size = ms.size();
+        System.out.print("Enter which two matrices to " + opName +
+                         " (out of " + size + " matrices): ");
+        int xi = sc.nextInt() - 1, yi = sc.nextInt() - 1;
+        if (xi < 0 || xi > size || yi < 0 || yi > size) {
+            System.err.println("Invalid index of matrix");
+            return;
+        }
+        try {
+            var m = op.apply(ms.get(xi), ms.get(yi));
+            ms.add(m);
+            System.out.println("The resulting matrix " + (size + 1) + ":");
+            m.display();
+        } catch (IllegalArgumentException e) {
+            System.out.println("Error in the operation: " + e.getMessage());
+        }
+    }
+    public static void main(String args[]) {
+        var sc = new Scanner(System.in);
+        var ms = new ArrayList<Matrix>(); 
+        System.out.println("Menu-driven program for matrix operations");
+        while (true) {
+            try {
+                menu();
+                System.out.print("Enter your choice: ");
+                var choice = sc.nextInt();
+                switch (choice) {
+                case 1:
+                    ms.add(takeMatrix(sc));
+                    break;
+                case 2:
+                    displayMatrix(sc, ms);
+                    break;
+                case 3:
+                    operate(sc, ms, "add", MatrixOperations::add);
+                    break;
+                case 4:
+                    operate(sc, ms, "subtract", MatrixOperations::subtract);
+                    break;
+                case 5:
+                    operate(sc, ms, "multiply", MatrixOperations::multiply);
+                    break;
+                case 6:
+                    System.out.println("Bye");
+                    return;
+                default:
+                    System.err.println("Invalid choice, try again.");
+                    break;
+                }
+            } catch (InputMismatchException e) {
+                System.err.println("Invalid input, try again.");
+            } catch (Exception e) {
+                System.err.println("Error: " + e.getMessage());
+            }
+        }
+    }
+}
diff --git a/java/code/SingletonExample.java b/java/code/SingletonExample.java
new file mode 100644
index 0000000..68e5655
--- /dev/null
+++ b/java/code/SingletonExample.java
@@ -0,0 +1,23 @@
+class Singleton {
+    private static Singleton instance;
+    private Singleton() {
+        System.out.println("Creating singleton instance");
+    }
+    public static Singleton getInstance() {
+        if (instance == null) {
+            instance = new Singleton();
+        }
+        System.out.println("Providing singleton instance");
+        return instance;
+    }
+}
+
+class SingletonExample {
+    public static void main(String[] args) {
+        Singleton s1 = Singleton.getInstance();
+        Singleton s2 = Singleton.getInstance();
+        if (s1 == s2)
+            System.out.println("The singleton instances are identical.");
+    }
+}
+
diff --git a/java/code/StaticExecution.java b/java/code/StaticExecution.java
new file mode 100644
index 0000000..7aa19c8
--- /dev/null
+++ b/java/code/StaticExecution.java
@@ -0,0 +1,30 @@
+import java.util.Random;
+
+class StaticExample {
+    private static int objectCount = 0;
+    static int getObjectCount() { return objectCount; }
+    static {
+        System.out.println("Executing static block in StaticExample");
+    }
+    StaticExample() {
+        if (objectCount == 0)
+            System.out.println("Executing StaticExample constructor for the first time");
+        objectCount++;
+    }
+}
+
+class StaticExecution {
+    static {
+        System.out.println("Executing static block in StaticExecution");
+    }
+    public static void main(String args[]) {
+        System.out.println("Executing static main method in StaticExecution");
+        int c = new Random().nextInt(10) + 1;
+        for (int i = 0; i < c; i++) {
+            var ex = new StaticExample();
+        }
+        System.out.println("The number of objects of StaticExample created: " +
+            StaticExample.getObjectCount());
+    }
+}
+
diff --git a/java/code/StringOperations.java b/java/code/StringOperations.java
new file mode 100644
index 0000000..de817ce
--- /dev/null
+++ b/java/code/StringOperations.java
@@ -0,0 +1,112 @@
+import java.util.Scanner;
+
+class MyString {
+    String str;
+
+    MyString(String s) { str = s; }
+
+    String valueOf() { return str; }
+
+    int countWords() {
+        int count = 0, size = str.length();
+        enum state { WORD, SPACE };
+        state st = state.WORD;
+        for (int i = 0; i < size; i++) {
+            char c = str.charAt(i);
+            if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
+                st = state.SPACE;
+            } else if (st != state.WORD) {
+                st = state.WORD;
+                count++;
+            }
+        }
+        return count;
+    }
+
+    MyString reverse() {
+        char[] arr = str.toCharArray();
+        int end = arr.length - 1;
+        for (int i = 0; i < arr.length / 2; i++, end--) {
+            char tmp = arr[i];
+            arr[i] = arr[end];
+            arr[end] = tmp;
+        }
+        return new MyString(String.copyValueOf(arr));
+    }
+    
+    MyString toLowerCase() {
+        char[] arr = str.toCharArray();
+        char[] narr = new char[arr.length];
+        for (int i = 0; i < arr.length; i++) {
+            char c = arr[i];
+            if ('A' <= c && c <= 'Z') c += 'a' - 'A';
+            narr[i] = c;
+        }
+        return new MyString(String.copyValueOf(narr));
+    }
+    
+    boolean equals(MyString ms) {
+        char[] arr1 = str.toCharArray();
+        char[] arr2 = ms.valueOf().toCharArray();
+        if (arr1.length != arr2.length) return false;
+        for (int i = 0; i < arr1.length; i++) {
+            if (arr1[i] != arr2[i]) return false;
+        }
+        return true;
+    }
+
+    boolean isCaseInsensitivePalindrome() {
+        return str.toLowerCase().equals(reverse().toLowerCase().valueOf());
+    }
+}
+
+class StringOperations {
+    static void menu() {
+        System.out.println(
+            "Options:\n" +
+            " 1. Re-enter a string\n" +
+            " 2. Display the string\n" +
+            " 3. Count words in the string\n" +
+            " 4. Reverse the string\n" +
+            " 5. Case-insensitively check whether the string is palindrome or not\n" +
+            " 6. Exit\n");
+    }
+    public static void main(String[] args) {
+        Scanner sc = new Scanner(System.in);
+        System.out.println("Menu-driven program for string operations");
+        System.out.print("Enter a string: ");
+        MyString ms = new MyString(sc.nextLine());
+        while (true) {
+            menu();
+            System.out.print("Enter your choice: ");
+            int choice = sc.nextInt();
+            sc.skip("\n");
+            switch (choice) {
+            case 1:
+                System.out.print("Enter a string: ");
+                ms = new MyString(sc.nextLine());
+                break;
+            case 2:
+                System.out.println("The string is: " + ms.valueOf());
+                break;
+            case 3:
+                int count = ms.countWords();
+                System.out.println("The string has " + count + " words.");
+                break;
+            case 4:
+                System.out.println("The given string reversed is: " + ms.reverse().valueOf());
+                break;
+            case 5:
+                System.out.println("The given string is" +
+                        (ms.isCaseInsensitivePalindrome() ? "" : "n't") +
+                        " case-insensitively palindrome.");
+                break;
+            case 6:
+                System.out.println("Bye.");
+                return;
+            default:
+                System.out.println("Invalid choice, try again.");
+            }
+        }
+    }
+}
diff --git a/java/code/StudentsArray.java b/java/code/StudentsArray.java
new file mode 100644
index 0000000..b526a44
--- /dev/null
+++ b/java/code/StudentsArray.java
@@ -0,0 +1,91 @@
+import java.util.*;
+
+class Subject {
+    String title;
+    int theory;
+
+    Subject(String title, int theory) {
+        this.title = title;
+        this.theory = theory;
+    }
+
+    static Subject input(Scanner sc) {
+        System.out.println("Enter details of subject:");
+        System.out.print("Enter title: ");
+        String title = sc.nextLine();
+        System.out.print("Enter theory marks: ");
+        int theory = sc.nextInt();
+        sc.skip("\n");
+        return new Subject(title, theory);
+    }
+    int getTheoryMarks() { return theory; }
+
+    void display() {
+        System.out.println("  Marks obtained in " + title + ": " + theory);
+    }
+}
+
+class Student {
+    final static int SUBJECT_COUNT = 3;
+    long roll;
+    String name;
+    String stream;
+    Subject[] subjects;
+
+    Student(long roll, String name, String stream, Subject[] subjects) {
+        this.roll = roll;
+        this.name = name;
+        this.stream = stream;
+        this.subjects = subjects;
+    }
+
+    static Student input(Scanner sc) {
+        System.out.println("Enter the details of the student:");
+        System.out.print("Enter Roll no.: ");
+        long roll = sc.nextLong();
+        sc.skip("\n");
+        System.out.print("Enter name: ");
+        String name = sc.nextLine();
+        System.out.print("Enter stream: ");
+        String stream = sc.nextLine();
+        Subject[] subjects = new Subject[SUBJECT_COUNT];
+        for (int i = 0; i < subjects.length; i++) {
+            System.out.print("For subject " + (i + 1) + ": ");
+            subjects[i] = Subject.input(sc);
+        }
+        return new Student(roll, name, stream, subjects);
+    }
+
+    void display() {
+        System.out.println("Student details:");
+        System.out.println("  Roll No.: " + roll);
+        System.out.println("  Name: " + name);
+        System.out.println("  Stream: " + stream);
+        int totalMarks = 0;
+        for (Subject subject : subjects) {
+            subject.display();
+            totalMarks += subject.getTheoryMarks();
+        }
+        double average = ((double)totalMarks) / subjects.length;
+        System.out.println("  Average percentage: " + String.format("%.2f", average) + "%");
+    }
+}
+
+class StudentsArray {
+    public static void main(String[] args) {
+        var sc = new Scanner(System.in);
+        System.out.println("Enter the number of students: ");
+        Student[] students = new Student[sc.nextInt()];
+        System.out.println("Enter the details of the students:");
+        for (int i = 0; i < students.length; i++) {
+            System.out.print("For student " + (i + 1) + ": ");
+            students[i] = Student.input(sc);
+        }
+        System.out.println("Displaying the details of the students:");
+        for (int i = 0; i < students.length; i++) {
+            System.out.println("\nFor student " + (i + 1) + ": ");
+            students[i].display();
+        }
+    }
+}
+