Top 100 JAVA Programs for Interview with Answer

 

 

100 JAVA  Programs for Interview with Answer :

  1. Hello World

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

  1. Print numbers from 1 to N

public class PrintNumbers {

    public static void main(String[] args) {

        int N = 10;

        for (int i = 1; i <= N; i++) {

            System.out.println(i);

        }

    }

}

  1. Calculate the sum of N natural numbers

public class SumOfNaturalNumbers {

    public static void main(String[] args) {

        int N = 10;

        int sum = 0;

        for (int i = 1; i <= N; i++) {

            sum += i;

        }

        System.out.println("Sum: " + sum);

    }

}

  1. Factorial of a number

public class Factorial {

    public static void main(String[] args) {

        int num = 5;

        int factorial = 1;

        for (int i = 1; i <= num; i++) {

            factorial *= i;

        }

        System.out.println("Factorial: " + factorial);

    }

}

  1. Fibonacci series

public class Fibonacci {

    public static void main(String[] args) {

        int N = 10;

        int first = 0, second = 1;

        System.out.print(first + " " + second);

        for (int i = 2; i < N; i++) {

            int next = first + second;

            System.out.print(" " + next);

            first = second;

            second = next;

        }

    }

}

  1. Prime number checker

public class PrimeChecker {

    public static void main(String[] args) {

        int num = 17;

        boolean isPrime = true;

        for (int i = 2; i <= Math.sqrt(num); i++) {

            if (num % i == 0) {

                isPrime = false;

                break;

            }

        }

        System.out.println(num + " is prime: " + isPrime);

    }

}

  1. Palindrome checker

public class PalindromeChecker {

    public static void main(String[] args) {

        String str = "radar";

        boolean isPalindrome = true;

        int left = 0, right = str.length() - 1;

        while (left < right) {

            if (str.charAt(left) != str.charAt(right)) {

                isPalindrome = false;

                break;

            }

            left++;

            right--;

        }

        System.out.println(str + " is palindrome: " + isPalindrome);

    }

}

  1. Reverse a string

public class ReverseString {

    public static void main(String[] args) {

        String str = "hello";

        StringBuilder reversed = new StringBuilder(str).reverse();

        System.out.println("Reversed: " + reversed);

    }

}

  1. Check for Armstrong number

public class ArmstrongNumber {

    public static void main(String[] args) {

        int num = 153;

        int originalNum = num;

        int sum = 0;

        int digits = (int) Math.log10(num) + 1;

        while (num > 0) {

            int digit = num % 10;

            sum += Math.pow(digit, digits);

            num /= 10;

        }

        boolean isArmstrong = sum == originalNum;

        System.out.println(originalNum + " is Armstrong: " + isArmstrong);

    }

}

  1. Swap two numbers

public class SwapNumbers {

    public static void main(String[] args) {

        int a = 5, b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        int temp = a;

        a = b;

        b = temp;

        System.out.println("After swap: a = " + a + ", b = " + b);

    }

}

  1. Find the largest element in an array

public class LargestElementInArray {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int largest = arr[0];

        for (int i = 1; i < arr.length; i++) {

            if (arr[i] > largest) {

                largest = arr[i];

            }

        }

        System.out.println("Largest element: " + largest);

    }

}

  1. Calculate the average of elements in an array

public class AverageOfArray {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int sum = 0;

        for (int num : arr) {

            sum += num;

        }

        double average = (double) sum / arr.length;

        System.out.println("Average: " + average);

    }

}

  1. Reverse an array

public class ReverseArray {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int left = 0, right = arr.length - 1;

        while (left < right) {

            int temp = arr[left];

            arr[left] = arr[right];

            arr[right] = temp;

            left++;

            right--;

        }

        System.out.print("Reversed array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

}

  1. Find the second largest element

public class SecondLargestElement {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int firstLargest = Integer.MIN_VALUE;

        int secondLargest = Integer.MIN_VALUE;

        for (int num : arr) {

            if (num > firstLargest) {

                secondLargest = firstLargest;

                firstLargest = num;

            } else if (num > secondLargest && num < firstLargest) {

                secondLargest = num;

            }

        }

        System.out.println("Second largest element: " + secondLargest);

    }

}

  1. Merge two arrays

public class MergeArrays {

    public static void main(String[] args) {

        int[] arr1 = { 1, 2, 3 };

        int[] arr2 = { 4, 5, 6 };

        int[] merged = new int[arr1.length + arr2.length];

        int index = 0;

        for (int num : arr1) {

            merged[index] = num;

            index++;

        }

        for (int num : arr2) {

            merged[index] = num;

            index++;

      

 

 }

        System.out.print("Merged array: ");

        for (int num : merged) {

            System.out.print(num + " ");

        }

    }

}

  1. Count occurrences of an element

public class CountOccurrences {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 2, 3, 2, 4, 5 };

        int target = 2;

        int count = 0;

        for (int num : arr) {

            if (num == target) {

                count++;

            }

        }

        System.out.println("Occurrences of " + target + ": " + count);

    }

}

  1. Remove duplicates from an array

public class RemoveDuplicates {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 2, 3, 4, 4, 5 };

        int[] unique = new int[arr.length];

        int index = 0;

        for (int num : arr) {

            boolean isDuplicate = false;

            for (int i = 0; i < index; i++) {

                if (num == unique[i]) {

                    isDuplicate = true;

                    break;

                }

            }

            if (!isDuplicate) {

                unique[index] = num;

                index++;

            }

        }

        System.out.print("Array with duplicates removed: ");

        for (int i = 0; i < index; i++) {

            System.out.print(unique[i] + " ");

        }

    }

}

  1. Check if an array is sorted

public class ArraySortedCheck {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 4, 4, 5 };

        boolean isSorted = true;

        for (int i = 1; i < arr.length; i++) {

            if (arr[i] < arr[i - 1]) {

                isSorted = false;

                break;

            }

        }

        System.out.println("Array is sorted: " + isSorted);

    }

}

  1. Find the intersection of two arrays

public class ArrayIntersection {

    public static void main(String[] args) {

        int[] arr1 = { 1, 2, 2, 3, 4, 5 };

        int[] arr2 = { 2, 2, 4, 5, 6 };

        Set<Integer> set = new HashSet<>();

        for (int num : arr1) {

            set.add(num);

        }

        List<Integer> intersection = new ArrayList<>();

        for (int num : arr2) {

            if (set.contains(num)) {

                intersection.add(num);

                set.remove(num);

            }

        }

        System.out.print("Intersection: ");

        for (int num : intersection) {

            System.out.print(num + " ");

        }

    }

}

  1. Rotate an array

public class RotateArray {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 3, 4, 5 };

        int rotateBy = 2;

        int n = arr.length;

        rotateBy %= n; // Handle cases where rotateBy is greater than n

        int[] rotated = new int[n];

        for (int i = 0; i < n; i++) {

            rotated[(i + rotateBy) % n] = arr[i];

        }

        System.out.print("Rotated array: ");

        for (int num : rotated) {

            System.out.print(num + " ");

        }

    }

}

  1. Count characters, words, and sentences in a string

