30 Java Coding Interview Questions for Beginner, Mid-Level and Expert Developers

java coding interview questions

Technology is evolving rapidly and software engineers need to keep up with the latest trends in today’s competitive environment. Java is a leading programming language especially for backend programming. This article presents a variety of coding challenges that span fundamental principles, advanced features and performance optimization strategies to help you improve your Java programming abilities and understanding. 

These coding tasks will not only help technical recruiters designing coding questions for candidates but also help applicants prepare for an interview. These exercises will help you solve problems and write more efficient, resilient and maintainable Java code. Let’s start with beginner level Java coding questions.

Java Coding Interview Questions for Beginners

Developer Skill Assessment Tool

When preparing interview questions for beginners in the Java language, you should focus on core concepts and the technical areas which build a strong foundation in the language. These concepts include basic syntax, data types, control statements, arrays, strings, OOP, collections, exception and error handling. Here are 10 coding challenges designed for beginner level Java programmers.

Question 1

What will be the output of the below code:

 public class Main {
	public static void main(String[] args) {
    	int x = 10;
    	if (x > 5) {
        	int y = 20;
        	System.out.println(x + y);
    	}
    	System.out.println(x);
	}
}

Hint: Variable scope

Question 2

What is wrong with the below code:

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

Hint: Array concepts

Question 3

What is wrong with the below code:

public class Main {
	public static void main(String[] args) {
    	int x = 3.14;
    	System.out.println(x);
	}
}

Hint: Data types

Question 4

Write a Java method that reverses a given string without using any built-in method for reversal.

Question 5

What will be the output of the following code:

public class Main {
	public static void main(String[] args) {
    	int dayOfWeek = 3;
    	String day;
     	switch (dayOfWeek) {
        	case 1:
            	day = "Monday";
            	break;
        	case 2:
            	day = "Tuesday";
            	break;
        	case 3:
            	day = "Wednesday";
            	break;
        	default:
            	day = "Unknown";
    	}
     	System.out.println(day);
	}
}

Hint: Control statements

Question 6

What is wrong in the below code:

public class Main {
	public static void main(String[] args) {
    	String s1 = "Java";
    	String s2 = "Java";
    	if (s1 == s2) {
        	System.out.println("Strings are equal");
    	} else {
        	System.out.println("Strings are not equal");
    	}
	}
}

Hint: String comparison

Question 7

Write a Java program to check if the given string is a palindrome or not. A palindrome is a string that is read the same backward or forward.

Question 8

What will be the output of the following code:

public class Main {
	public static void main(String[] args) {
    	String s1 = "";
   	 s1=s1+”java”
    	String s2 = " is fun!";
    	System.out.println(s1 + s2);
	}
}

Hint: String concatenation

Question 9

What is wrong with the below code:

public class Main {
	public static void main(String[] args) {
    	System.out.println("Hello, World!");
    	return;
    	System.out.println("I am after the return statement");
	}
}

Question 10

Find the issue in the below code:

public class Main {
	public static void main(String[] args) {
    	String text;
    	int length = text.length();
   	 System.out.println("The length of the text is: " + length);
	}
}

Java Coding Interview Questions for Mid-level Developers

When designing interview questions for mid-level Java engineers, you should prepare questions that test a deeper understanding of the language and advanced features. Some of the areas that should be tested include advanced OOP, generics, collections, concurrency, file I/O, Java 8+ features, design patterns and serialization. Find below some of the questions that test these concepts:

Question 1

What is wrong with the below code:

class Counter {
	private int count = 0;
 	public void increment() {
    	count++;
	}
 	public int getCount() {
    	return count;
	}
}
 public class Main {
	public static void main(String[] args) {
    	Counter counter = new Counter();
    	Thread t1 = new Thread(() -> {
        	for (int i = 0; i < 1000; i++) {
            	counter.increment();
        	}
    	});
     	Thread t2 = new Thread(() -> {
        	for (int i = 0; i < 1000; i++) {
            	counter.increment();
        	}
    	});
     	t1.start();
    	t2.start();
     	System.out.println("Counter: " + counter.getCount());
	}
}

Hint: Thread synchronization

Question 2

What will be the output of the below code:

public class Main {
	public static void print(int a) {
    	System.out.println("int: " + a);
	}
 	public static void print(Integer a) {
    	System.out.println("Integer: " + a);
	}
 
	public static void main(String[] args) {
    	int a = 5;
    	Integer b = 10;
    	print(a);
    	print(b);
	}
}

Hint: Method overloading

Question 3

A class has three static methods all defined with a synchronized keyword. A user has called one of the static methods, and while the first method is still in execution, a second user calls a second static method. Will the second user be able to execute the second static method? Elaborate the reasoning for your answer.

Question 4

Write a Java method that takes a list of integer as input and returns a list of their factorials using CompletableFuture for asynchronous computation. The method signature should be like:

public static List<BigInteger> calculateFactorials(List<Integer> input)

Make sure that the output list retains the same order as the input list. 

Question 5

What is wrong with the below code:

public class Main {
	public static int sum(int n) {
    	if (n <= 0) {
        	return sum(n + 1);
    	}
    	return n + sum(n - 1);
	}
 	public static void main(String[] args) {
    	System.out.println(sum(-5));
	}
}

 Hint: Recursion

Question 6

What will be the output of the below code:

public class Main {
	public static void main(String[] args) {
    	Predicate<Integer> isEven = n -> n % 2 == 0;
    	System.out.println(isEven.test(4));
    	System.out.println(isEven.test(7));
	}
}

Hint: lambda expression and functional interfaces

 Question 7

What is wrong with the below code:

public class Main {
	public static void main(String[] args) {
    	List<String> list = new ArrayList<>();
    	list.add("One");
    	list.add("Two");
    	list.add("Three");
     	for (String item : list) {
        	if (item.equals("Two")) {
            	list.remove(item);
        	}
    	}
	}
}

Hint: Concurrent modification

Question 8

Write a Java method with a list of strings as input that returns a list of the top N frequent words using Java streams. You can ignore case sensitivity. The method signature should be as below:

public static List<String> findTopNFrequentWords(List<String> words, int m)

Here is an example input:

List<String> words = Arrays.asList("apple", "orange", "banana", "apple", "orange", "apple");
int n = 2;

Output for the input above will be:

[“apple”, “orange”]

Question 9

What is wrong with the below code:

public class Main {
	public static void main(String[] args) {
    	try {
        	FileInputStream fis = new FileInputStream("input.txt");
        	int data = fis.read();
        	while (data != -1) {
            	System.out.print((char) data);
            	data = fis.read();
        	}
    	} catch (IOException e) {
        	e.printStackTrace();
    	}
	}
}

Question 10

Write Java code that shows the difference between equals() and the hashCode() methods in Java. Also, write code that shows its implementation in one of your custom classes.

Java Coding Interview Questions for Expert Java Developers

When designing coding challenges for expert level Java programmers, you need to test the advanced concepts and in-depth knowledge of Java features. Some of the areas to test include concurrency, performance optimization, distributed systems, reflection and annotations, advanced design patterns and security. Sample Java coding questions can be found below:

Question 1

Find the issue in the below code:

public class Singleton {
	private static Singleton instance;
 	private Singleton() {
	}
 	public static Singleton getInstance() {
    	if (instance == null) {
        	instance = new Singleton();
    	}
    	return instance;
	}
}

Hint: Lazy initialization

Question 2

What will be the output of the below code:

public class Main {
	public static void main(String[] args) {
    	List<String> strings = new ArrayList<>();
    	strings.add("Java");
    	strings.add("Kotlin");
    	strings.add("Scala");
     	List<?> list = strings;
    	System.out.println(list.get(1));
	}
}

Hint: Type inference and diamond operator

Question 3

Find the issue in the below code:

public class Main {
	private static Object lock1 = new Object();
	private static Object lock2 = new Object();
 
	public static void main(String[] args) {
    	Thread t1 = new Thread(() -> {
        	synchronized (lock1) {
            	try {
                	Thread.sleep(100);
            	} catch (InterruptedException e) {
            	}
   	         synchronized (lock2) {
                    System.out.println("Thread 1");
            	}
        	}
    	});
     	Thread t2 = new Thread(() -> {
        	synchronized (lock2) {
            	try {
                	Thread.sleep(100);
            	} catch (InterruptedException e) {
            	}
            	synchronized (lock1) {
                    System.out.println("Thread 2");
            	}
        	}
    	});
 
    	t1.start();
    	t2.start();
	}
}

