Essential Java Programming Examples and Core Concepts

Usage of Static and Global Variables

class VariableDemo {
    private int instanceVar = 10;
    private static int staticVar = 20;

    public void displayVariables() {
        int localVar = 30;

        System.out.println("Instance Variable: " + instanceVar);
        System.out.println("Static Variable: " + staticVar);
        System.out.println("Local Variable: " + localVar);
    }

    public static void main(String[] args) {
        VariableDemo demo = new VariableDemo();
        demo.displayVariables();

        System.out.println("Accessing static variable from main: " + VariableDemo.staticVar);
        VariableDemo.staticVar = 25;

        System.out.println("Updated static variable: " + VariableDemo.staticVar);
        demo.displayVariables();
    }
}

String Operations: Length, Concatenation, and Substring

public class StringOperations {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";

        int lengthStr1 = str1.length();
        int lengthStr2 = str2.length();

        System.out.println("Length of str1: " + lengthStr1);
        System.out.println("Length of str2: " + lengthStr2);

        String concatenatedString = str1 + " " + str2;
        System.out.println("Concatenated String: " + concatenatedString);

        StringBuilder sb = new StringBuilder();
        sb.append(str1).append(" ").append(str2);

        System.out.println("Concatenated String using StringBuilder: " + sb.toString());

        String substring = concatenatedString.substring(0, 5);
        System.out.println("Substring of concatenated string: " + substring);

        String anotherSubstring = concatenatedString.substring(6);
        System.out.println("Another substring of concatenated string: " + anotherSubstring);
    }
}

Default and Parameterized Constructors

class Rectangle {
    private int length;
    private int width;

    // Default Constructor
    public Rectangle() {
        length = 1;
        width = 1;
    }

    // Parameterized Constructor
    public Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    public int calculateArea() {
        return length * width;
    }

    public void displayDimensions() {
        System.out.println("Length = " + length + ", Width = " + width);
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Rectangle rect1 = new Rectangle();

        System.out.println("Rectangle 1:");
        rect1.displayDimensions();
        System.out.println("Area = " + rect1.calculateArea());

        Rectangle rect2 = new Rectangle(5, 3);

        System.out.println("\nRectangle 2:");
        rect2.displayDimensions();
        System.out.println("Area = " + rect2.calculateArea());
    }
}

Method Overloading in Java

public class MethodOverloadingDemo {
    public int add() {
        return add(0, 0);
    }

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

    public float add(float a, float b) {
        return a + b;
    }

    public float sum() {
        return add(0.0f, 0.0f);
    }

    public static void main(String[] args) {
        MethodOverloadingDemo demo = new MethodOverloadingDemo();

        System.out.println("Sum of two integers (default): " + demo.add());
        System.out.println("Sum of two integers (5+3): " + demo.add(5, 3));
        System.out.println("Sum of two floats (default): " + demo.sum());
        System.out.println("Sum of two floats (2.5+3.5): " + demo.add(2.5f, 3.5f));
    }
}

Handling Negative Array Size Exception

import java.util.Scanner;

public class NegativeArrayDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of array: ");
        int size = scanner.nextInt();

        try {
            int[] array = new int[size];
            System.out.println("Array of size " + size + " created successfully.");
        } catch (NegativeArraySizeException e) {
            System.out.println("Error: Array size cannot be negative.");
        } finally {
            scanner.close();
        }
    }
}

Factorial of a List of Numbers from Input

public class FactorialCalculator {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Please provide numbers as command-line arguments.");
            return;
        }

        for (String arg : args) {
            try {
                int number = Integer.parseInt(arg);
                long factorial = calculateFactorial(number);
                System.out.println("Factorial of " + number + " is " + factorial);
            } catch (NumberFormatException e) {
                System.out.println("Invalid input: " + arg + " is not a valid integer.");
            }
        }
    }

    public static long calculateFactorial(int number) {
        long factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        return factorial;
    }
}

Prime Numbers Between Two Limits

import java.util.Scanner;

public class PrimeNumbersInRange {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the lower limit: ");
        int lowerLimit = scanner.nextInt();

        System.out.print("Enter the upper limit: ");
        int upperLimit = scanner.nextInt();

        System.out.println("Prime numbers between " + lowerLimit + " and " + upperLimit + " are:");

        for (int number = lowerLimit; number <= upperLimit; number++) {
            if (isPrime(number)) {
                System.out.print(number + " ");
            }
        }
        scanner.close();
    }

    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Threads Using the Runnable Interface

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - Count: " + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted: " + e.getMessage());
            }
        }
    }
}

public class ThreadUsingRunnable {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable, "Thread-1");
        Thread thread2 = new Thread(myRunnable, "Thread-2");

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

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted: " + e.getMessage());
        }
        System.out.println("All threads have finished execution.");
    }
}

Demonstrating a Division by Zero Exception

import java.util.Scanner;

public class DivisionByZeroDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter numerator: ");
        int numerator = scanner.nextInt();

        System.out.print("Enter denominator: ");
        int denominator = scanner.nextInt();

        try {
            int result = numerator / denominator;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        } finally {
            scanner.close();
        }
    }
}

Checking for Odd or Even Numbers

import java.util.Scanner;

public class OddEvenCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        if (number % 2 == 0) {
            System.out.println(number + " is even");
        } else {
            System.out.println(number + " is odd");
        }
        scanner.close();
    }
}