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
- Start reading the string from the last character
- Append each character to a new string
- 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
- Reverse the string
- Compare original and reversed strings
- 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
- Use a
HashMapto store character counts - Traverse the string character by character
- Increment frequency in the map
- 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
- Base case: factorial(0) = 1
- 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
- Assume first element as maximum
- Compare with remaining elements
- 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
- Calculate expected sum using formula
n(n+1)/2 - Subtract actual sum of array
- 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
- Prime numbers have exactly two factors
- Check divisibility from 2 to √n
- 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
- Use a
Setto track unique values - 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
- Track the largest and second-largest values
- Iterate through the array only once
- 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
- Convert string to character array
- Store frequency using
HashMap - 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
- Use a
Setto store unique elements - 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
- Convert strings to character arrays
- Sort both arrays
- 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
- Split string by space
- Reverse each word individually
- 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
- Store character counts in
LinkedHashMap - Maintain insertion order
- 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
- Use nested loops
- Swap elements when required
- 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
- Convert list to stream
- Use
max()with comparator - 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 referenceequals()→ 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
- Initialize first two numbers
- Calculate next using sum of previous two
- 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));
}
}
