Java Programming Examples: Strings, Recursion, File I/O, and More

1. String Concatenation

String str1 = “Hello”;
String str2 = “world”;
// Using the + operator
String concatenatedString = str1 + “, ” + str2;
// Using the concat() method
String concatenatedString2 = str1.concat(“, “).concat(str2);
System.out.println(concatenatedString);
System.out.println(concatenatedString2);

2. Recursion Examples

public class RecursionExamples {
    // Factorial using recursion
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * factorial(n – 1);
        }
    }
    // Fibonacci using tail recursion
    public static int fibonacci(int n, int a, int b) {
        if (n == 0) {
            return a;
        } else if (n == 1) {
            return b;
        } else {
            return fibonacci(n – 1, b, a + b);
        }
    }
    // Palindrome check using recursion
    public static boolean isPalindrome(String str) {
        if (str.length()
            return true;
        } else {
            char first = str.charAt(0);
            char last = str.charAt(str.length() – 1);
            if (first == last) {
                return isPalindrome(str.substring(1, str.length() – 1));
            } else {
                return false;
            }
        }
    }
    public static void main(String[] args) {
        // Testing factorial
        int factResult = factorial(5);
        System.out.println(“Factorial of 5: ” + factResult);
        // Testing fibonacci
        int fibResult = fibonacci(6, 0, 1);
        System.out.println(“Fibonacci of 6: ” + fibResult);
        // Testing palindrome
        String palindromeStr = “madam”;
        boolean isPalindromeResult = isPalindrome(palindromeStr);
        System.out.println(“Is ‘” + palindromeStr + “‘ a palindrome? ” + isPalindromeResult);
    }
}

3. File Read/Write Example

import java.io.*;
public class FileReadWriteExample {
    public static void main(String[] args) {
        // Specify the file path
        String filePath = “example.txt”;
        // Write to a file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(“Hello, world!\n”);
            writer.write(“This is a sample text.”);
        } catch (IOException e) {
            System.err.println(“Error writing to the file: ” + e.getMessage());
        }
        // Read from the file
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            System.out.println(“Contents of the file:”);
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println(“Error reading from the file: ” + e.getMessage());
        }
    }
}

4. Inner Classes Example

public class InnerClassesExample {
    private int outerVariable = 10;
    private static int staticOuterVariable = 20;
    // Local inner class
    public void localInnerClassExample() {
        class LocalInner {
            void display() {
                System.out.println(“Local Inner Class: ” + outerVariable);
            }
        }
        LocalInner localInner = new LocalInner();
        localInner.display();
    }
    // Anonymous inner class
    public void anonymousInnerClassExample() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(“Anonymous Inner Class: ” + staticOuterVariable);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
    // Static inner class
    static class StaticInner {
        void display() {
            System.out.println(“Static Inner Class: ” + staticOuterVariable);
        }
    }
    public static void main(String[] args) {
        InnerClassesExample outer = new InnerClassesExample();
        // Accessing local inner class
        outer.localInnerClassExample();
        // Accessing anonymous inner class
        outer.anonymousInnerClassExample();
        // Accessing static inner class
        StaticInner staticInner = new StaticInner();
        staticInner.display();
    }
}

5. Exception Handling Example

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            int result = divide(10, 0);
            System.out.println(“Result: ” + result); // This line won’t execute if an exception occurs
        } catch (ArithmeticException e) {
            // Handling the ArithmeticException
            System.err.println(“Cannot divide by zero: ” + e.getMessage());
        } finally {
            // This block is always executed, regardless of whether an exception occurs or not
            System.out.println(“Finally block executed”);
        }
        // Code continues execution after exception handling
        System.out.println(“Program continues after exception handling”);
    }
    public static int divide(int dividend, int divisor) {
        // Method that may throw an exception
        return dividend / divisor;
    }
}

6. Socket Read/Write Example

import java.io.*;
import java.net.*;
public class SocketReadWriteExample {
    public static void main(String[] args) {
        final String serverAddress = “localhost”; // Change this to your server address
        final int port = 8080; // Change this to your server’s port
        try {
            // Create a socket to establish a connection to the server
            Socket socket = new Socket(serverAddress, port);
            // Get the output stream of the socket
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter out = new PrintWriter(outputStream, true);
            // Write data to the server
            out.println(“Hello, server!”);
            // Get the input stream of the socket
            InputStream inputStream = socket.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            // Read data from the server
            String response = in.readLine();
            System.out.println(“Server response: ” + response);
            // Close the streams and socket
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            System.err.println(“Error: ” + e.getMessage());
        }
    }
}

7. Multithreading Example

public class MultiThreadExample {
    public static void main(String[] args) {
        // Create two instances of the Runnable objects
        MyRunnable myRunnable1 = new MyRunnable(“Thread 1”);
        MyRunnable myRunnable2 = new MyRunnable(“Thread 2”);
        // Create two threads and pass the Runnable objects to them
        Thread thread1 = new Thread(myRunnable1);
        Thread thread2 = new Thread(myRunnable2);
        // Start the threads
        thread1.start();
        thread2.start();
    }
}
// Implement the Runnable interface
class MyRunnable implements Runnable {
    private String name;
    // Constructor to initialize the thread name
    public MyRunnable(String name) {
        this.name = name;
    }
    // Override the run() method
    @Override
    public void run() {
        for (int i = 0; i
            System.out.println(name + “: ” + i);
            try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                System.err.println(“Thread interrupted: ” + e.getMessage());
            }
        }
    }
}