public class StringStatistics {

    public static void main(String[] args) {

        String text = "Hello, this is a sample sentence. It contains multiple words.";

        int charCount = 0;

        int wordCount = 0;

        int sentenceCount = 0;

        for (char c : text.toCharArray()) {

            if (Character.isLetter(c)) {

                charCount++;

            }

            if (c == ' ' || c == '.' || c == '?' || c == '!') {

                if (charCount > 0) {

                    wordCount++;

                }

                if (c == '.' || c == '?' || c == '!') {

                    sentenceCount++;

                }

                charCount = 0;

            }

        }

        System.out.println("Character count: " + charCount);

        System.out.println("Word count: " + wordCount);

        System.out.println("Sentence count: " + sentenceCount);

    }

}

  1. Convert uppercase to lowercase and vice versa

public class CaseConversion {

    public static void main(String[] args) {

        String text = "Hello World";

        String uppercase = text.toUpperCase();

        String lowercase = text.toLowerCase();

        System.out.println("Uppercase: " + uppercase);

        System.out.println("Lowercase: " + lowercase);

    }

}

  1. Check if a string is a palindrome

public class StringPalindrome {

    public static void main(String[] args) {

        String str = "radar";

        boolean isPalindrome = true;

        int left = 0, right = str.length() - 1;

        while (left < right) {

            if (str.charAt(left) != str.charAt(right)) {

                isPalindrome = false;

                break;

            }

            left++;

            right--;

        }

        System.out.println(str + " is palindrome: " + isPalindrome);

    }

}

  1. Count occurrences of a substring

public class SubstringOccurrences {

    public static void main(String[] args) {

        String text = "Hello, world! Hello, universe!";

        String substring = "Hello";

        int count = 0;

        int index = text.indexOf(substring);

        while (index != -1) {

            count++;

            index = text.indexOf(substring, index + substring.length());

        }

        System.out.println("Occurrences of \"" + substring + "\": " + count);

    }

}

  1. Replace a substring in a string

public class ReplaceSubstring {

    public static void main(String[] args) {

        String text = "Hello, world! Hello, universe!";

        String oldSubstring = "Hello";

        String newSubstring = "Hi";

        String replaced = text.replace(oldSubstring, newSubstring);

        System.out.println("Replaced: " + replaced);

    }

}

  1. Check if two strings are anagrams

public class AnagramCheck {

    public static void main(String[] args) {

        String str1 = "listen";

        String str2 = "silent";

        boolean isAnagram = true;

        if (str1.length() != str2.length()) {

            isAnagram = false;

        } else {

            int[] charCount = new int[26]; // Assuming input contains only lowercase letters

            for (char c : str1.toCharArray()) {

                charCount[c - 'a']++;

            }

            for (char c : str2.toCharArray()) {

                charCount[c - '

 

a']--;

            }

            for (int count : charCount) {

                if (count != 0) {

                    isAnagram = false;

                    break;

                }

            }

        }

        System.out.println("Anagram: " + isAnagram);

    }

}

  1. Reverse words in a sentence

public class ReverseWordsInSentence {

    public static void main(String[] args) {

        String sentence = "Hello world, how are you?";

        String[] words = sentence.split("\\s+");

        StringBuilder reversedSentence = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--) {

            reversedSentence.append(words[i]).append(" ");

        }

        System.out.println("Reversed sentence: " + reversedSentence.toString().trim());

    }

}

  1. Remove spaces from a string

public class RemoveSpaces {

    public static void main(String[] args) {

        String sentence = "   Hello   world,  how are  you?   ";

        String trimmed = sentence.trim();

        String noSpaces = trimmed.replaceAll("\\s+", " ");

        System.out.println("Without spaces: " + noSpaces);

    }

}

  1. Find the longest common prefix

public class LongestCommonPrefix {

    public static void main(String[] args) {

        String[] strings = { "flower", "flow", "flight" };

        String longestPrefix = strings[0];

        for (int i = 1; i < strings.length; i++) {

            while (!strings[i].startsWith(longestPrefix)) {

                longestPrefix = longestPrefix.substring(0, longestPrefix.length() - 1);

            }

        }

        System.out.println("Longest common prefix: " + longestPrefix);

    }

}

  1. Convert string to integer (and vice versa)

public class StringToIntAndViceVersa {

    public static void main(String[] args) {

        String strNumber = "12345";

        int intNumber = Integer.parseInt(strNumber);

        int incremented = intNumber + 1;

        String strResult = String.valueOf(incremented);

        System.out.println("Incremented as string: " + strResult);

    }

}

  1. Factorial using recursion

public class FactorialRecursion {

    public static void main(String[] args) {

        int num = 5;

        int factorial = calculateFactorial(num);

        System.out.println("Factorial of " + num + ": " + factorial);

    }

 

    private static int calculateFactorial(int n) {

        if (n == 0 || n == 1) {

            return 1;

        }

        return n * calculateFactorial(n - 1);

    }

}

  1. Fibonacci using recursion

public class FibonacciRecursion {

    public static void main(String[] args) {

        int N = 10;

        System.out.print("Fibonacci series: ");

        for (int i = 0; i < N; i++) {

            System.out.print(fibonacci(i) + " ");

        }

    }

 

    private static int fibonacci(int n) {

        if (n <= 1) {

            return n;

        }

        return fibonacci(n - 1) + fibonacci(n - 2);

    }

}

  1. GCD (Greatest Common Divisor) using recursion

public class GCDRecursion {

    public static void main(String[] args) {

        int a = 48, b = 18;

        int gcd = findGCD(a, b);

        System.out.println("GCD of " + a + " and " + b + ": " + gcd);

    }

 

    private static int findGCD(int a, int b) {

        if (b == 0) {

            return a;

        }

        return findGCD(b, a % b);

    }

}

  1. Sum of digits using recursion

public class SumOfDigitsRecursion {

    public static void main(String[] args) {

        int num = 12345;

        int sum = calculateSumOfDigits(num);

        System.out.println("Sum of digits in " + num + ": " + sum);

    }

 

    private static int calculateSumOfDigits(int num) {

        if (num == 0) {

            return 0;

        }

        return num % 10 + calculateSumOfDigits(num / 10);

    }

}

  1. Tower of Hanoi

public class TowerOfHanoi {

    public static void main(String[] args) {

        int numDiscs = 3;

        solveTowerOfHanoi(numDiscs, 'A', 'C', 'B');

    }

 

    private static void solveTowerOfHanoi(int n, char source, char destination, char auxiliary) {

        if (n == 1) {

            System.out.println("Move disc 1 from " + source + " to " + destination);

            return;

        }

        solveTowerOfHanoi(n - 1, source, auxiliary, destination);

        System.out.println("Move disc " + n + " from " + source + " to " + destination);

        solveTowerOfHanoi(n - 1, auxiliary, destination, source);

    }

}

  1. Binary search using recursion

