Java Programming Examples and Code Snippets

1. Prime Number via Command-Line Argument

This program checks if a number provided via command-line arguments is a prime number.

class PrimeCheck {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        boolean isPrime = true;
        if (n <= 1) isPrime = false;
        for (int i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime)
            System.out.println(n + " is Prime");
        else
            System.out.println(n + " is Not Prime");
    }
}

2. Count Vowels and Consonants

This snippet uses the Scanner class to count vowels and consonants in a user-provided string.

import java.util.Scanner;

class VowelConsonantCount {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine().toLowerCase();
        int vowels = 0, consonants = 0;
        for (char ch : s.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                if ("aeiou".indexOf(ch) != -1)
                    vowels++;
                else
                    consonants++;
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
    }
}

3. Demonstrate join() and sleep() Methods

Learn how to manage thread execution using join() and sleep().

class MyThread extends Thread {
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + " : " + i);
                Thread.sleep(500);
            }
        } catch (Exception e) {}
    }
}

class ThreadJoinDemo {
    public static void main(String[] args) throws Exception {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.setName("Thread-1");
        t2.setName("Thread-2");
        t1.start();
        t1.join();
        t2.start();
    }
}

4. Linear Search Implementation

A simple implementation of the Linear Search algorithm to find an element in an array.

import java.util.Scanner;

class LinearSearch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = {10, 20, 30, 40, 50};
        System.out.print("Enter element to search: ");
        int key = sc.nextInt();
        int pos = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                pos = i;
                break;
            }
        }
        if (pos != -1)
            System.out.println("Element found at index " + pos);
        else
            System.out.println("Element not found");
    }
}

5. Reverse String Without Built-in Methods

Manually reverse a string using a for loop and character concatenation.

import java.util.Scanner;

class ReverseStringNoBuiltin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter string: ");
        String s = sc.nextLine();
        String rev = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            rev += s.charAt(i);
        }
        System.out.println("Reversed String: " + rev);
    }
}

6. GUI Login Form Using Swing

Create a basic graphical user interface (GUI) login form with JFrame and GridLayout.

import javax.swing.*;
import java.awt.*;

class LoginForm {
    public static void main(String[] args) {
        JFrame f = new JFrame("Login Form");
        f.setSize(300, 200);
        f.setLayout(new GridLayout(3, 2));
        JLabel l1 = new JLabel("Username:");
        JLabel l2 = new JLabel("Password:");
        JTextField t1 = new JTextField();
        JPasswordField t2 = new JPasswordField();
        JButton b = new JButton("Login");
        f.add(l1); f.add(t1);
        f.add(l2); f.add(t2);
        f.add(new JLabel());
        f.add(b);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

7. Factorial via Command-Line Argument

Calculate the factorial of a number passed as a command-line argument.

class FactorialCmd {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int fact = 1;
        for (int i = 1; i <= n; i++)
            fact *= i;
        System.out.println("Factorial: " + fact);
    }
}

8. Rectangle Class with Parameterized Constructor

Demonstrates object-oriented programming using a parameterized constructor to calculate area.

class Rectangle {
    int length, width;
    Rectangle(int l, int w) {
        length = l;
        width = w;
    }
    int area() {
        return length * width;
    }
}

class RectangleTest {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(10, 5);
        System.out.println("Area = " + r.area());
    }
}

9. Multithreading: Odd and Even Numbers

Using two separate threads to print odd and even numbers concurrently.

class OddThread extends Thread {
    public void run() {
        for (int i = 1; i <= 10; i += 2) {
            System.out.println("Odd Thread: " + i);
        }
    }
}

class EvenThread extends Thread {
    public void run() {
        for (int i = 2; i <= 10; i += 2) {
            System.out.println("Even Thread: " + i);
        }
    }
}

class OddEvenDemo {
    public static void main(String[] args) {
        OddThread o = new OddThread();
        EvenThread e = new EvenThread();
        o.start();
        e.start();
    }
}