Hint: Thread synchronization

Question 4

What will be the output of the below code:

class A {
	A get() {
    	return this;
	}
}
 class B extends A {
	B get() {
    	return this;
	}
 	void message() {
    	System.out.println("Hello from B");
	}
}
 public class Main {
	public static void main(String[] args) {
    	new B().get().message();
	}
}

Hint: Inheritance and covariant return types

 Question 5

Consider the following code snippet:

public class ConcatenationChallenge {
 	public static String concatenateStrings(List<String> inputStrings) {
    	String result = "";
    	for (String str : inputStrings) {
        	result += str;
    	}
    	return result;
	}
 
	public static void main(String[] args) {
    	List<String> input = Arrays.asList("Hello", " ", "World", "!");
    	String output = concatenateStrings(input);
    	System.out.println(output);
	}
}

The concatenateStrings method uses string concatenation within a loop, which is inefficient due to the immutability of strings in Java and memory consumption. Suggest an alternative approach to improve the performance of this method without changing the output.

Question 6

What is wrong with the below code:

public class Main {
	public static void main(String[] args) {
    	String s = "Immutable";
    	try {
        	Field valueField = String.class.getDeclaredField("value");
        	valueField.setAccessible(true);
        	char[] value = (char[]) valueField.get(s);
        	value[0] = 'M';
        	System.out.println(s);
    	} catch (NoSuchFieldException | IllegalAccessException e) {
        	e.printStackTrace();
    	}
	}
}

Hint: Reflection

Question 7

What will be the output of the below code:

public class Main {
	public static void main(String[] args) {
    	List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
    	Optional<String> result = names.stream()
        	.filter(name -> name.startsWith("D"))
        	.findFirst();
 
    	System.out.println(result.orElse("No match found"));
	}
}

Hint: Java 8 optional and functional programming

 Question 8

Create a class with an asynchronous image processing pipeline using:

· CompletableFuture,

· ExecutorService

· Custom callback interface

Implement methods to load an image, apply a filter, and save the processed image. Combine these methods in a pipeline that calls a provided ImageProcessingCallback upon completion or failure.

Question 9

Consider the following code snippet:

public class GenericsChallenge {
 	public static <T extends Number & Comparable<T>> T getMax(T num1, T num2) {
    	return num1.compareTo(num2) > 0 ? num1 : num2;
	}
 	public static void main(String[] args) {
    	Integer int1 = 5;
    	Integer int2 = 10;
    	Double double1 = 3.5;
    	Double double2 = 7.5;
 
    	// Usage examples
    	Integer maxInt = getMax(int1, int2);
    	Double maxDouble = getMax(double1, double2);
	}
}

What is the purpose of the T extends Number & Comparable<T> constraint in the generic method getMax()? Explain the importance of this constraint and why it’s necessary for the method to function correctly.

Question 10

Analyze the below code:

public class GCChallenge {
 	public static void main(String[] args) {
    	List<String> longLivedList = new ArrayList<>();
     	for (int i = 0; i < 100; i++) {
        	for (int j = 0; j < 10_000; j++) {
            	String shortLivedString = "ShortLived-" + i + "-" + j;
        	}
             longLivedList.add("LongLived-" + i);
    	}
	}
}

Explain the impact of the choice of garbage collection algorithm on its performance. Describe how to select an appropriate garbage collector for this specific use case.

Conclusion

This article provides a diverse set of Java coding challenges designed for beginners, intermediate and expert developers. Through these coding challenges, recruiters can evaluate applicant’s skills and grasp on various Java concepts, from the basics to advanced topics and performance optimization. 

As Java continues to evolve, it’s essential for developers to stay up to date with the latest trends and best practices. We encourage readers to keep exploring Java, take on more complex coding challenges and connect with the Java community to keep growing their expertise and knowledge.

Test assessment tool

Further reading: