Top 42 Java Coding Interview Questions & Answers [Freshers to Advanced]
Did you know that 90% of Fortune 500 companies use Java to build large-scale applications? Java remains one of the most popular programming languages for developers worldwide, especially for those pursuing a career in software development. Whether you are a beginner or an experienced Java developer, cracking a coding interview is important to get a job in this competitive industry. This blog provides the top Java coding interview questions across different experience levels, from beginners to experienced professionals. These questions will help you prepare efficiently for your next interview, highlighting important concepts and problem-solving approaches.
Java Coding Questions for Freshers
As a beginner in Java, it is important to grasp the fundamentals of the language and its core concepts like abstraction and polymorphism. The following Java coding interview questions for beginners are designed to test your understanding of basic Java principles, syntax, and problem-solving abilities. These coding challenges will help you showcase your skills in areas such as data types, control structures, and simple algorithms. Mastering the following questions will not only prepare you for interviews but also strengthen your foundation for more advanced programming tasks.
Q1. Write a Java program to check if a number is prime.
Sample Answer: A prime number is a number greater than 1 that has no divisors other than 1 and itself. Here is a Java code to check if a number is prime or not:
public class PrimeCheck {
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int number = 29;
System.out.println(number + " is prime? " + isPrime(number));
}
}
Q2. QWrite a Java program to reverse a string without using the StringBuilder or reverse() method.
Sample Answer: Here’s a Java program to reverse a string by iterating from the last character to the first.
public class StringReverse {
public static String reverseString(String str) {
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
String input = "Hello";
System.out.println("Reversed: " + reverseString(input));
}
}
Pro Tip: Basic conceptual-based Java coding job interview questions and answers are quite common in entry-level job interviews. You can check out our Java cheat sheet to prepare effectively for answering coding questions.
Q3. Write a program to check if a given string is a palindrome.
Sample Answer: A string is a palindrome if it reads the same forwards and backward. Here’s a program that checks if a given string is palindrome or not.
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Q4. Write a Java program to find the factorial of a number using recursion.
Sample Answer: This program finds the factorial of a number by calling itself recursively until it reaches 1, giving us the factorial value step-by-step.
public class FactorialRecursion {
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}
Q5. Write a program to swap two numbers without using a temporary variable.
Sample Answer: Here’s a way to swap two numbers without a temporary variable. By using arithmetic operations, the code reassigns the values directly to each variable.
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before Swap: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Q6. Write a Java program to find the largest element in an array.
Sample Answer: This code finds the largest element in an array by initially setting the first element as the maximum and comparing each subsequent element to update this value.
public class LargestInArray {
public static int findLargest(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public static void main(String[] args) {
int[] numbers = {3, 9, 1, 5, 7};
System.out.println("Largest element is: " + findLargest(numbers));
}
}
Q7. Write a program to find the second-largest number in an array.
Sample Answer: This Java program identifies the second-largest number in an array by tracking both the largest and second-largest values in one pass through the array.
public class SecondLargestInArray {
public static int findSecondLargest(int[] array) {
int firstLargest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : array) {
if (num > firstLargest) {
secondLargest = firstLargest;
firstLargest = num;
} else if (num > secondLargest && num != firstLargest) {
secondLargest = num;
}
}
return secondLargest;
}
public static void main(String[] args) {
int[] numbers = {4, 8, 1, 2, 9, 3};
System.out.println("Second largest element is: " + findSecondLargest(numbers));
}
}
Q8. Write a program to find the sum of the digits of a number.
Sample Answer: Here’s a method to calculate the sum of a number’s digits. It uses a loop to extract each digit, adding them together until the number is fully processed.
public class SumOfDigits {
public static int sumDigits(int number) {
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
public static void main(String[] args) {
int number = 1234;
System.out.println("Sum of digits: " + sumDigits(number));
}
}
Q9. Write a Java program to find the Fibonacci series up to a given number.
Sample Answer: In this code, the Fibonacci sequence is generated by repeatedly adding the last two numbers to get the next term, up to the specified count.
public class FibonacciSeries {
public static void fibonacci(int n) {
int a = 0, b = 1;
System.out.print(a + " " + b + " ");
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
}
}
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci series up to " + n + " terms: ");
fibonacci(n);
}
}
Pro Tip: TCS frequently hires Java developers to work on various projects. You can go through some commonly asked TCS Java developer interview questions to improve your chances of landing a job at the company.
Q10. Write a Java program to find the GCD of two numbers using the Euclidean algorithm.
Sample Answer: The program given below uses the Euclidean algorithm to find the GCD of two numbers. It works by repeatedly dividing the larger number by the smaller until the remainder is zero.
public class GCDExample {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args) {
int a = 56, b = 98;
System.out.println("GCD of " + a + " and " + b + " is: " + gcd(a, b));
Q11. Write a Java program to reverse the order of words in a sentence.
Sample Answer: This code reverses the order of words in a sentence by splitting it into words, reversing the array, and then joining them back into a single string.
public class ReverseWords {
public static String reverseWords(String sentence) {
String[] words = sentence.split(" ");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]).append(" ");
}
return reversed.toString().trim();
}
public static void main(String[] args) {
String sentence = "Java is fun";
System.out.println("Reversed sentence: " + reverseWords(sentence));
}
}
}
Q12. Write a Java program to count the number of vowels in a string.
Sample Answer: This program counts the number of vowels in a string by iterating through each character and checking if it’s a vowel, using a simple loop.
public class VowelCounter {
public static int countVowels(String str) {
int count = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) != -1) count++;
}
return count;
}
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Number of vowels: " + countVowels(str));
}
}
Q13. Write a Java program to implement the quicksort algorithm.
Sample Answer: Here, quicksort is implemented by choosing a pivot, partitioning the array around it, and then recursively sorting each subarray to arrange the elements.
import java.util.Arrays;
public class QuickSort {
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
public static int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
public static void main(String[] args) {
int[] array = {10, 7, 8, 9, 1, 5};
quickSort(array, 0, array.length - 1);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
Q14. Write a Java program to find all permutations of a given string.
Sample Answer: This code finds all permutations of a given string by swapping characters and recursively generating each possible combination in sequence.
public class Permutations {
public static void permute(String str, String answer) {
if (str.length() == 0) {
System.out.println(answer);
return;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String ros = str.substring(0, i) + str.substring(i + 1);
permute(ros, answer + ch);
}
}
public static void main(String[] args) {
String str = "ABC";
permute(str, "");
}
}
Java Coding Questions for 2 to 3 Years of Experienced Professionals
Mid-level job interview questions typically require you to demonstrate a deeper understanding of the language and its applications. In this section, you will encounter Java coding test questions and answers that challenge your ability to optimize code, work with complex data structures, and implement design patterns. These questions are designed to assess your critical thinking and problem-solving skills, as well as your experience with Java frameworks and libraries.
Q15. Write a Java program to implement a stack using an array.
Sample Answer: This code shows how to implement a stack using an array with methods to push, pop, and check if the stack is empty.
public class StackUsingArray {
private int[] stack;
private int top;
public StackUsingArray(int capacity) {
stack = new int[capacity];
top = -1;
}
public void push(int value) {
if (top == stack.length - 1) System.out.println("Stack overflow");
else stack[++top] = value;
}
public int pop() {
if (top == -1) {
System.out.println("Stack underflow");
return -1;
}
return stack[top--];
}
public boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
StackUsingArray stack = new StackUsingArray(5);
stack.push(10);
stack.push(20);
stack.pop();
System.out.println("Stack is empty: " + stack.is
Q16. Write a Java program to convert infix expressions to postfix expressions.
Sample Answer: Here, the program converts infix expressions to postfix, using operator precedence and a stack to manage the expression structure.
import java.util.Stack;
public class InfixToPostfix {
public static String infixToPostfix(String exp) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : exp.toCharArray()) {
if (Character.isLetterOrDigit(c)) result.append(c);
else if (c == '(') stack.push(c);
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') result.append(stack.pop());
stack.pop();
} else {
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) result.append(stack.pop());
stack.push(c);
}
}
while (!stack.isEmpty()) result.append(stack.pop());
return result.toString();
}
public static int precedence(char ch) {
return switch (ch) {
case '+', '-' -> 1;
case '*', '/' -> 2;
case '^' -> 3;
default -> -1;
};
}
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println("Postfix expression: " + infixToPostfix(exp));
}
}
Q17. Write a Java program to find the first non-repeating character in a string.
Sample Answer: This code finds the first non-repeating character in a string by counting occurrences and returning the first unique character.
import java.util.HashMap;
public class FirstNonRepeatingChar {
public static Character firstNonRepeatingChar(String str) {
HashMap<Character, Integer> countMap = new HashMap<>();
for (char ch : str.toCharArray()) {
countMap.put(ch, countMap.getOrDefault(ch, 0) + 1);
}
for (char ch : str.toCharArray()) {
if (countMap.get(ch) == 1) return ch;
}
return null;
}
public static void main(String[] args) {
String str = "swiss";
System.out.println("First non-repeating character: " + firstNonRepeatingChar(str));
}
}
Q18. Write a program to merge two sorted arrays into a single sorted array.
Sample Answer: This program merges two sorted arrays into a single sorted array by comparing elements from each array in sequence.
import java.util.Arrays;
public class MergeSortedArrays {
public static int[] merge(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) merged[k++] = arr1[i++];
else merged[k++] = arr2[j++];
}
while (i < arr1.length) merged[k++] = arr1[i++];
while (j < arr2.length) merged[k++] = arr2[j++];
return merged;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
System.out.println("Merged array: " + Arrays.toString(merge(arr1, arr2)));
}
}
Pro Tip: Answering any type of Java programming interview questions can be tricky. To answer coding questions more effectively, enroll in a Java course to improve your knowledge of core concepts.
Q19. Write a Java program to find the maximum difference between two elements in an array such that the larger element appears after the smaller element.
Sample Answer: This code calculates the maximum difference between two array elements where the larger element comes after the smaller one.
public class MaxDifference {
public static int maxDifference(int[] arr) {
int minElement = arr[0];
int maxDiff = arr[1] - arr[0];
for (int i = 1; i < arr.length; i++) {
maxDiff = Math.max(maxDiff, arr[i] - minElement);
minElement = Math.min(minElement, arr[i]);
}
return maxDiff;
}
public static void main(String[] args) {
int[] arr = {2, 3, 10, 6, 4, 8, 1};
System.out.println("Maximum difference: " + maxDifference(arr));
}
}
Q20. Write a Java program to remove duplicates from an array without using any additional data structures.
Sample Answer: This program removes duplicates in an array without using additional data structures, modifying the array to store only unique elements.
import java.util.ArrayList;
import java.util.List;
public class ArrayIntersection {
public static List<Integer> intersect(int[] arr1, int[] arr2) {
List<Integer> intersection = new ArrayList<>();
for (int i : arr1) {
for (int j : arr2) {
if (i == j && !intersection.contains(i)) {
intersection.add(i);
break;
}
}
}
return intersection;
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
System.out.println("Intersection: " + intersect(arr1, arr2));
}
}
Q21. Write a Java program to find the intersection of two arrays.
Sample Answer: Here, the code finds common elements between two arrays by comparing each element and storing unique intersections in a list.
public class SelectionSort {
public static void selectionSort(int[] array) {
int n = array.length; // Get the length of the array
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the minimum is the first element in the unsorted part
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j; // Update the index of the minimum element
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
int[] array = {29, 10, 14, 37, 13};
selectionSort(array);
for (int num : array) {
System.out.print(num + " "); // Output the sorted elements
}
}
}
Q22. Write a Java program to find the maximum subarray sum using Kadane’s Algorithm.
Sample Answer: This program finds the maximum sum of a contiguous subarray using Kadane’s algorithm, which efficiently tracks local and global maxima.
import java.util.ArrayList;
import java.util.List;
public class MaxSubarraySum {
public static int maxSubArraySum(int[] arr) {
int maxSoFar = arr[0];
int maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Maximum subarray sum: " + maxSubArraySum(arr));
}
}
Q23. Write a Java program to rotate a matrix by 90 degrees clockwise.
Sample Answer: This program rotates a square matrix by 90 degrees clockwise. It achieves this by moving elements in layers from top to bottom, right to left, etc., using a temporary variable for the swaps.
public class RotateMatrix {
public static void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = temp;
}
}
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotate(matrix);
for (int[] row : matrix) {
for (int num : row) System.out.print(num + " ");
System.out.println();
}
}
}
Q24. Write a Java program to find all pairs of elements in an array whose sum equals a given number.
Sample Answer: The program given below adds up to a given target to find pairs in an array. Additionally, it uses nested loops to locate and display all matching pairs, showing each valid combination.
public class PairSum {
public static void findPairs(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
System.out.println("(" + arr[i] + ", " + arr[j] + ")");
}
}
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 5;
findPairs(arr, target);
}
}
Q25. Write a Java program to find the missing number in an array of integers from 1 to n.
Sample Answer: This code calculates the missing number in a sequence from 1 to n by finding the difference between the sum of the complete sequence and existing elements.
public class MissingNumber {
public static int findMissing(int[] arr, int n) {
int totalSum = n * (n + 1) / 2;
int arraySum = 0;
for (int num : arr) arraySum += num;
return totalSum - arraySum;
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6};
System.out.println("Missing number: " + findMissing(arr, 6));
}
}
Q26. Write a Java program to sort an array of 0s, 1s, and 2s without using any sorting algorithm.
Sample Answer: This given program implements a three-pointer technique efficiently. It arranges an array of 0s, 1s, and 2s in linear time by swapping elements based on their values.
public class Sort012 {
public static void sort(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0 -> {
int temp = arr[low];
arr[low++] = arr[mid];
arr[mid++] = temp;
}
case 1 -> mid++;
case 2 -> {
int temp = arr[mid];
arr[mid] = arr[high];
arr[high--] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 0, 1, 2};
sort(arr);
for (int num : arr) System.out.print(num + " ");
}
}
Q27. Write a Java program to generate Pascal’s Triangle up to a given number of rows.
Sample Answer: By iterating through each row and calculating values from the previous row’s elements, this code constructs Pascal’s Triangle up to a specified number of rows.
import java.util.ArrayList;
import java.util.List;
public class PascalsTriangle {
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> row = new ArrayList<>();
row.add(1);
for (int j = 1; j < i; j++) {
row.add(triangle.get(i - 1).get(j - 1) + triangle.get(i - 1).get(j));
}
if (i > 0) row.add(1);
triangle.add(row);
}
return triangle;
}
public static void main(String[] args) {
int numRows = 5;
System.out.println(generate(numRows));
}
}
Pro Tip: Several multinational companies hire Java developers to develop software applications. Deloitte is one of the companies that hire and offer lucrative compensation packages for Java developers. Consider applying at Deloitte and prepare for Java-specific interview questions with the help of our guide on Deloitte Java developer interview questions.
Q28. Write a Java program to implement selection sort.
Sample Answer: This program implements a selection sort that identifies the smallest unsorted element and swaps it with the current position. It then proceeds to progressively sort the array in ascending order.
public class SelectionSort {
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
int[] array = {29, 10, 14, 37, 13};
selectionSort(array);
for (int num : array) {
System.out.print(num + " ");
}
}
}
Pro Tip: Interviewers try to test your knowledge of OOP concepts during Java coding interviews. You can learn about the benefits of OOPs in Java to answer the interview questions related to it.
Java Coding Questions for 5 to 10+ Years of Experienced Professionals
Interviews for experienced professionals assess your ability to deal with complex coding problems to offer effective solutions. The Java coding interview questions are used to test your knowledge of advanced Java topics. Additionally, you would also need to show that you can write clean and efficient code to crack interviews as an experienced developer. Here are some of the most commonly asked senior-level Java developer coding interview questions:
Q29. Write a Java program to implement a simple LRU (Least Recently Used) Cache.
Sample Answer: To implement an LRU (least recently used) cache, this code leverages LinkedHashMap with an overridden method to remove the oldest entries once capacity is reached, maintaining cache efficiency.
import java.util.LinkedHashMap;
import java.util.Map;
public 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<>(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.put(4, "D"); // Evicts the oldest entry (1, "A")
System.out.println(cache); // Output: {2=B, 3=C, 4=D}
}
}
Q30. Write a Java program to implement a thread-safe Singleton design pattern.
Sample Answer: This Singleton pattern ensures thread safety by employing double-checked locking. The following allows only one instance of the class across all threads in a concurrent environment.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Q31. Write a Java program to check if two strings are anagrams using sorting.
Sample Answer: This program checks two strings for anagram status by sorting their characters and confirming equality, which indicates identical character arrangements.
import java.util.Arrays;
public class AnagramCheck {
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) return false;
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
System.out.println(areAnagrams("listen", "silent")); // true
}
}
Q32. Write a Java program to serialize and deserialize a Java object.
Sample Answer: Illustrating object persistence, this code saves an object to a file and reads it back, using serialization and deserialization to preserve the object’s state.
import java.io.*;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class SerializeDeserialize {
public static void main(String[] args) {
Person person = new Person("John", 30);
// Serialization
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person deserializedPerson = (Person) ois.readObject();
System.out.println("Deserialized Person: " + deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Q33. Write a Java program to reverse a linked list using recursion.
Sample Answer: This recursive approach reverses a linked list by adjusting node links one by one until reaching the end, where it then unwinds the recursion, setting the final order.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class ReverseLinkedList {
public static ListNode reverse(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head = reverse(head);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
Q34. Write a Java program to implement the Producer-Consumer problem using the wait and notify methods.
Sample Answer: This Java program demonstrates the producer-consumer problem using a shared queue with wait() and notify() for synchronized data exchange between two threads.
import java.util.LinkedList;
import java.util.Queue;
class ProducerConsumer {
private final Queue<Integer> queue = new LinkedList<>();
private final int LIMIT = 10;
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
while (queue.size() == LIMIT) {
wait();
}
queue.add(value++);
System.out.println("Produced " + value);
notify();
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (queue.isEmpty()) {
wait();
}
int value = queue.poll();
System.out.println("Consumed " + value);
notify();
}
}
}
}
public class Main {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Thread producer = new Thread(() -> {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumer = new Thread(() -> {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
}
Pro Tip: Infosys regularly asks these Java coding job interview questions and answers when hiring a developer. If you aim to get a job at Infosys as a Java developer, refer to our blog on Infosys interview questions for Java developers.
Q35. Write a Java program to find the lowest common ancestor (LCA) of two nodes in a binary tree.
Sample Answer: The find LCA function identifies the lowest common ancestor in a binary tree by recursively searching for the two target nodes in the left and right subtrees.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public class LowestCommonAncestor {
public static TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = findLCA(root.left, p, q);
TreeNode right = findLCA(root.right, p, q);
return (left != null && right != null) ? root : (left != null ? left : right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
TreeNode lca = findLCA(root, root.left.left, root.left.right);
System.out.println("LCA: " + lca.val); // Output: 2
}
}
Q36. Write a Java program to find the kth smallest element in a binary search tree.
Sample Answer: This program uses in-order traversal to find the k-th smallest element in a Binary Search Tree. It will count nodes until the desired element is found.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public class KthSmallestInBST {
private static int count = 0;
private static int result = Integer.MIN_VALUE;
public static int kthSmallest(TreeNode root, int k) {
inOrder(root, k);
return result;
}
private static void inOrder(TreeNode node, int k) {
if (node == null) return;
inOrder(node.left, k);
if (++count == k) {
result = node.val;
return;
}
inOrder(node.right, k);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(1);
root.right = new TreeNode(4);
root.left.right = new TreeNode(2);
System.out.println("2nd smallest element: " + kthSmallest(root, 2)); // Output: 2
}
}
Q37. Write a Java program to perform binary search in a rotated sorted array.
Sample Answer: Here is a binary search implementation to find a target element in a rotated sorted array. The following code adjusts search bounds based on rotation.
public class RotatedArraySearch {
public static int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else {
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] nums = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
System.out.println("Index of target: " + search(nums, target)); // Output: 4
}
}
Q38. Write a Java program to detect a cycle in a directed graph using DFS.
Sample Answer: This code uses depth-first search (DFS) with recursion to check for cycles in a directed graph by tracking visited nodes and nodes in the current recursive stack.
import java.util.ArrayList;
import java.util.List;
public class GraphCycleDetection {
public static boolean hasCycle(List<List<Integer>> adjList, boolean[] visited, boolean[] stack, int node) {
if (stack[node]) return true;
if (visited[node]) return false;
visited[node] = true;
stack[node] = true;
for (int neighbor : adjList.get(node)) {
if (hasCycle(adjList, visited, stack, neighbor)) return true;
}
stack[node] = false;
return false;
}
public static void main(String[] args) {
int vertices = 4;
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) adjList.add(new ArrayList<>());
adjList.get(0).add(1);
adjList.get(1).add(2);
adjList.get(2).add(0);
adjList.get(2).add(3);
boolean[] visited = new boolean[vertices];
boolean[] stack = new boolean[vertices];
boolean cycle = false;
for (int i = 0; i < vertices; i++) {
if (!visited[i] && hasCycle(adjList, visited, stack, i)) {
cycle = true;
break;
}
}
System.out.println("Cycle detected: " + cycle); // Output: true
}
}
Q39. Write a Java program to find the maximum path sum in a binary tree.
Sample Answer: This program calculates the maximum path sum in a binary tree by recursively evaluating left and right subtree sums and updating the maximum.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public class MaxPathSum {
private static int maxSum = Integer.MIN_VALUE;
public static int maxPathSum(TreeNode root) {
calculateSum(root);
return maxSum;
}
private static int calculateSum(TreeNode node) {
if (node == null) return 0;
int leftSum = Math.max(0, calculateSum(node.left));
int rightSum = Math.max(0, calculateSum(node.right));
maxSum = Math.max(maxSum, leftSum + rightSum + node.val);
return node.val + Math.max(leftSum, rightSum);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(-10);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println("Maximum path sum: " + maxPathSum(root)); // Output: 42
}
}
Q40. Write a Java program to validate a binary search tree.
Sample Answer: This program validates if a binary tree is a BST by ensuring each node falls within a valid range determined by its ancestors.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public class ValidateBST {
public static boolean isValidBST(TreeNode root) {
return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private static boolean validate(TreeNode node, long min, long max) {
if (node == null) return true;
if (node.val <= min || node.val >= max) return false;
return validate(node.left, min, node.val) && validate(node.right, node.val, max);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(2);
root.left = new TreeNode(1);
root.right = new TreeNode(3);
System.out.println("Is valid BST: " + isValidBST(root)); // Output: true
}
}
Pro Tip: Read the Java developer job description carefully and draft the application, including the resume and cover letter according to the JD.
Q41. Write a Java program to serialize and deserialize a binary tree.
Sample Answer: This code converts a binary tree to a string (serialization) and reconstructs it back to a tree (deserialization) using level-order traversal.
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public class SerializeDeserializeTree {
// Serializes a tree to a single string.
public static String serialize(TreeNode root) {
if (root == null) return "null";
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append("null,");
} else {
sb.append(node.val).append(",");
queue.add(node.left);
queue.add(node.right);
}
}
return sb.toString();
}
// Deserializes your encoded data to tree.
public static TreeNode deserialize(String data) {
if (data.equals("null")) return null;
String[] values = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(values[0]));
queue.add(root);
for (int i = 1; i < values.length; i++) {
TreeNode node = queue.poll();
if (!values[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(values[i]));
queue.add(node.left);
}
if (!values[++i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(values[i]));
queue.add(node.right);
}
}
return root;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(5);
String serialized = serialize(root);
System.out.println("Serialized: " + serialized);
TreeNode deserialized = deserialize(serialized);
System.out.println("Deserialized Root: " + deserialized.val);
}
}
Q42. Write a Java program to find the number of islands in a 2D grid.
Sample Answer: Here is a program that counts distinct islands in a 2D grid by traversing each land cell with DFS and marking connected cells to prevent double-counting.
public class NumberOfIslands {
public static int numIslands(char[][] grid) {
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
private static void dfs(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0') return;
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
public static void main(String[] args) {
char[][] grid = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
System.out.println("Number of islands: " + numIslands(grid)); // Output: 3
}
}
Tips for Java Coding Job Interview Preparation
You can ace a Java coding job interview by building a strong foundation in Java concepts and practicing programming skills. The coding interview preparation requires a well-structured plan to guide your study and practice. Here are some essential tips to help you succeed in your Java coding job interview preparation:
- Make a Plan: Start by creating a comprehensive study plan. Familiarize yourself with the Java developer roadmap and break down your preparation into manageable sections. Focus on key Java topics, algorithms, data structures, and frameworks. Setting specific timelines will help you stay on track.
- Practice Coding Daily: Consistency is key. Dedicate daily time to solving coding challenges on platforms like LeetCode, HackerRank, or CodeSignal. This will enhance your problem-solving skills and help you get comfortable writing clean, efficient code.
- Work on Real Projects: Apply your knowledge by working on personal or open-source projects. This hands-on experience will help reinforce your understanding of Java concepts and showcase your skills to potential employers.
- Prepare for Behavioral Questions: Interviews often include behavioral questions that assess your soft skills and teamwork abilities. Practice the STAR (situation, task, action, result) technique to articulate your past experiences effectively.
- Craft a Strong Cover Letter: Write a tailored Java developer cover letter that highlights your relevant skills and experiences. Use the opportunity to showcase your passion for Java development and how you can contribute to the company’s success.
Conclusion
Approach your interviews by preparing Java coding job interview questions and answers that can lead to your long-term career success in software development. In addition, revisiting common coding patterns, data structures, and algorithms can significantly improve your coding skills for these interviews. You can use platforms like LeetCode or HackerRank for practice. These platforms can help you simulate the interview environment, helping you prepare more effectively. If you are wondering which language would be most beneficial for you as per your goals, check out our blog on C++ vs. Java to make an informed decision.
FAQs
Answer: Understanding algorithms is quiet important for java coding interviews as they help you solve problems efficiently. Employers look for candidates who can write optimal solutions and understand time and space complexity.
Answer: Knowing popular frameworks like Spring or Hibernate can give you an advantage, especially for roles that require specific expertise. Be sure to review the job description to tailor your preparation.
Answer: Yes, platforms like LeetCode, HackerRank, and CodeSignal are great for practice. They provide a range of problems and simulate the coding interview environment.