Advanced Java Programs with Explanation

Advanced Java Programs with Explanation

Here are examples of advanced Java programs, along with explanations:


1. Multithreading in Java

This program demonstrates how to use threads in Java.

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - " + i);
            try {
                Thread.sleep(500); // Pauses execution for 500ms
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class MultithreadingExample {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.start();
        t2.start();
    }
}

Explanation:

  • MyThread extends Thread: A custom thread class.
  • start(): Starts the thread, invoking its run() method.
  • Thread.sleep(500): Puts the thread to sleep for 500 milliseconds.

2. Reading and Writing Files

This program demonstrates file handling by writing and then reading from a file.

import java.io.*;

public class FileHandling {
    public static void main(String[] args) {
        String filePath = "example.txt";

        // Writing to a file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write("This is a sample text file.");
            writer.newLine();
            writer.write("File handling in Java is powerful.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading from a file
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • BufferedWriter and FileWriter: Used to write text to a file.
  • BufferedReader and FileReader: Used to read text from a file.
  • try-with-resources: Ensures that file streams are closed automatically.

3. Lambda Expressions

This program demonstrates the use of lambda expressions to simplify functional interfaces.

import java.util.*;

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");

        // Using a lambda expression to sort the list
        Collections.sort(names, (a, b) -> a.compareTo(b));

        // Using a lambda expression to print each element
        names.forEach(name -> System.out.println(name));
    }
}

Explanation:

  • (a, b) -> a.compareTo(b): Lambda function to compare two strings.
  • names.forEach: Iterates through the list using a lambda expression.

4. Implementing a Singleton Design Pattern

This program shows how to implement the Singleton pattern.

class Singleton {
    private static Singleton instance;

    private Singleton() {
        // Private constructor
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("Singleton instance invoked!");
    }
}

public class SingletonExample {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        singleton.showMessage();
    }
}

Explanation:

  • private static Singleton instance;: Ensures only one instance is created.
  • getInstance(): Provides access to the instance.
  • private Singleton(): Prevents instantiation from other classes.

5. JDBC Connectivity

This program connects to a database using JDBC.

import java.sql.*;

public class JDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/testdb";
        String user = "root";
        String password = "password";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connected to the database!");

            String query = "SELECT * FROM users";
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(query)) {

                while (rs.next()) {
                    System.out.println("ID: " + rs.getInt("id") +
                                       ", Name: " + rs.getString("name"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • DriverManager.getConnection: Establishes a connection to the database.
  • Statement and ResultSet: Executes queries and retrieves results.

6. Java Streams API

This program demonstrates the use of Streams for functional programming.

import java.util.*;
import java.util.stream.*;

public class StreamsExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Filtering even numbers and summing them
        int sum = numbers.stream()
                         .filter(n -> n % 2 == 0)
                         .mapToInt(n -> n)
                         .sum();

        System.out.println("Sum of even numbers: " + sum);
    }
}

Explanation:

  • stream(): Converts the list to a stream.
  • filter: Filters only even numbers.
  • mapToInt: Maps each number to an int.
  • sum(): Sums all the filtered numbers.

7. Custom Exception

This program demonstrates how to create and throw a custom exception.

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            checkValue(10);
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void checkValue(int value) throws CustomException {
        if (value < 20) {
            throw new CustomException("Value is less than 20!");
        }
    }
}

Explanation:

  • CustomException extends Exception: Creates a custom exception class.
  • throw new CustomException: Throws the custom exception.

These programs demonstrate advanced Java concepts such as multithreading, file handling, design patterns, JDBC, Streams API, and custom exceptions. Let me know if you'd like more examples! 😊

Prakash Bojja

I have a personality with all the positives, which makes me a dynamic personality with charm. I am a software professional with capabilities far beyond those of anyone who claims to be excellent.

Post a Comment

Previous Post Next Post

Contact Form