Top 30 Trending Java Coding Examples

To understand these Java examples, you should know the following:

1. Write a function to reverse a string in Java

Code:

public class ReverseString {
    public static String reverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(reverse("Java Programming"));
    }
}

Output:

gnimmargorP avaJ

Explanation:

Uses the built-in reverse() method of StringBuilder to efficiently reverse the character sequence in O(n) time.

2. Write a function to check if a string is a palindrome in Java

Code:

public class PalindromeCheck {
    public static boolean isPalindrome(String str) {
        String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int left = 0, right = cleaned.length() - 1;
        while (left < right) {
            if (cleaned.charAt(left) != cleaned.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
    }
}

Output:

true

Explanation:

Removes non-alphanumeric characters, converts to lowercase, and compares characters moving inward from both ends using two pointers.

3. Find indices of two numbers that sum up to a target using a HashMap in Java

Code:

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

public class TwoSum {
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum(nums, 9)));
    }
}

Output:

[0, 1]

Explanation:

Stores visited elements and their indices in a HashMap to check for complement values in O(1) average lookup time.

4. Find duplicate characters in a string with Java

Code:

import java.util.HashSet;
import java.util.Set;

public class DuplicateCharacters {
    public static void printDuplicates(String str) {
        Set<Character> seen = new HashSet<>();
        Set<Character> duplicates = new HashSet<>();
        
        for (char ch : str.toCharArray()) {
            if (!seen.add(ch)) {
                duplicates.add(ch);
            }
        }
        System.out.println(duplicates);
    }

    public static void main(String[] args) {
        printDuplicates("programming");
    }
}

Output:

[r, g, m]

Explanation:

Uses a set to track observed characters and collects duplicates when seen.add() evaluates to false.

5. Count occurrences of each character in a string using Streams in Java

Code:

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterCount {
    public static void main(String[] args) {
        String str = "java streams";
        Map<Character, Long> counts = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
                
        System.out.println(counts);
    }
}

Output:

{ =1, a=3, r=1, s=2, t=1, e=1, v=1, j=1, m=1}

Explanation:

Converts string to IntStream, boxes integers to Characters, and counts occurrence frequency using Collectors.groupingBy.

6. Check if two strings are anagrams of each other in Java

Code:

import java.util.Arrays;

public class AnagramCheck {
    public static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        char[] a1 = s1.toLowerCase().toCharArray();
        char[] a2 = s2.toLowerCase().toCharArray();
        Arrays.sort(a1);
        Arrays.sort(a2);
        return Arrays.equals(a1, a2);
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("listen", "silent"));
    }
}

Output:

true

Explanation:

Converts both inputs to character arrays, sorts them, and checks for array equality.

7. Generate Fibonacci series using iteration in Java

Code:

public class FibonacciIterative {
    public static void printFibonacci(int n) {
        int a = 0, b = 1;
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
    }

    public static void main(String[] args) {
        printFibonacci(7);
    }
}

Output:

0 1 1 2 3 5 8

Explanation:

Computes term values iteratively using simple additions and temporary variable swapping with O(1) extra space.

8. Compute Fibonacci series using recursion and memoization in Java

Code:

import java.util.HashMap;
import java.util.Map;

public class FibonacciMemoization {
    private static Map<Integer, Long> memo = new HashMap<>();

    public static long fib(int n) {
        if (n <= 1) return n;
        if (memo.containsKey(n)) return memo.get(n);
        long result = fib(n - 1) + fib(n - 2);
        memo.put(n, result);
        return result;
    }

    public static void main(String[] args) {
        System.out.println(fib(50));
    }
}

Output:

12586269025

Explanation:

Uses top-down dynamic programming to cache intermediate recursive outputs, converting O(2^n) time to O(n).

9. Perform binary search on a sorted array iteratively in Java

Code:

public class BinarySearch {
    public static int search(int[] arr, int target) {
        int low = 0, high = arr.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) return mid;
            if (arr[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        System.out.println(search(arr, 40));
    }
}

Output:

3

Explanation:

Halves the search space sequentially to find target values in logarithmic O(log n) time complexity.

10. Merge two sorted arrays into a single sorted array in Java

Code:

import java.util.Arrays;

public class MergeSortedArrays {
    public static int[] merge(int[] a, int[] b) {
        int[] result = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;

        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) result[k++] = a[i++];
            else result[k++] = b[j++];
        }
        while (i < a.length) result[k++] = a[i++];
        while (j < b.length) result[k++] = b[j++];
        return result;
    }

    public static void main(String[] args) {
        int[] a = {1, 3, 5};
        int[] b = {2, 4, 6};
        System.out.println(Arrays.toString(merge(a, b)));
    }
}

Output:

[1, 2, 3, 4, 5, 6]

Explanation:

Traverses both arrays simultaneously using two pointers to combine elements in linear O(n + m) time.

11. Find the maximum subarray sum using Kadane’s Algorithm in Java

Code:

public class KadanesAlgorithm {
    public static int maxSubArray(int[] nums) {
        int maxSoFar = nums[0];
        int maxEndingHere = nums[0];

        for (int i = 1; i < nums.length; i++) {
            maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
            maxSoFar = Math.max(maxSoFar, maxEndingHere);
        }
        return maxSoFar;
    }

    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(nums));
    }
}

Output:

6

Explanation:

Tracks contiguous maximum local sum and updates global maximum in a single linear O(n) pass.

12. Perform custom sorting with Comparator and Lambda Expressions in Java

Code:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Person {
    String name;
    int age;
    Person(String name, int age) { this.name = name; this.age = age; }
    @Override
    public String toString() { return name + ":" + age; }
}

public class LambdaSort {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 22),
            new Person("Charlie", 25)
        );

        people.sort(Comparator.comparingInt(p -> p.age));
        System.out.println(people);
    }
}

Output:

[Bob:22, Charlie:25, Alice:30]

Explanation:

Uses functional interfaces and Comparator.comparingInt() to sort objects by properties cleanly.

13. Read a file line by line using Files.lines() in Java

Code:

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class ReadFileLineByLine {
    public static void main(String[] args) {
        try {
            Path path = Files.createTempFile("demo", ".txt");
            Files.writeString(path, "Line 1\nLine 2\nLine 3");

            try (var lines = Files.lines(path)) {
                lines.forEach(System.out::println);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Line 1
Line 2
Line 3

Explanation:

Files.lines() reads files lazily as a Stream<String>, ensuring low memory footprint for large files.

14. Filter and collect elements using the Java Streams API

Code:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFilter {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        List<Integer> evens = numbers.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList());

        System.out.println(evens);
    }
}

Output:

[2, 4, 6, 8, 10]

Explanation:

Filters elements matching a predicate condition and collects results into a new List instance.

15. Perform map and reduce operations with Streams API in Java

Code:

import java.util.Arrays;
import java.util.List;

public class StreamMapReduce {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sumOfSquares = numbers.stream()
                .map(n -> n * n)
                .reduce(0, Integer::sum);

        System.out.println(sumOfSquares);
    }
}

Output:

55

Explanation:

Maps integers to their squares and aggregates them into a single total value using binary reducer operations.

16. Find the second largest element in an array in Java

Code:

public class SecondLargest {
    public static int findSecondLargest(int[] arr) {
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        for (int num : arr) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num > secondLargest && num != largest) {
                secondLargest = num;
            }
        }
        return secondLargest;
    }

    public static void main(String[] args) {
        int[] numbers = {12, 35, 1, 10, 34, 1};
        System.out.println(findSecondLargest(numbers));
    }
}

Output:

34

Explanation:

Maintains two tracking variables across a single loop iteration to extract second largest value in O(n) time.

17. Check if a number is prime in Java

Code:

public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;

        for (int i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPrime(29));
    }
}

Output:

true

Explanation:

Checks divisors up to the square root of n using 6k ± 1 optimization for fast primality testing.

18. Group objects using Collectors.groupingBy() in Java

Code:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class GroupingByExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "bat", "car", "ant");
        Map<Integer, List<String>> grouped = words.stream()
                .collect(Collectors.groupingBy(String::length));

        System.out.println(grouped);
    }
}

Output:

{3=[bat, car, ant], 5=[apple], 6=[banana]}

Explanation:

Groups stream items into a Map using word length evaluations as grouping key classifications.

19. Implement a thread-safe Singleton pattern in Java

Code:

public class Singleton {
    private Singleton() {}

    private static class InstanceHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return InstanceHolder.INSTANCE;
    }

    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

Output:

true

Explanation:

Uses the Bill Pugh holder pattern to achieve lazy initialization and thread safety through ClassLoader mechanics.

20. Create immutable data objects using Java Records

Code:

public class RecordDemo {
    public record User(String name, String email, int id) {}

    public static void main(String[] args) {
        User user = new User("Alex", "alex@example.com", 101);
        System.out.println(user.name());
        System.out.println(user);
    }
}

Output:

Alex
User[name=Alex, email=alex@example.com, id=101]

Explanation:

Java Records automatically generate boilerplate code including constructors, getters, equals(), hashCode(), and toString().

21. Use pattern matching for instanceof in Java

Code:

public class PatternMatchingInstanceof {
    public static void process(Object obj) {
        if (obj instanceof String s) {
            System.out.println("String length: " + s.length());
        } else if (obj instanceof Integer i) {
            System.out.println("Square: " + (i * i));
        }
    }

    public static void main(String[] args) {
        process("Hello Java");
        process(5);
    }
}

Output:

String length: 10
Square: 25

Explanation:

Eliminates explicit explicit casting after instanceof type checks by assigning a scoped variable directly.

22. Use Text Blocks for multi-line string formatting in Java

Code:

public class TextBlocksDemo {
    public static void main(String[] args) {
        String json = """
                {
                    "title": "Java Features",
                    "status": "Active"
                }
                """;
        System.out.println(json);
    }
}

Output:

{
    "title": "Java Features",
    "status": "Active"
}

Explanation:

Text blocks allow multi-line string declarations without explicit escape sequences, preserving original formatting.

23. Execute tasks using Virtual Threads in Java

Code:

import java.util.concurrent.Executors;

public class VirtualThreadsDemo {
    public static void main(String[] args) {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 2; i++) {
                final int id = i;
                executor.submit(() -> {
                    System.out.println("Task " + id + " running");
                });
            }
        }
    }
}

Output:

Task 0 running
Task 1 running

Explanation:

Spawns high-throughput, lightweight threads managed directly by the Java runtime instead of OS-level platform threads.

24. Implement custom exception handling with Try-With-Resources in Java

Code:

class CustomResource implements AutoCloseable {
    public void execute() {
        System.out.println("Resource executing...");
    }

    @Override
    public void close() {
        System.out.println("Resource closed automatically.");
    }
}

public class TryWithResourcesDemo {
    public static void main(String[] args) {
        try (CustomResource resource = new CustomResource()) {
            resource.execute();
        }
    }
}

Output:

Resource executing...
Resource closed automatically.

Explanation:

Try-with-resources statement guarantees automatic closure of resources that implement the AutoCloseable interface.

25. Implement Deep Copy using Cloneable constructors in Java

Code:

class Address {
    String city;
    Address(String city) { this.city = city; }
    Address(Address other) { this.city = other.city; }
}

class Person {
    String name;
    Address address;
    Person(String name, Address address) { this.name = name; this.address = address; }
    Person(Person other) {
        this.name = other.name;
        this.address = new Address(other.address);
    }
}

public class DeepCopyDemo {
    public static void main(String[] args) {
        Person p1 = new Person("John", new Address("NYC"));
        Person p2 = new Person(p1);
        p2.address.city = "LA";

        System.out.println("Original: " + p1.address.city);
        System.out.println("Copied: " + p2.address.city);
    }
}

Output:

Original: NYC
Copied: LA

Explanation:

Copy constructors create distinct internal reference instances, preventing modifications in copy from mutating source object state.

26. Implement an LRU Cache using LinkedHashMap in Java

Code:

import java.util.LinkedHashMap;
import java.util.Map;

class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(2);
        cache.put(1, "One");
        cache.put(2, "Two");
        cache.get(1);
        cache.put(3, "Three");

        System.out.println(cache);
    }
}

Output:

{1=One, 3=Three}

Explanation:

Configuring LinkedHashMap with access-order mode automatically handles eviction of stale entries via removeEldestEntry().

27. Check for balanced parentheses using Stack in Java

Code:

import java.util.ArrayDeque;
import java.util.Deque;

public class BalancedParentheses {
    public static boolean isBalanced(String expr) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : expr.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) return false;
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                    (c == '}' && top != '{') ||
                    (c == ']' && top != '[')) return false;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("{[()]}"));
    }
}

Output:

true

Explanation:

Pushes opening brackets onto a stack and verifies matching pop operations for every closing bracket encountered.

28. Transpose a 2D Matrix in Java

Code:

import java.util.Arrays;

public class MatrixTranspose {
    public static void main(String[] args) {
        int[][] matrix = { {1, 2, 3}, {4, 5, 6} };
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] transpose = new int[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                transpose[j][i] = matrix[i][j];
            }
        }

        for (int[] row : transpose) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Output:

[1, 4]
[2, 5]
[3, 6]

Explanation:

Swaps matrix row indices with column indices to convert horizontal dimensional dimensions into vertical representations.

29. Execute asynchronous tasks using Callable and Future in Java

Code:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableFutureDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Callable<String> task = () -> "Async Result Completed";

        Future<String> future = executor.submit(task);
        System.out.println(future.get());

        executor.shutdown();
    }
}

Output:

Async Result Completed

Explanation:

Submit tasks returning values via Callable to an ExecutorService and retrieve outputs using Future.get().

30. Flatten a nested list using flatMap() in Java

Code:

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMap {
    public static void main(String[] args) {
        List<List<String>> nested = Arrays.asList(
            Arrays.asList("A", "B"),
            Arrays.asList("C", "D", "E")
        );

        List<String> flatList = nested.stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toList());

        System.out.println(flatList);
    }
}

Output:

[A, B, C, D, E]

Explanation:

Maps each collection stream to an individual sequence before flattening all elements into a single stream output.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

Java - Abstract Classes & Interfaces
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment