Java coding interview

Java Coding Questions for Tech Round (With Step-by-Step Explanation)

Java technical interviews focus heavily on problem-solving ability, core Java fundamentals, and clean coding practices.
In this article, we will go through frequently asked Java coding questions in tech rounds, explaining each step clearly so beginners and experienced developers can both benefit.

1. Reverse a String Without Using reverse()

🔹 Problem Statement

Reverse a given string without using any built-in reverse function.

🔹 Approach Explanation

  1. Start reading the string from the last character
  2. Append each character to a new string
  3. Continue until the first character

This tests your understanding of loops and string manipulation.

🔹 Java Code

String input = "hello";
String reversed = "";

for (int i = input.length() - 1; i >= 0; i--) {
    reversed += input.charAt(i);
}

System.out.println(reversed);

🔹 Time Complexity

O(n) – each character is processed once

2. Check Whether a String Is Palindrome

🔹 Problem Statement

Check if a string reads the same forward and backward.

🔹 Approach Explanation

  1. Reverse the string
  2. Compare original and reversed strings
  3. If both are equal → Palindrome

🔹 Java Code

String input = "madam";
String reversed = new StringBuilder(input).reverse().toString();

System.out.println(input.equals(reversed));

>>>> OR without reverse()

  String string1 = "madam";
       String result = "";
       for(int i = string1.length() -1; i>=0; i--) {
           result += string1.charAt(i);
       }      
  System.out.println(result.equals(string1) ? "Palindrome" : " not Palindrome");

🔹 Time Complexity

O(n)

3. Find Duplicate Characters in a String

🔹 Problem Statement

Identify characters that appear more than once in a string.

🔹 Approach Explanation

  1. Use a HashMap to store character counts
  2. Traverse the string character by character
  3. Increment frequency in the map
  4. Print characters whose count > 1

🔹 Java Code

String input = "programming";
Map<Character, Integer> map = new HashMap<>();

for (char c : input.toCharArray()) {
    map.put(c, map.getOrDefault(c, 0) + 1);
}

map.forEach((key, value) -> {
    if (value > 1) {
        System.out.println(key);
    }
});

🔹 Time Complexity

O(n)

4. Swap Two Numbers Without Using Third Variable

🔹 Problem Statement

Swap two integers without using an extra variable.

🔹 Approach Explanation

We use addition and subtraction to swap values mathematically.

🔹 Java Code

int a = 10;
int b = 20;

a = a + b;
b = a - b;
a = a - b;

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

🔹 Time Complexity

O(1)

5. Find Factorial of a Number (Recursive)

🔹 Problem Statement

Calculate factorial using recursion.

🔹 Approach Explanation

  1. Base case: factorial(0) = 1
  2. Recursive case: n × factorial(n−1)

🔹 Java Code

class Main {
     static int factorial(int n) {
        if(n ==0) {
            return 1;
        }
        return n*factorial(n-1);
    }
    public static void main(String[] args) {
        System.out.print(factorial(4));
    }
}

🔹 Time Complexity

O(n)

6. Find Largest Element in an Array

🔹 Problem Statement

Find the maximum number in an array.

🔹 Approach Explanation

  1. Assume first element as maximum
  2. Compare with remaining elements
  3. Update max if a larger value is found

🔹 Java Code

int[] arr = {4, 7, 1, 9};
int max = arr[0];

for (int num : arr) {
    if (num > max) {
        max = num;
    }
}

System.out.println(max);

OR 

List<Integer> nums = Arrays.asList(1,33,2,4,45);
        int max = nums.get(0);
        for(int i=1;i<nums.size(); i++){
            if(nums.get(i)>max) {
                max = nums.get(i);
            }
        }
        
        System.out.print(max);

🔹 Time Complexity

O(n)

7. Find Missing Number in an Array (1 to N)

🔹 Problem Statement

One number is missing from a sequence of 1 to N.

🔹 Approach Explanation

  1. Calculate expected sum using formula
    n(n+1)/2
  2. Subtract actual sum of array
  3. Remaining value is the missing number

🔹 Java Code

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

int expectedSum = n * (n + 1) / 2;
int actualSum = 0;

for (int num : arr) {
    actualSum += num;
}

System.out.println(expectedSum - actualSum);

🔹 Time Complexity

O(n)

8. Check Whether a Number Is Prime

🔹 Problem Statement

Determine whether a number is prime.

🔹 Approach Explanation

  1. Prime numbers have exactly two factors
  2. Check divisibility from 2 to √n
  3. If divisible → not prime

🔹 Java Code

int n = 29;
boolean isPrime = true;

for (int i = 2; i <= Math.sqrt(n); i++) {
    if (n % i == 0) {
        isPrime = false;
        break;
    }
}

System.out.println(isPrime);

🔹 Time Complexity

O(√n)

9. Find Duplicate Elements Using Java 8 Streams

🔹 Problem Statement

Find duplicates in a list using Java 8.

🔹 Approach Explanation

  1. Use a Set to track unique values
  2. If add() returns false → duplicate element

🔹 Java Code

List<Integer> list = List.of(1, 2, 3, 2, 4, 3);
Set<Integer> set = new HashSet<>();

list.stream()
    .filter(e -> !set.add(e))
    .forEach(System.out::println);

🔹 Time Complexity

O(n)

10. Create an Immutable Class

🔹 Problem Statement

Design an immutable class in Java.

🔹 Key Rules

  • Class must be final
  • Fields must be private final
  • No setters

🔹 Java Code

final class Employee {
    private final int id;

    public Employee(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

11. Find Second Largest Number in an Array

🔹 Problem Statement

Find the second largest element from an integer array.

🔹 Step-by-Step Approach

  1. Track the largest and second-largest values
  2. Iterate through the array only once
  3. Update values based on comparison

🔹 Java Code

int[] arr = {10, 5, 20, 8};
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;
    }
}

System.out.println(secondLargest);

🔹 Time Complexity

O(n)

12. Count Occurrence of Each Character in a String

🔹 Problem Statement

Count how many times each character appears in a string.

🔹 Step-by-Step Approach

  1. Convert string to character array
  2. Store frequency using HashMap
  3. Print key-value pairs

🔹 Java Code

String input = "java";
Map<Character, Integer> map = new HashMap<>();

for (char c : input.toCharArray()) {
    map.put(c, map.getOrDefault(c, 0) + 1);
}

System.out.println(map);

13. Remove Duplicate Elements from an Array

🔹 Problem Statement

Remove duplicate values from an array.

🔹 Step-by-Step Approach

  1. Use a Set to store unique elements
  2. Convert set back to array or list

🔹 Java Code

int[] arr = {1, 2, 2, 3, 4, 4};
Set<Integer> set = new LinkedHashSet<>();

for (int num : arr) {
    set.add(num);
}

System.out.println(set);

14. Check Anagram Strings

🔹 Problem Statement

Check if two strings are anagrams.

🔹 Step-by-Step Approach

  1. Convert strings to character arrays
  2. Sort both arrays
  3. Compare sorted arrays

🔹 Java Code

String s1 = "listen";
String s2 = "silent";

char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();

Arrays.sort(a1);
Arrays.sort(a2);

System.out.println(Arrays.equals(a1, a2));

Note:  here a1, a2 is primitive and char is used for that. Arrays.sort() only work with this.

Character is used for Object type

and Arrays.sort(arr, Collections.reverseOrder()) in revers only work with object(Character). Not with char.

15. Reverse Each Word in a String

🔹 Problem Statement

Reverse each word in a sentence without changing word order.

🔹 Step-by-Step Approach

  1. Split string by space
  2. Reverse each word individually
  3. Append to result

🔹 Java Code

String input = "Java is powerful";
String[] words = input.split(" ");
String result = "";

for (String word : words) {
    result += new StringBuilder(word).reverse() + " ";
}

System.out.println(result.trim());

16. Find First Non-Repeated Character

🔹 Problem Statement

Find the first character that does not repeat in a string.

🔹 Step-by-Step Approach

  1. Store character counts in LinkedHashMap
  2. Maintain insertion order
  3. Return first character with count = 1

🔹 Java Code

String input = "swiss";
Map<Character, Integer> map = new LinkedHashMap<>();

for (char c : input.toCharArray()) {
    map.put(c, map.getOrDefault(c, 0) + 1);
}

for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    if (entry.getValue() == 1) {
        System.out.println(entry.getKey());
        break;
    }
}

17. Sort Array Without Using sort()

🔹 Problem Statement

Sort an array manually (basic sorting logic).

🔹 Step-by-Step Approach

  1. Use nested loops
  2. Swap elements when required
  3. Implement simple bubble sort

🔹 Java Code

int[] arr = {5, 2, 8, 1}; //primitive type

for (int i = 0; i < arr.length; i++) {
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] > arr[j]) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}

System.out.println(Arrays.toString(arr));

Using stream() method::

int[] arr = {23, 45, 12, 3, 22, 4}; //primitive type

Arrays.stream(arr)
      .boxed()
      .sorted(Collections.reverseOrder())
      .forEach(System.out::print);

//In Java 8 Streams, boxed() converts a primitive stream into an object (wrapper) stream.

18. Java 8: Find Maximum Number from List

🔹 Problem Statement

Find the maximum number using Java 8 Streams.

🔹 Step-by-Step Approach

  1. Convert list to stream
  2. Use max() with comparator
  3. Fetch value using get()

🔹 Java Code

List<Integer> list = Arrays.asList(3, 7, 1, 9);

int max = list.stream()
              .max(Integer::compare)
              .get();

System.out.println(max);

19. Difference Between == and equals() (Logic Based)

🔹 Explanation

  • == → compares memory reference
  • equals() → compares content

🔹 Example

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b);        // false
System.out.println(a.equals(b));   // true

If primitive type string then 
String a = "java";
String b = "java";

System.out.println(a == b);        // false
System.out.println(a.equals(b));   // true

20. Print Fibonacci Series

🔹 Problem Statement

Print Fibonacci series up to N numbers.

🔹 Step-by-Step Approach

  1. Initialize first two numbers
  2. Calculate next using sum of previous two
  3. Loop until count is reached

🔹 Java Code

class Main {
     // Recursive Fibonacci method
    static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args) {

        int num = 5;
        int[] fib = new int[num + 1];

        for (int n = 0; n <= num; n++) {
            fib[n] = fibonacci(n);
        }

        System.out.println(Arrays.toString(fib));
    }
}

Similar Posts