public class BinarySearchRecursion {

    public static void main(String[] args) {

        int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15 };

        int target = 7;

        int index = binarySearch(arr, target, 0, arr.length - 1);

        if (index != -1) {

            System.out.println(target + " found at index " + index);

        } else {

            System.out.println(target + " not found in the array.");

        }

    }

 

    private static int binarySearch(int[] arr, int target, int left, int right) {

        if (left > right) {

            return -1;

        }

        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {

            return mid;

        } else if (arr[mid] < target) {

            return binarySearch(arr, target, mid + 1, right);

        } else {

            return binarySearch(arr, target, left, mid - 1);

        }

    }

}

  1. Calculate power using recursion

public class PowerCalculationRecursion {

    public static void main(String[] args) {

        int base = 2;

        int exponent = 5;

        int result = calculatePower(base, exponent);

        System.out.println(base + " raised to the power " + exponent + ": " + result);

    }

 

    private static int calculatePower(int base, int exponent) {

        if (exponent == 0) {

            return 1;

        }

        return base * calculatePower(base, exponent - 1);

    }

}

  1. Print permutations of a string

public class StringPermutations {

    public static void main(String[] args) {

        String str = "abc";

        generatePer

 

mutations(str, 0, str.length() - 1);

    }

 

    private static void generatePermutations(String str, int left, int right) {

        if (left == right) {

            System.out.println(str);

            return;

        }

        for (int i = left; i <= right; i++) {

            str = swap(str, left, i);

            generatePermutations(str, left + 1, right);

            str = swap(str, left, i);

        }

    }

 

    private static String swap(String str, int i, int j) {

        char[] charArray = str.toCharArray();

        char temp = charArray[i];

        charArray[i] = charArray[j];

        charArray[j] = temp;

        return new String(charArray);

    }

}

  1. Print combinations of a string

public class StringCombinations {

    public static void main(String[] args) {

        String str = "abc";

        int r = 2; // Combination length

        generateCombinations(str, new char[r], 0, 0);

    }

 

    private static void generateCombinations(String str, char[] data, int start, int index) {

        if (index == data.length) {

            System.out.println(new String(data));

            return;

        }

        for (int i = start; i < str.length(); i++) {

            data[index] = str.charAt(i);

            generateCombinations(str, data, i + 1, index + 1);

        }

    }

}

  1. Recursive palindrome check

public class RecursivePalindrome {

    public static void main(String[] args) {

        String str = "radar";

        boolean isPalindrome = checkPalindrome(str, 0, str.length() - 1);

        System.out.println(str + " is palindrome: " + isPalindrome);

    }

 

    private static boolean checkPalindrome(String str, int left, int right) {

        if (left >= right) {

            return true;

        }

        if (str.charAt(left) != str.charAt(right)) {

            return false;

        }

        return checkPalindrome(str, left + 1, right - 1);

    }

}

  1. Bubble Sort

public class BubbleSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        bubbleSort(arr);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void bubbleSort(int[] arr) {

        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {

            for (int j = 0; j < n - i - 1; j++) {

                if (arr[j] > arr[j + 1]) {

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                }

            }

        }

    }

}

  1. Selection Sort

public class SelectionSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        selectionSort(arr);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void selectionSort(int[] arr) {

        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {

            int minIndex = i;

            for (int j = i + 1; j < n; j++) {

                if (arr[j] < arr[minIndex]) {

                    minIndex = j;

                }

            }

            int temp = arr[i];

            arr[i] = arr[minIndex];

            arr[minIndex] = temp;

        }

    }

}

  1. Insertion Sort

public class InsertionSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        insertionSort(arr);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void insertionSort(int[] arr) {

        int n = arr.length;

        for (int i = 1; i < n; i++) {

            int key = arr[i];

            int j = i - 1;

            while (j >= 0 && arr[j] > key) {

                arr[j + 1] = arr[j];

                j--;

            }

            arr[j + 1] = key;

        }

    }

}

  1. Merge Sort

public class MergeSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        mergeSort(arr, 0, arr.length - 1);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void mergeSort(int[] arr, int left, int right) {

        if (left < right) {

            int mid = left + (right - left) / 2;

            mergeSort(arr, left, mid);

            mergeSort(arr, mid + 1, right);

            merge(arr, left, mid, right);

        }

    }

 

    private static void merge(int[] arr, int left, int mid, int right) {

        int n1 = mid - left + 1;

        int n2 = right - mid;

        int[] leftArray = new int[n1];

        int[] rightArray = new int[n2];

        for (int i = 0; i < n1; i++) {

            leftArray[i] = arr[left + i];

        }

        for (int i = 0; i < n2; i++) {

            rightArray[i] = arr[mid + 1 + i];

        }

        int i = 0, j = 0, k = left;

        while (i < n1 && j < n2) {

            if (leftArray[i] <= rightArray[j]) {

                arr[k] = leftArray[i];

                i++;

            } else {

                arr[k] = rightArray[j];

                j++;

            }

            k++;

        }

        while (i < n1) {

            arr[k] = leftArray[i];

            i++;

            k++;

        }

        while (j < n2) {

            arr[k] = rightArray[j];

            j++;

            k++;

        }

    }

}

  1. Quick Sort

public class QuickSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        quickSort(arr, 0, arr.length - 1);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

 

 

        }

    }

 

    private static void quickSort(int[] arr, int low, int high) {

        if (low < high) {

            int pivotIndex = partition(arr, low, high);

            quickSort(arr, low, pivotIndex - 1);

            quickSort(arr, pivotIndex + 1, high);

        }

    }

 

    private static int partition(int[] arr, int low, int high) {

        int pivot = arr[high];

        int i = low - 1;

        for (int j = low; j < high; j++) {

            if (arr[j] < pivot) {

                i++;

                int temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

        int temp = arr[i + 1];

        arr[i + 1] = arr[high];

        arr[high] = temp;

        return i + 1;

    }

}

  1. Binary Search

public class BinarySearch {

    public static void main(String[] args) {

        int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15 };

        int target = 7;

        int index = binarySearch(arr, target);

        if (index != -1) {

            System.out.println(target + " found at index " + index);

        } else {

            System.out.println(target + " not found in the array.");

        }

    }

 

    private static int binarySearch(int[] arr, int target) {

        int left = 0;

        int right = arr.length - 1;

        while (left <= right) {

            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {

                return mid;

            } else if (arr[mid] < target) {

                left = mid + 1;

            } else {

                right = mid - 1;

            }

        }

        return -1;

    }

}

  1. Linear Search

public class LinearSearch {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int target = 8;

        int index = linearSearch(arr, target);

        if (index != -1) {

            System.out.println(target + " found at index " + index);

        } else {

            System.out.println(target + " not found in the array.");

        }

    }

 

    private static int linearSearch(int[] arr, int target) {

        for (int i = 0; i < arr.length; i++) {

            if (arr[i] == target) {

                return i;

            }

        }

        return -1;

    }

}

  1. Find Kth largest/smallest element

import java.util.Arrays;

 

public class KthLargestSmallest {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 8, 10, 1 };

        int k = 3;

        int kthLargest = findKthLargest(arr, k);

        System.out.println("Kth largest element: " + kthLargest);

 

        int kthSmallest = findKthSmallest(arr, k);

        System.out.println("Kth smallest element: " + kthSmallest);

    }

 

    private static int findKthLargest(int[] arr, int k) {

        Arrays.sort(arr);

        return arr[arr.length - k];

    }

 

    private static int findKthSmallest(int[] arr, int k) {

        Arrays.sort(arr);

        return arr[k - 1];

    }

}

  1. Counting Sort

public class CountingSort {

    public static void main(String[] args) {

        int[] arr = { 4, 2, 2, 8, 3, 3, 1 };

        countingSort(arr);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void countingSort(int[] arr) {

        int max = Arrays.stream(arr).max().getAsInt();

        int min = Arrays.stream(arr).min().getAsInt();

        int range = max - min + 1;

        int[] count = new int[range];

        int[] output = new int[arr.length];

 

        for (int num : arr) {

            count[num - min]++;

        }

 

        for (int i = 1; i < range; i++) {

            count[i] += count[i - 1];

        }

 

        for (int i = arr.length - 1; i >= 0; i--) {

            output[count[arr[i] - min] - 1] = arr[i];

            count[arr[i] - min]--;

        }

 

        for (int i = 0; i < arr.length; i++) {

            arr[i] = output[i];

        }

    }

}

  1. Radix Sort

public class RadixSort {

    public static void main(String[] args) {

        int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 };

        radixSort(arr);

        System.out.print("Sorted array: ");

        for (int num : arr) {

            System.out.print(num + " ");

        }

    }

 

    private static void radixSort(int[] arr) {

        int max = Arrays.stream(arr).max().getAsInt();

        for (int exp = 1; max / exp > 0; exp *= 10) {

            countSort(arr, exp);

        }

    }

 

    private static void countSort(int[] arr, int exp) {

        int n = arr.length;

        int[] output = new int[n];

        int[] count = new int[10];

 

        for (int i = 0; i < n; i++) {

            count[(arr[i] / exp) % 10]++;

        }

 

        for (int i = 1; i < 10; i++) {

            count[i] += count[i - 1];

        }

 

        for (int i = n - 1; i >= 0

 

; i--) {

            output[count[(arr[i] / exp) % 10] - 1] = arr[i];

            count[(arr[i] / exp) % 10]--;

        }

 

        for (int i = 0; i < n; i++) {

            arr[i] = output[i];

        }

    }

}

  1. Implement a Stack

import java.util.EmptyStackException;

 

class Stack {

    private int[] data;

    private int top;

    private int capacity;

 

    public Stack(int capacity) {

        this.capacity = capacity;

        this.data = new int[capacity];

        this.top = -1;

    }

 

    public boolean isEmpty() {

        return top == -1;

    }

 

    public boolean isFull() {

        return top == capacity - 1;

    }

 

    public void push(int value) {

        if (isFull()) {

            throw new StackOverflowError("Stack is full");

        }

        data[++top] = value;

    }

 

    public int pop() {

        if (isEmpty()) {

            throw new EmptyStackException();

        }

        return data[top--];

    }

 

    public int peek() {

        if (isEmpty()) {

            throw new EmptyStackException();

        }

        return data[top];

    }

}

 

public class StackImplementation {

    public static void main(String[] args) {

        Stack stack = new Stack(5);

        stack.push(1);

        stack.push(2);

        stack.push(3);

 

        System.out.println("Peek: " + stack.peek());

        System.out.println("Pop: " + stack.pop());

        System.out.println("Peek: " + stack.peek());

    }

}

  1. Implement a Queue

import java.util.LinkedList;

import java.util.Queue;

 

public class QueueImplementation {

    public static void main(String[] args) {

        Queue<Integer> queue = new LinkedList<>();

        queue.offer(1);

        queue.offer(2);

        queue.offer(3);

 

        System.out.println("Peek: " + queue.peek());

        System.out.println("Poll: " + queue.poll());

        System.out.println("Peek: " + queue.peek());

    }

}

  1. Implement a Linked List

class ListNode {

    int val;

    ListNode next;

 

    ListNode(int val) {

        this.val = val;

    }

}

 

class LinkedList {

    ListNode head;

 

    void insert(int val) {

        ListNode newNode = new ListNode(val);

        newNode.next = head;

        head = newNode;

    }

 

    void display() {

        ListNode current = head;

        while (current != null) {

            System.out.print(current.val + " -> ");

            current = current.next;

        }

        System.out.println("null");

    }

}

 

public class LinkedListImplementation {

    public static void main(String[] args) {

        LinkedList list = new LinkedList();

        list.insert(3);

        list.insert(2);

        list.insert(1);

 

        list.display();

    }

}

  1. Implement a Binary Search Tree

class TreeNode {

    int val;

    TreeNode left;

    TreeNode right;

 

    TreeNode(int val) {

        this.val = val;

    }

}

 

class BinarySearchTree {

    TreeNode root;

 

    void insert(int val) {

        root = insertRec(root, val);

    }

 

    TreeNode insertRec(TreeNode root, int val) {

        if (root == null) {

            root = new TreeNode(val);

            return root;

        }

        if (val < root.val) {

            root.left = insertRec(root.left, val);

        } else if (val > root.val) {

            root.right = insertRec(root.right, val);

        }

        return root;

    }

 

    void inorderTraversal(TreeNode root) {

        if (root != null) {

            inorderTraversal(root.left);

            System.out.print(root.val + " ");

            inorderTraversal(root.right);

        }

    }

}

 

public class BinarySearchTreeImplementation {

    public static void main(String[] args) {

        BinarySearchTree tree = new BinarySearchTree();

        tree.insert(50);

        tree.insert(30);

        tree.insert(20);

        tree.insert(40);

        tree.insert(70);

        tree.insert(60);

        tree.insert(80);

 

        tree.inorderTraversal(tree.root);

    }

}

  1. Implement a Hash Map

import java.util.ArrayList;

import java.util.List;

 

class KeyValue {

    int key;

    int value;

 

    KeyValue(int key, int value) {

        this.key = key;

        this.value = value;

    }

}

 

class HashMap {

    private List<KeyValue>[] map;

    private int capacity;

 

    public HashMap(int capacity) {

        this.capacity = capacity;

        this.map = new ArrayList[capacity];

    }

 

    private int hash(int key) {

        return key % capacity;

    }

 

    public void put(int key, int value) {

        int hash = hash(key);

        if (map[hash] == null) {

            map[hash] = new ArrayList<>();

        }

        for (KeyValue entry : map[hash]) {

            if (entry.key == key) {

                entry.value = value;

                return;

            }

        }

        map[hash].add(new KeyValue(key, value));

    }

 

    public int get(int key) {

        int hash = hash(key);

        if (map[hash] != null) {

            for (KeyValue entry : map[hash]) {

                if (entry.key == key) {

                    return entry.value;

                }

            }

        }

        return -1;

    }

 

    public void remove(int key) {

        int hash = hash(key);

        if (map[hash] != null) {

            for (KeyValue entry : map[hash]) {

                if (entry.key == key) {

                    map[hash].remove(entry);

                    return;

                }

            }

        }

    }

}

 

public class HashMapImplementation {

    public static void main(String[] args) {

        HashMap map = new HashMap(10);

        map.put(1, 10);

        map.put(2, 20);

        map.put(11, 110);

        map.put(21, 210);

 

        System.out.println("Value at key 1: " + map.get(1));

        System.out.println("Value at key 11: " + map.get(11));

        System.out.println("Value at key 3: " + map.get(3));

 

        map.remove(2);

        System.out.println("Value at key 2 (after removal): " + map.get(2));

    }

}

  1. Implement a Graph

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

class Graph {

    private Map<Integer, List<Integer>> adjacencyList;

 

    public Graph() {

        this.adjacencyList = new HashMap<>();

    }

 

    public void addVertex(int vertex) {

        adjacencyList.put(vertex, new ArrayList<>());

    }

 

    public void addEdge(int source, int destination) {

        adjacencyList.get(source).add(destination);

        adjacencyList.get(destination).add(source); // For undirected graph

    }

 

    public List<Integer> getNeighbors(int vertex) {

        return adjacencyList.get(vertex);

    }

}

 

public class GraphImplementation {

    public static void main(String[] args) {

        Graph graph = new Graph();

        graph.add

 

Vertex(0);

        graph.addVertex(1);

        graph.addVertex(2);

        graph.addVertex(3);

 

        graph.addEdge(0, 1);

        graph.addEdge(0, 2);

        graph.addEdge(1, 2);

        graph.addEdge(2, 3);

 

        List<Integer> neighbors = graph.getNeighbors(0);

        System.out.println("Neighbors of vertex 0: " + neighbors);

    }

}

  1. Implement a Priority Queue (Heap)

import java.util.PriorityQueue;

 

public class PriorityQueueImplementation {

    public static void main(String[] args) {

        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

        minHeap.offer(5);

        minHeap.offer(2);

        minHeap.offer(8);

        minHeap.offer(1);

 

        System.out.println("Min element: " + minHeap.peek());

        System.out.println("Poll: " + minHeap.poll());

        System.out.println("Min element after poll: " + minHeap.peek());

    }

}

  1. Implement a Trie

class TrieNode {

    TrieNode[] children;

    boolean isEndOfWord;

 

    TrieNode() {

        this.children = new TrieNode[26];

        this.isEndOfWord = false;

    }

}

 

class Trie {

    private TrieNode root;

 

    Trie() {

        this.root = new TrieNode();

    }

 

    void insert(String word) {

        TrieNode node = root;

        for (char c : word.toCharArray()) {

            int index = c - 'a';

            if (node.children[index] == null) {

                node.children[index] = new TrieNode();

            }

            node = node.children[index];

        }

        node.isEndOfWord = true;

    }

 

    boolean search(String word) {

        TrieNode node = root;

        for (char c : word.toCharArray()) {

            int index = c - 'a';

            if (node.children[index] == null) {

                return false;

            }

            node = node.children[index];

        }

        return node.isEndOfWord;

    }

 

    boolean startsWith(String prefix) {

        TrieNode node = root;

        for (char c : prefix.toCharArray()) {

            int index = c - 'a';

            if (node.children[index] == null) {

                return false;

            }

            node = node.children[index];

        }

        return true;

    }

}

 

public class TrieImplementation {

    public static void main(String[] args) {

        Trie trie = new Trie();

        trie.insert("apple");

        System.out.println("Search for 'apple': " + trie.search("apple")); // Output: true

        System.out.println("Search for 'app': " + trie.search("app")); // Output: false

        System.out.println("Starts with 'app': " + trie.startsWith("app")); // Output: true

        trie.insert("app");

        System.out.println("Search for 'app': " + trie.search("app")); // Output: true

    }

}

  1. Implement a Red-Black Tree

enum Color {

    RED,

    BLACK

}

 

class RBTreeNode {

    int val;

    RBTreeNode parent;

    RBTreeNode left;

    RBTreeNode right;

    Color color;

 

    RBTreeNode(int val) {

        this.val = val;

        this.color = Color.RED;

    }

}

 

class RedBlackTree {

    private RBTreeNode root;

    private RBTreeNode nil; // Sentinel node

 

    public RedBlackTree() {

        nil = new RBTreeNode(-1);

        nil.color = Color.BLACK;

        root = nil;

    }

 

    // Insertion, deletion, and balancing operations here...

}

 

public class RedBlackTreeImplementation {

    public static void main(String[] args) {

        RedBlackTree tree = new RedBlackTree();

        // Perform insertion, deletion, or other operations on the Red-Black Tree

    }

}

  1. Implement an AVL Tree

class AVLTreeNode {

    int val;

    int height;

    AVLTreeNode left;

    AVLTreeNode right;

 

    AVLTreeNode(int val) {

        this.val = val;

        this.height = 1;

    }

}

 

class AVLTree {

    private AVLTreeNode root;

 

    // Insertion, deletion, and balancing operations here...

}

 

public class AVLTreeImplementation {

    public static void main(String[] args) {

        AVLTree tree = new AVLTree();

        // Perform insertion, deletion, or other operations on the AVL Tree

    }

}

  1. Create a class and object

class Person {

    String name;

    int age;

 

    Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    void display() {

        System.out.println("Name: " + name + ", Age: " + age);

    }

}

 

public class ClassAndObject {

    public static void main(String[] args) {

        Person person1 = new Person("Alice", 25);

        person1.display();

 

        Person person2 = new Person("Bob", 30);

        person2.display();

    }

}

  1. Inheritance

class Vehicle {

    void display() {

        System.out.println("This is a vehicle.");

    }

}

 

class Car extends Vehicle {

    void displayCar() {

        System.out.println("This is a car.");

    }

}

 

public class InheritanceExample {

    public static void main(String[] args) {

        Car car = new Car();

        car.display(); // Accessing inherited method

        car.displayCar(); // Accessing subclass method

    }

}

  1. Polymorphism

class Shape {

    void draw() {

        System.out.println("Drawing a shape.");

    }

}

 

class Circle extends Shape {

    @Override

    void draw() {

        System.out.println("Drawing a circle.");

    }

}

 

class Rectangle extends Shape {

    @Override

    void draw() {

        System.out.println("Drawing a rectangle.");

    }

}

 

public class PolymorphismExample {

    public static void main(String[] args) {

        Shape shape1 = new Circle();

        shape1.draw();

 

        Shape shape2 = new Rectangle();

        shape2.draw();

    }

}

  1. Encapsulation

class Student {

    private String name;

    private int age;

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        if (age >= 0) {

            this.age = age;

        }

    }

}

 

public class EncapsulationExample {

    public static void main(String[] args) {

        Student student = new Student();

        student.setName("Alice");

        student.setAge(20);

        System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());

    }

}

  1. Abstraction

abstract class Shape {

    abstract void draw();

}

 

class

 

 Circle extends Shape {

    @Override

    void draw() {

        System.out.println("Drawing a circle.");

    }

}

 

class Rectangle extends Shape {

    @Override

    void draw() {

        System.out.println("Drawing a rectangle.");

    }

}

 

public class AbstractionExample {

    public static void main(String[] args) {

        Shape circle = new Circle();

        circle.draw();

 

        Shape rectangle = new Rectangle();

        rectangle.draw();

    }

}

  1. Interface and Abstract class

interface Printable {

    void print();

}

 

abstract class Document {

    abstract void open();

}

 

class PDFDocument extends Document implements Printable {

    @Override

    void open() {

        System.out.println("Opening PDF document.");

    }

 

    @Override

    public void print() {

        System.out.println("Printing PDF document.");

    }

}

 

public class InterfaceAbstractExample {

    public static void main(String[] args) {

        PDFDocument pdfDocument = new PDFDocument();

        pdfDocument.open();

        pdfDocument.print();

    }

}

  1. Method Overriding

class Animal {

    void sound() {

        System.out.println("Animal makes a sound.");

    }

}

 

class Cat extends Animal {

    @Override

    void sound() {

        System.out.println("Cat meows.");

    }

}

 

public class MethodOverridingExample {

    public static void main(String[] args) {

        Animal animal = new Cat();

        animal.sound(); // Calls overridden method in Cat class

    }

}

  1. Method Overloading

class Calculator {

    int add(int a, int b) {

        return a + b;

    }

 

    double add(double a, double b) {

        return a + b;

    }

}

 

public class MethodOverloadingExample {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        System.out.println("Sum of integers: " + calculator.add(5, 3));

        System.out.println("Sum of doubles: " + calculator.add(5.5, 3.2));

    }

}

  1. Constructors

class Person {

    String name;

    int age;

 

    Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    void display() {

        System.out.println("Name: " + name + ", Age: " + age);

    }

}

 

public class ConstructorsExample {

    public static void main(String[] args) {

        Person person1 = new Person("Alice", 25);

        person1.display();

 

        Person person2 = new Person("Bob", 30);

        person2.display();

    }

}

  1. Static and Instance variables/methods

class MathUtils {

    static int multiply(int a, int b) {

        return a * b;

    }

 

    int add(int a, int b) {

        return a + b;

    }

}

 

public class StaticInstanceExample {

    public static void main(String[] args) {

        int result1 = MathUtils.multiply(5, 3); // Call static method

        System.out.println("Multiplication result: " + result1);

 

        MathUtils math = new MathUtils();

        int result2 = math.add(5, 3); // Call instance method

        System.out.println("Addition result: " + result2);

    }

}

  1. Read from a text file

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class ReadFileExample {

    public static void main(String[] args) {

        String filePath = "sample.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

  1. Write to a text file

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

 

public class WriteFileExample {

    public static void main(String[] args) {

        String filePath = "output.txt";

        String content = "Hello, this is a sample text.";

 

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {

            writer.write(content);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

  1. Copy contents from one file to another

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

 

public class FileCopyExample {

    public static void main(String[] args) {

        String sourcePath = "source.txt";

        String destinationPath = "destination.txt";

 

        try (BufferedReader reader = new BufferedReader(new FileReader(sourcePath));

             BufferedWriter writer = new BufferedWriter(new FileWriter(destinationPath))) {

 

            String line;

            while ((line = reader.readLine()) != null) {

                writer.write(line);

                writer.newLine();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

  1. Count characters/words/lines in a file

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class FileStatisticsExample {

    public static void main(String[] args) {

        String filePath = "sample.txt";

        int charCount = 0;

        int wordCount = 0;

        int lineCount = 0;

 

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            String line;

            while ((line = reader.readLine()) != null) {

                charCount += line.length();

                wordCount += line.split("\\s+").length;

                lineCount++;

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        System.out.println("Character count: " + charCount);

        System.out.println("Word count: " + wordCount);

        System.out.println("Line count: " + lineCount);

    }

}

  1. Serialize and Deserialize objects

import java.io.*;

 

class Student implements Serializable {

    String name;

    int age;

 

    Student(String name, int age) {

        this.name = name;

        this.age = age;

    }

}

 

public class SerializationExample {

    public static void main(String[] args) {

        Student student = new Student("Alice", 25);

 

        // Serialize object to a file

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {

            oos.writeObject(student);

            System.out.println("Object serialized.");

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        // Deserialize object from a file

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {

            Student deserializedStudent = (Student) ois.readObject();

            System.out.println("Deserialized Object:");

            System.out.println("Name: " + deserializedStudent.name);

            System.out.println("Age: " + deserializedStudent.age);

        } catch (IOException | ClassNotFoundException e) {

            e.printStackTrace();

        }

    }

}

  1. Try-catch blocks

public class ExceptionHandlingExample {

    public static void main(String[] args) {

        try {

            int result = divide(10, 0);

            System.out.println("Result:

 

 " + result);

        } catch (ArithmeticException e) {

            System.out.println("Error: Division by zero");

        }

    }

 

    private static int divide(int a, int b) {

        return a / b;

    }

}

  1. Multiple catch blocks

public class MultipleCatchExample {

    public static void main(String[] args) {

        try {

            int[] arr = { 1, 2, 3 };

            System.out.println(arr[4]);

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array index out of bounds");

        } catch (Exception e) {

            System.out.println("An error occurred");

        }

    }

}

  1. Custom exceptions

class AgeException extends Exception {

    AgeException(String message) {

        super(message);

    }

}

 

public class CustomExceptionExample {

    public static void main(String[] args) {

        try {

            validateAge(15);

        } catch (AgeException e) {

            System.out.println("Error: " + e.getMessage());

        }

    }

 

    private static void validateAge(int age) throws AgeException {

        if (age < 18) {

            throw new AgeException("Age must be 18 or older.");

        }

    }

}

  1. Nested try-catch blocks

public class NestedExceptionExample {

    public static void main(String[] args) {

        try {

            int[] arr = { 1, 2, 3 };

            System.out.println(arr[4]);

        } catch (ArrayIndexOutOfBoundsException e) {

            try {

                int result = divide(10, 0);

                System.out.println("Result: " + result);

            } catch (ArithmeticException ex) {

                System.out.println("Error: Division by zero");

            }

        }

    }

 

    private static int divide(int a, int b) {

        return a / b;

    }

}

  1. Using “finally” block

public class FinallyBlockExample {

    public static void main(String[] args) {

        try {

            int result = divide(10, 2);

            System.out.println("Result: " + result);

        } catch (ArithmeticException e) {

            System.out.println("Error: Division by zero");

        } finally {

            System.out.println("Finally block executed.");

        }

    }

 

    private static int divide(int a, int b) {

        return a / b;

    }

}

  1. Create a thread using the Thread class

public class ThreadExample {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> {

            for (int i = 0; i < 5; i++) {

                System.out.println("Thread is running: " + i);

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        });

 

        thread.start();

    }

}

  1. Implement Runnable interface

public class RunnableExample {

    public static void main(String[] args) {

        Runnable runnable = () -> {

            for (int i = 0; i < 5; i++) {

                System.out.println("Thread is running: " + i);

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        };

 

        Thread thread = new Thread(runnable);

        thread.start();

    }

}

  1. Synchronize threads

class Counter {

    private int count = 0;

 

    synchronized void increment() {

        count++;

    }

 

    int getCount() {

        return count;

    }

}

 

public class SynchronizationExample {

    public static void main(String[] args) throws InterruptedException {

        Counter counter = new Counter();

 

        Runnable runnable = () -> {

            for (int i = 0; i < 1000; i++) {

                counter.increment();

            }

        };

 

        Thread thread1 = new Thread(runnable);

        Thread thread2 = new Thread(runnable);

 

        thread1.start();

        thread2.start();

 

        thread1.join();

        thread2.join();

 

        System.out.println("Count: " + counter.getCount());

    }

}

  1. Thread communication using wait/notify

class Processor {

    void produce() throws InterruptedException {

        synchronized (this) {

            System.out.println("Producer thread is producing...");

            wait(); // Releases the lock and waits

            System.out.println("Producer thread resumed production.");

        }

    }

 

    void consume() throws InterruptedException {

        Thread.sleep(2000);

        synchronized (this) {

            System.out.println("Consumer thread is consuming...");

            notify(); // Notifies waiting thread to resume

        }

    }

}

 

public class ThreadCommunicationExample {

    public static void main(String[] args) {

        Processor processor = new Processor();

 

        Thread producerThread = new Thread(() -> {

            try {

                processor.produce();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        });

 

        Thread consumerThread = new Thread(() -> {

            try {

                processor.consume();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        });

 

        producerThread.start();

        consumerThread.start();

    }

}

  1. Deadlock prevention

public class DeadlockPreventionExample {

    public static void main(String[] args) {

        final String resource1 = "resource1";

        final String resource2 = "resource2";

 

        Thread thread1 = new Thread(() -> {

            synchronized (resource1) {

                System.out.println("Thread 1: Holding resource 1...");

                try {

                    Thread.sleep(100);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println("Thread 1: Waiting for resource 2...");

                synchronized (resource2) {

                    System.out.println("Thread 1: Holding resources 1 and 2...");

                }

            }

        });

 

        Thread thread2 = new Thread(() -> {

            synchronized (resource2) {

                System.out.println("Thread 2: Holding resource 2...");

                try {

                    Thread.sleep(100);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println("Thread 2: Waiting for resource 1...");

                synchronized (resource1) {

                    System.out.println("Thread 2: Holding resources 2 and 1...");

                }

            }

        });

 

        thread1.start();

        thread2.start();

    }

}

  1. Create a simple client-server application

import java.io.*;

import java.net.*;

 

class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(12345);

        System.out.println("Server is running...");

 

        while (true) {

            Socket clientSocket = serverSocket.accept();

            System.out.println("Client connected: " + clientSocket.getInetAddress());

 

            // Handle client request using clientSocket's InputStream and OutputStream

            // ...

 

            clientSocket.close();

        }

    }

}

 

class Client {

    public static void main(String[] args) throws IOException {

        String serverAddress =

 

 "localhost";

        int serverPort = 12345;

 

        Socket socket = new Socket(serverAddress, serverPort);

        System.out.println("Connected to server: " + socket.getInetAddress());

 

        // Communicate with the server using socket's InputStream and OutputStream

        // ...

 

        socket.close();

    }

}

  1. Implement TCP communication

import java.io.*;

import java.net.*;

 

class TCPServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(12345);

        System.out.println("Server is running...");

 

        while (true) {

            Socket clientSocket = serverSocket.accept();

            System.out.println("Client connected: " + clientSocket.getInetAddress());

 

            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

 

            String message = reader.readLine();

            System.out.println("Received from client: " + message);

 

            writer.println("Server received: " + message);

 

            reader.close();

            writer.close();

            clientSocket.close();

        }

    }

}

 

class TCPClient {

    public static void main(String[] args) throws IOException {

        String serverAddress = "localhost";

        int serverPort = 12345;

 

        Socket socket = new Socket(serverAddress, serverPort);

        System.out.println("Connected to server: " + socket.getInetAddress());

 

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

 

        System.out.print("Enter a message to send to server: ");

        String message = reader.readLine();

 

        writer.println(message);

 

        BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String response = serverReader.readLine();

        System.out.println("Received from server: " + response);

 

        reader.close();

        writer.close();

        serverReader.close();

        socket.close();

    }

}

  1. Implement UDP communication

import java.io.*;

import java.net.*;

 

class UDPServer {

    public static void main(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket(12345);

        System.out.println("Server is running...");

 

        while (true) {

            byte[] receiveData = new byte[1024];

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            socket.receive(receivePacket);

 

            String message = new String(receivePacket.getData(), 0, receivePacket.getLength());

            System.out.println("Received from client: " + message);

 

            InetAddress clientAddress = receivePacket.getAddress();

            int clientPort = receivePacket.getPort();

 

            String response = "Server received: " + message;

            byte[] sendData = response.getBytes();

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);

            socket.send(sendPacket);

        }

    }

}

 

class UDPClient {

    public static void main(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket();

        System.out.println("Client is running...");

 

        InetAddress serverAddress = InetAddress.getByName("localhost");

        int serverPort = 12345;

 

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

 

        System.out.print("Enter a message to send to server: ");

        String message = reader.readLine();

 

        byte[] sendData = message.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);

        socket.send(sendPacket);

 

        byte[] receiveData = new byte[1024];

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        socket.receive(receivePacket);

 

        String response = new String(receivePacket.getData(), 0, receivePacket.getLength());

        System.out.println("Received from server: " + response);

 

        reader.close();

        socket.close();

    }

}

  1. HTTP GET/POST requests

Note: Sending HTTP requests involves using libraries like java.net.HttpURLConnection or third-party libraries like Apache HttpClient or OkHttp. Below is a simplified example using HttpURLConnection.

import java.io.*;

import java.net.*;

 

public class HttpExample {

    public static void main(String[] args) throws IOException {

        // Sending an HTTP GET request

        URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

 

        connection.setRequestMethod("GET");

 

        int responseCode = connection.getResponseCode();

        System.out.println("Response Code: " + responseCode);

 

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;

        StringBuilder response = new StringBuilder();

        while ((line = reader.readLine()) != null) {

            response.append(line);

        }

        reader.close();

 

        System.out.println("Response Content:");

        System.out.println(response.toString());

 

        // Sending an HTTP POST request

        URL postUrl = new URL("https://jsonplaceholder.typicode.com/posts");

        HttpURLConnection postConnection = (HttpURLConnection) postUrl.openConnection();

 

        postConnection.setRequestMethod("POST");

        postConnection.setRequestProperty("Content-Type", "application/json");

        postConnection.setDoOutput(true);

 

        String postData = "{\"title\":\"New Post\",\"body\":\"This is a new post.\",\"userId\":1}";

        OutputStream outputStream = postConnection.getOutputStream();

        outputStream.write(postData.getBytes());

        outputStream.flush();

 

        int postResponseCode = postConnection.getResponseCode();

        System.out.println("POST Response Code: " + postResponseCode);

 

        BufferedReader postReader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));

        StringBuilder postResponse = new StringBuilder();

        while ((line = postReader.readLine()) != null) {

            postResponse.append(line);

        }

        postReader.close();

 

        System.out.println("POST Response Content:");

        System.out.println(postResponse.toString());

    }

}

  1. URL parsing

import java.net.URL;

 

public class URLParsingExample {

    public static void main(String[] args) throws Exception {

        String urlString = "https://www.example.com:8080/path/page.html?query=param#fragment";

 

        URL url = new URL(urlString);

 

        System.out.println("Protocol: " + url.getProtocol());

        System.out.println("Host: " + url.getHost());

        System.out.println("Port: " +

 

 url.getPort());

        System.out.println("Path: " + url.getPath());

        System.out.println("Query: " + url.getQuery());

        System.out.println("Fragment: " + url.getRef());

    }

}

  1. Create a simple GUI window

Note: GUI programming involves using libraries like Swing. Below is a basic example of creating a simple GUI window.

import javax.swing.*;

 

public class SimpleGUIExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Simple GUI Example");

        frame.setSize(400, 300);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true);

    }

}

  1. Create buttons and event listeners

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class ButtonExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Button Example");

        frame.setSize(300, 200);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        JButton button = new JButton("Click Me");

        button.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                JOptionPane.showMessageDialog(frame, "Button clicked!");

            }

        });

 

        frame.add(button);

        frame.setLayout(new FlowLayout());

        frame.setVisible(true);

    }

}

  1. Text fields and labels

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class TextFieldExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Text Field Example");

        frame.setSize(300, 200);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        JTextField textField = new JTextField(20);

        JLabel label = new JLabel("Enter your name:");

        JButton button = new JButton("Submit");

 

        button.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                String name = textField.getText();

                JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");

            }

        });

 

        frame.add(label);

        frame.add(textField);

        frame.add(button);

        frame.setLayout(new FlowLayout());

        frame.setVisible(true);

    }

}

  1. Checkboxes and radio buttons

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class CheckboxRadioButtonExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Checkbox and Radio Button Example");

        frame.setSize(300, 200);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        JCheckBox checkBox = new JCheckBox("Check Me");

        JRadioButton radioButton1 = new JRadioButton("Option 1");

        JRadioButton radioButton2 = new JRadioButton("Option 2");

 

        ButtonGroup radioGroup = new ButtonGroup();

        radioGroup.add(radioButton1);

        radioGroup.add(radioButton2);

 

        JButton button = new JButton("Submit");

 

        button.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                String message = "Checkbox selected: " + checkBox.isSelected() + "\n";

                if (radioButton1.isSelected()) {

                    message += "Selected radio button: Option 1";

                } else if (radioButton2.isSelected()) {

                    message += "Selected radio button: Option 2";

                } else {

                    message += "No radio button selected";

                }

                JOptionPane.showMessageDialog(frame, message);

            }

        });

 

        frame.add(checkBox);

        frame.add(radioButton1);

        frame.add(radioButton2);

        frame.add(button);

        frame.setLayout(new FlowLayout());

        frame.setVisible(true);

    }

}

  1. Dialog boxes (Alerts and prompts)

import javax.swing.*;

 

public class DialogBoxExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Dialog Box Example");

        frame.setSize(300, 200);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        JButton alertButton = new JButton("Show Alert");

        alertButton.addActionListener(e -> {

            JOptionPane.showMessageDialog(frame, "This is an alert message.", "Alert", JOptionPane.WARNING_MESSAGE);

        });

 

        JButton promptButton = new JButton("Show Prompt");

        promptButton.addActionListener(e -> {

            String inputValue = JOptionPane.showInputDialog(frame, "Enter your name:");

            if (inputValue != null) {

                JOptionPane.showMessageDialog(frame, "Hello, " + inputValue + "!");

            }

        });

 

        frame.add(alertButton);

        frame.add(promptButton);

        frame.setLayout(new FlowLayout());

        frame.setVisible(true);

    }

}

  1. Panels and layouts

import javax.swing.*;

import java.awt.*;

 

public class PanelLayoutExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Panel and Layout Example");

        frame.setSize(400, 300);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        JPanel panel = new JPanel();

        panel.setLayout(new GridLayout(2, 2));

 

        JButton button1 = new JButton("Button 1");

        JButton button2 = new JButton("Button 2");

        JButton button3 = new JButton("Button 3");

        JButton button4 = new JButton("Button 4");

 

        panel.add(button1);

        panel.add(button2);

        panel.add(button3);

        panel.add(button4);

 

        frame.add(panel);

        frame.setVisible(true);

    }

}

  1. Drawing on a JPanel

import javax.swing.*;

import java.awt.*;

 

class DrawingPanel extends JPanel {

    @Override

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.setColor(Color.RED);

        g.drawRect(50, 50, 200, 100);

        g.setColor(Color.BLUE);

        g.fillOval(100, 150, 100, 100);

    }

}

 

public class DrawingExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Drawing Example");

        frame.setSize(400, 300);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        DrawingPanel panel = new DrawingPanel();

        frame.add(panel);

        frame.setVisible(true);

    }

}

  1. Image display

(Note: To display images, you need to have image files available in your project directory.)

import javax.swing.*;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

 

class ImagePanel extends JPanel {

    private BufferedImage image;

 

    ImagePanel(String imagePath) {

        try {

            image = ImageIO.read(new File(imagePath));

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

 

    @Override

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.drawImage(image, 0, 0, null);

    }

}

 

public class ImageDisplayExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Image Display Example");

        frame.setSize(400, 300);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        String imagePath = "image.jpg"; // Path to your image file

        ImagePanel panel = new ImagePanel(imagePath);

        frame.add(panel);

        frame.setVisible(true);

    }

}

  1. Establish a database connection

(Note: To establish a database connection, you need a database server and appropriate credentials. Below is a simplified example using JDBC to connect to a database.)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

 

public class DatabaseConnectionExample {

    public static void main(String[] args) {

        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your database URL

        String username = "your_username"; // Replace with your database username

        String password = "your_password"; // Replace with your database password

 

        try {

            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            System.out.println("Connected to the database.");

            // Perform database operations here

            connection.close();

            System.out.println("Connection closed.");

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

Post a Comment

0 Comments