// Tutorial //

Top 50 Java Programming Interview Questions

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Top 50 Java Programming Interview Questions

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java Programming Interview Questions are always the deciding factor in any Java interview. Whether you are a beginner in Java or an expert programmer, you will be tested for your coding skills in the interview. So, it’s a good idea to brush up your coding skills before you face the interview.

Java Programming Interview Questions

I am providing 50+ Java programming questions to test your coding skills. It’s good for beginners as well as experienced Java developers. The best part is that some of the questions are from the latest releases (Java 14). If you can write Java programs using the latest features, it means you keep yourself up to date, which will work in your favor.

1. How to reverse a String in Java?

It might be surprising, but there is no reverse() utility method in the String class. But, it’s a very simple task. We can create a character array from the string and then iterate it from the end to start. We can append the characters to a string builder and finally return the reversed string.

public class StringPrograms {

	public static void main(String[] args) {

		String str = "123";
		System.out.println(reverse(str));
	}

	public static String reverse(String in) {
		if (in == null)
			throw new IllegalArgumentException("Null is not valid input");

		StringBuilder out = new StringBuilder();

		char[] chars = in.toCharArray();

		for (int i = chars.length - 1; i >= 0; i--)
			out.append(chars[i]);

		return out.toString();
	}
}

Bonus Points: Adding null check in the method and using StringBuilder for appending the characters. Easy to Miss: The indexing in Java starts from 0. So, we have to start at “chars.length - 1” in the for loop.

2. How to swap two numbers without using a third variable?

It’s a slightly tricky question. It’s a three steps process. It’s better visualized in code.

int a = 10;
int b = 20;

b = b + a; // now b is sum of both the numbers
a = b - a; // b - a = (b + a) - a = b (a is swapped)
b = b - a; // (b + a) - b = a (b is swapped)

We can’t return multiple variables in Java. Since Java is Pass-by-Value and these are primitive data types, their values won’t change. For example, below swap function will not change the input integer values.

public static void swapNumbers(int a, int b) {
    b = b + a;
	a = b - a;
	b = b - a;
}

public static void main(String[] args) {
	int a = 10;
	int b = 20;
	swapNumbers(a, b);
	System.out.printf("a is %d, b is %d", a, b); // a is 10, b is 20
}

3. Java Program to check if a vowel is present in the string?

We can use regular expression to check if the string contains vowels or not.

public class StringContainsVowels {

	public static void main(String[] args) {

		System.out.println(stringContainsVowels("Hello")); // true
		System.out.println(stringContainsVowels("TV")); // false

	}

	public static boolean stringContainsVowels(String input) {

		return input.toLowerCase().matches(".*[aeiou].*");

	}

}

4. Java program to check if the given number is Prime?

We can write a simple program to divide the given number “n” from 2 to n/2 and check the remainder. If the remainder is 0, then it’s not a prime number.

public class PrimeNumberCheck {

	public static void main(String[] args) {

		System.out.println(isPrime(19)); // true
		System.out.println(isPrime(49)); // false
	}

	public static boolean isPrime(int n) {
		if (n == 0 || n == 1) {
			return false;
		}
		if (n == 2) {
			return true;
		}
		for (int i = 2; i <= n / 2; i++) {
			if (n % i == 0) {
				return false;
			}
		}

		return true;
	}
}

But, this is not very memory and time-efficient. For a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number.

5. Fibonacci Series using recursion

We can use a for loop to print fibonacci series.

public static void printFibonacciSeries(int count) {
	int a = 0;
	int b = 1;
	int c = 1;
	for (int i = 1; i <= count; i++) {
		System.out.print(a + ", ");
		a = b;
		b = c;
		c = a + b;
	}
}

The fibonacci number is generated by adding the previous two numbers - F(N) = F(N-1) + F(N-2). We can use recursion to print fibonacci series.

public class FibonacciNumbers {
	public static int fibonacci(int n) {
		if (n <= 1)
			return n;
		return fibonacci(n - 1) + fibonacci(n - 2);
	}

	public static void main(String args[]) {
		int n = 10;
		System.out.println(fibonacci(n));
	}
}

6. Check if a List of integers contains only odd numbers?

We can use for loop and check each element one by one if they are odd or not.

public static boolean onlyOddNumbers(List<Integer> list) {
	for (int i : list) {
		if (i % 2 == 0)
			return false;
	}
	return true;
}

If the list is huge, we can use parallel stream for faster processing.

public static boolean onlyOddNumbers(List<Integer> list) {
	return list
			.parallelStream() // parallel stream for faster processing
			.anyMatch(x -> x % 2 != 0); // return as soon as any elements match the condition
}

7. Palindrome Check

A palindrome string is one whose reverse is also the same string. So we can reverse the input string and check if both strings are equal or not. We can also use the String charAt(int index) method to check for palindrome string.

boolean checkPalindromeString(String input) {
	boolean result = true;
	int length = input.length();
	for(int i=0; i < length/2; i++) {
		if(input.charAt(i) != input.charAt(length-i-1)) {
			result = false;
			break;
		}
	}
	return result;
}

8. How to remove Whitespaces from String

We can use Character.isWhitespace() method to remove whitespaces from the string.

String removeWhiteSpaces(String input){
	StringBuilder output = new StringBuilder();
	
	char[] charArray = input.toCharArray();
	
	for(char c : charArray) {
		if (!Character.isWhitespace(c))
			output.append(c);
	}
	
	return output.toString();
}

9. How to remove leading and trailing whitespaces from a string?

Java String class contains two methods to remove leading and trailing whitespaces - trim(), and strip(). The strip() method was added to the String class in Java 11. However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas the trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character. The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.

String s = "  abc  def\t";
		
s = s.strip();
		
System.out.println(s);

Since String is immutable, we have to assign the strip() output to the string.

10. Sorting an array in Java?

This question requires a deep understanding of sorting in Java. If you look at the Arrays utility class, there are many overloaded sort() methods to sort primitive as well as to object arrays. If you are sorting a primitive array in the natural order, then it’s very simple. Just use the Arrays.sort() method.

int[] array = {1, 2, 3, -1, -2, 4};

Arrays.sort(array);

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

But, if you want to sort an array of Objects, then the object must implement Comparable interface. If you want to specify the sorting criteria, then you can pass the Comparator for the sorting logic. You should read more about them at - Comparable and Comparator in Java.

11. How to Create a Deadlock Scenario Programatically?

Deadlock is a special scenario in the multi-threaded environment where two or more threads are blocked forever. The deadlock situation arises with at least two threads and two or more threads. Let’s write a simple program to create a deadlock.

public class ThreadDeadlock {

    public static void main(String[] args) throws InterruptedException {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Object obj3 = new Object();
    
        Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
        Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
        Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");
        
        t1.start();
        Thread.sleep(5000);
        t2.start();
        Thread.sleep(5000);
        t3.start();
        
    }

}

class SyncThread implements Runnable{
    private Object obj1;
    private Object obj2;

    public SyncThread(Object o1, Object o2){
        this.obj1=o1;
        this.obj2=o2;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " acquiring lock on "+obj1);
        synchronized (obj1) {
         System.out.println(name + " acquired lock on "+obj1);
         work();
         System.out.println(name + " acquiring lock on "+obj2);
         synchronized (obj2) {
            System.out.println(name + " acquired lock on "+obj2);
            work();
        }
         System.out.println(name + " released lock on "+obj2);
        }
        System.out.println(name + " released lock on "+obj1);
        System.out.println(name + " finished execution.");
    }
    private void work() {
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

All the three threads will be able to acquire a lock on the first object. But, they are using the shared resources and started in such a way that they will keep on waiting indefinitely to acquire the lock on the second object. We can use the java thread dump to detect the deadlocks. Read more at Deadlock in Java.

12. Find factorial of an integer?

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number. F(n) = F(1)*F(2)…F(n-1)*F(n). We can use recursion to find the factorial of an integer.

public static long factorial(long n) {
	if (n == 1)
		return 1;
	else
		return (n * factorial(n - 1));
}

13. Revese a Linked List?

LinkedList descendingIterator() returns an iterator that iterates over the element in the reverse order. We can use this iterator to create a new Linked List with elements in the reverse order.

LinkedList<Integer> ll = new LinkedList<>();

ll.add(1);
ll.add(2);
ll.add(3);
System.out.println(ll);

LinkedList<Integer> ll1 = new LinkedList<>();

ll.descendingIterator().forEachRemaining(ll1::add);

System.out.println(ll1);

If you are looking from the data structures and algorithms perspective, read reversing a linked list.

The array elements must be sorted for implementing binary search. The binary search algorithm is based on the following conditions. If the key is less than the middle element, then we now need to search only in the first half of the array. If the key is greater than the middle element, then we need to only search in the second half of the array. And if the key is equal to the middle element in the array, then the search ends. Finally, if the key is not found in the whole array, then it should return -1. This indicates that the element is not present.

public static int binarySearch(int arr[], int low, int high, int key) {
	int mid = (low + high) / 2;

	while (low <= high) {
		if (arr[mid] < key) {
			low = mid + 1;
		} else if (arr[mid] == key) {
			return mid;
		} else {
			high = mid - 1;
		}
		mid = (low + high) / 2;
	}
	if (low > high) {
		return -1;
	}
	return -1;
}

15. Merge Sort in Java?

Merge sort is one of the most efficient sorting algorithms. It works on the principle of Divide and Conquers. It is based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element. Then merging those sublists in a manner that results in a sorted list.

public class MergeSort {

	public static void main(String[] args) {

		int[] arr = { 70, 50, 30, 10, 20, 40, 60 };

		int[] merged = mergeSort(arr, 0, arr.length - 1);

		for (int val : merged) {
			System.out.print(val + " ");
		}

	}

	public static int[] mergeTwoSortedArrays(int[] one, int[] two) {

		int[] sorted = new int[one.length + two.length];

		int i = 0;
		int j = 0;
		int k = 0;

		while (i < one.length && j < two.length) {

			if (one[i] < two[j]) {
				sorted[k] = one[i];
				k++;
				i++;
			} else {
				sorted[k] = two[j];
				k++;
				j++;
			}
		}

		if (i == one.length) {

			while (j < two.length) {
				sorted[k] = two[j];
				k++;
				j++;
			}
		}

		if (j == two.length) {

			while (i < one.length) {
				sorted[k] = one[i];
				k++;
				i++;
			}
		}

		return sorted;

	}

	public static int[] mergeSort(int[] arr, int lo, int hi) {

		if (lo == hi) {
			int[] br = new int[1];
			br[0] = arr[lo];

			return br;
		}

		int mid = (lo + hi) / 2;

		int[] fh = mergeSort(arr, lo, mid);
		int[] sh = mergeSort(arr, mid + 1, hi);

		int[] merged = mergeTwoSortedArrays(fh, sh);

		return merged;
	}

}

16. Create a Pyramid of Characters in Java?

Pattern programs are used a lot in interviews to understand the logical thinking abilities of the interviewee. Pyramid patterns are very popular and once we get the logic on the way it’s created, writing code to achieve the same is an easy task. I have written an extensive post for different kind of pyramid patterns examples, read it here.

17. Check if two arrays contains same elements?

We will first create a set of elements from both the arrays. Then compare the elements in these sets to find if there is an element that is not present in both the sets?

package com.journaldev.programminginterviews;

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

public class ArraySameElements {

	public static void main(String[] args) {
		Integer[] a1 = {1,2,3,2,1};
		Integer[] a2 = {1,2,3};
		Integer[] a3 = {1,2,3,4};
		
		System.out.println(sameElements(a1, a2));
		System.out.println(sameElements(a1, a3));

	}

	static boolean sameElements(Object[] array1, Object[] array2) {
		Set<Object> uniqueElements1 = new HashSet<>(Arrays.asList(array1));
		Set<Object> uniqueElements2 = new HashSet<>(Arrays.asList(array2));
		
		// if size is different, means there will be a mismatch
		if(uniqueElements1.size() != uniqueElements2.size()) return false;
		
		for(Object obj : uniqueElements1) {
			// element not present in both?
			if (!uniqueElements2.contains(obj)) return false;
		}
		
		return true;
	}
}

18. Sum of all elements in integer array?

It’s a very simple program. We can use for loop to iterate over the array elements and add them to get the final sum.

int[] array = { 1, 2, 3, 4, 5 };

int sum = 0;

for (int i : array)
	sum += i;

System.out.println(sum);

19. Find second largest number in an array?

There are many ways to solve this problem. We can sort the array in natural ascending order and take the second last value. But, sorting is an expensive operation. We can also use two variables to find the second largest value in a single iteration.

private static int findSecondHighest(int[] array) {
	int highest = Integer.MIN_VALUE;
	int secondHighest = Integer.MIN_VALUE;

	for (int i : array) {
		if (i > highest) {
			secondHighest = highest;
			highest = i;
		} else if (i > secondHighest) {
			secondHighest = i;
		}

	}
	return secondHighest;
}

20. How to Shuffle an Array in Java?

We can use Random class to generate random index numbers and shuffle the elements.

int[] array = { 1, 2, 3, 4, 5, 6, 7 };

Random rand = new Random();

for (int i = 0; i < array.length; i++) {
	int randomIndexToSwap = rand.nextInt(array.length);
	int temp = array[randomIndexToSwap];
	array[randomIndexToSwap] = array[i];
	array[i] = temp;
}
System.out.println(Arrays.toString(array));

We can run the shuffling code inside another for loop to shuffle multiple rounds.

21. How to find if a string is present in a text file?

We can use Scanner class to read the file contents line by line. Then use String contains() method to check if the string is present in the file or not.

boolean findStringInFile(String filePath, String str) throws FileNotFoundException {
	File file = new File(filePath);

	Scanner scanner = new Scanner(file);

	// read the file line by line
	while (scanner.hasNextLine()) {
		String line = scanner.nextLine();
		if (line.contains(str)) {
			scanner.close();
			return true;
		}
	}
	scanner.close();
	return false;
}

The above code assumes that the string we are searching for in the file doesn’t contain newline characters.

22. How to print date in specific format?

We can use SimpleDateFormat class to get the date string into specific formatting.

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());
System.out.println(date); // 06-23-2020

Recommended Reading: Java SimpleDateFormat.

23. How to merge two lists in java?

We can use the addAll() method to merge multiple lists in Java.

List<String> list1 = new ArrayList<>();
list1.add("1");
List<String> list2 = new ArrayList<>();
list2.add("2");

List<String> mergedList = new ArrayList<>(list1);
mergedList.addAll(list2);
System.out.println(mergedList); // [1, 2]

24. How to Sort HashMap by values?

HashMap is not an ordered collection. So, sorting its entries doesn’t make any sense. But, we can sort the entries based on value and store into LinkedHashMap. LinkedHashMap maintains the order of insertion.

package com.journaldev.programminginterviews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortHashMapByValue {

	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<>();

		scores.put("David", 95);
		scores.put("Jane", 80);
		scores.put("Mary", 97);
		scores.put("Lisa", 78);
		scores.put("Dino", 65);

		System.out.println(scores);

		scores = sortByValue(scores);

		System.out.println(scores);

	}

	private static Map<String, Integer> sortByValue(Map<String, Integer> scores) {
		Map<String, Integer> sortedByValue = new LinkedHashMap<>();

		// get the entry set
		Set<Entry<String, Integer>> entrySet = scores.entrySet();
		System.out.println(entrySet);

		// create a list since the set is unordered
		List<Entry<String, Integer>> entryList = new ArrayList<>(entrySet);
		System.out.println(entryList);

		// sort the list by value
		entryList.sort((x, y) -> x.getValue().compareTo(y.getValue()));
		System.out.println(entryList);

		// populate the new hash map
		for (Entry<String, Integer> e : entryList)
			sortedByValue.put(e.getKey(), e.getValue());

		return sortedByValue;
	}

}

25. remove all occurrences of a given character from input String?

String class doesn’t have any method to remove characters. We can use the replace() method to create a new string without the given character.

String str1 = "abcdABCDabcdABCD";
		
str1 = str1.replace("a", ""); 

System.out.println(str1); // bcdABCDbcdABCD

The string is immutable in Java. All the string manipulation methods return a new string. So, it’s necessary that we assign it to another variable.

26. How to get distinct characters and their count in a String?

We can create the character array from the string. Then iterate over it and create a HashMap with the character as key and their count as value.

String str1 = "abcdABCDabcd";

char[] chars = str1.toCharArray();

Map<Character, Integer> charsCount = new HashMap<>();

for(char c : chars) {
	if(charsCount.containsKey(c)) {
		charsCount.put(c, charsCount.get(c)+1);
	}else
		charsCount.put(c, 1);
}

System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}

27. How to prove String is immutable programatically?

String s1 = "Java"; // "Java" String created in pool and reference assigned to s1

String s2 = s1; //s2 is also having the same reference to "Java" in the pool

System.out.println(s1 == s2); // proof that s1 and s2 have same reference

s1 = "Python"; 
//s1 value got changed above, so how String is immutable?

//well, in the above case a new String "Python" got created in the pool
//s1 is now referring to the new String in the pool 
//BUT, the original String "Java" is still unchanged and remains in the pool
//s2 is still referring to the original String "Java" in the pool

// proof that s1 and s2 have different reference
System.out.println(s1 == s2); 

System.out.println(s2); 
// prints "Java" supporting the fact that original String value is unchanged, hence String is immutable

28. Write a Program to showcase inheritance?

class Animal {
	String color;
}

class Cat extends Animal {
	void meuw(){
		System.out.println("Meuw");
	}
}

29. Write a Program to Show Diamond Problem with Multiple Inheritance?

Java doesn’t allow extending multiple classes. It’s to keep it simple and avoid diamond problem.

interface I {
	void foo();
}
class A implements I{
	public void foo() {}
}

class B implements I{
	public void foo() {}
}

class C extends A, B { // won't compile
	public void bar() {
		super.foo();
	}
}

In above example, if Java would have allowed multiple class inheritance, then which super foo() method should get called? There could be a mechanism to fix this, but Java language developers thought it’s better to keep it simple by not allowing multiple inheritance.

30. Write a Program to show try catch example?

Let’s look at a simple try-catch block code.

try {
	FileInputStream fis = new FileInputStream("test.txt");
}catch(FileNotFoundException e) {
	e.printStackTrace();
}

From Java 7 onwards, We can also catch multiple exceptions in a single catch block. It’s useful when we have the same code in all the catch blocks.

public static void foo(int x) throws IllegalArgumentException, NullPointerException {
	// some code
}

public static void main(String[] args) {
	try {
		foo(10);
	} catch (IllegalArgumentException | NullPointerException e) {
		System.out.println(e.getMessage());
	}
}

31. Write a code to show NullPointerException

If we are calling a function on the “null”, it will throw NullPointerException.

public static void main(String[] args) {
	printString(null, 3);
	
}

static void printString(String s, int count){
	for (int i = 0 ; i < count; i++) {
		System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException
	}
}

That’s why it’s better to have null check in place for early validation.

static void printString(String s, int count){
	if(s == null) return;
	for (int i = 0 ; i < count; i++) {
		System.out.println(s.toUpperCase());
	}
}

We can also throw IllegalArgumentException based on the project requirements.

32. How to Create a Record in Java?

Records is a preview feature introduced in Java 14. Records allow us to create a POJO class with minimal code. It automatically generates hashCode(), equals(), getter methods, and toString() method code for the class. Records are final and implicitly extends java.lang.Record class.

import java.util.Map;
 
public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {
}

Read more at Records in Java.

33. How to create Text Blocks in Java?

Java 13 added text blocks as a preview feature. We can create multiline strings using text blocks. The multiline string has to be written inside a pair of triple-double quotes.

String textBlock = """
		Hi
		Hello
		Yes""";

It’s same as creating a string as “Hi\nHello\nYes”.

34. Show example of switch expressions and multi-label case statements

The switch expressions were added as a preview feature in Java 12. It became a standard feature in Java 14 release. The below examples show switch expressions as well as multi-label case statements.

int choice = 2;

int x = switch (choice) {
case 1, 2, 3:
	yield choice;
default:
	yield -1;
};
System.out.println("x = " + x); // x = 2

We can also use lambda expressions in switch expressions.

String day = "TH";
String result = switch (day) {
case "M", "W", "F" -> "MWF";
case "T", "TH", "S" -> "TTS";
default -> {
	if (day.isEmpty())
		yield "Please insert a valid day.";
	else
		yield "Looks like a Sunday.";
}

};
System.out.println(result); // TTH

35. How to Compile and Run a Java Class from Command Line?

Let’s say we have a class as below.

public class Test {

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

}

We can compile it using the following code.

javac Test.java

For running the class, we can run the following command.

java Test

From the recent releases, java command will take care of compilation also if the class file is not present. If the class is in a package com.journaldev, then it should be inside the folder com/journaldev. The command to compile and run will be as follows.

java com/journaldev/Test.java

If our class requires some additional JARs to compile and run, we can use the -cp java option.

java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar  com/journaldev/Test.java

36. How to create Enum in Java?

Let’s look at a simple Enum.

public enum ThreadStates {
	START,
	RUNNING,
	WAITING,
	DEAD;
}

ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING, and DEAD. All Enum implicitly extends java.lang.Enum class and implements Serializable and Comparable interfaces. Enum can have methods also, read more at Enums in Java.

37. How to use forEach() method?

The forEach() method provides a shortcut to perform an action on all the elements of an iterable. Let’s say we have to iterate over the list elements and print it.

List<String> list = new ArrayList<>();

Iterator<String> it = list.iterator();

while (it.hasNext()) {
	System.out.println(it.next());
}

We can use forEach() method with lambda expression to reduce the code size.

List<String> list = new ArrayList<>();

list.forEach(System.out::print);

38. Write an interface with default and static method?

Java 8 introduced default and static methods in interfaces. This has bridged the gap between interfaces and abstract classes.

public interface Interface1 {
	
	// regular abstract method
	void method1(String str);
	
	default void log(String str){
		System.out.println("I1 logging::"+str);
	}
	
	static boolean isNull(String str) {
		System.out.println("Interface Null Check");

		return str == null ? true : "".equals(str) ? true : false;
	}
}

Read more at Java 8 interface changes.

39. How do we create a Functional interface?

An interface with exactly one abstract method is called Functional Interface. @FunctionalInterface annotation is added so that we can mark an interface as functional interface. The major benefit of Java 8 functional interfaces is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class implementation.

@FunctionalInterface
interface Foo {
	void test();
}

Further Reading: Java 8 Functional Interfaces.

40. Show an example of using lambda expressions in Java

Runnable is an excellent example of a functional interface. We can use lambda expressions to create a runnable.

Runnable r1 = () -> System.out.println("My Runnable");

41. Show examples of overloading and overriding in Java

When a class have two or more methods with the same name, they are called overloaded methods.

class Foo {

	void print(String s) {
		System.out.println(s);
	}

	void print(String s, int count) {
		while (count > 0) {
			System.out.println(s);
			count--;
		}
	}
}

When a superclass method is also implemented in the child class, it’s a case of overriding.

class Base {
	void printName(){
		System.out.println("Base Class");
	}
}

class Child extends Base{
	@Override
	void printName(){
		System.out.println("Child Class");
	}
}

Recommend Reading: Overriding vs Overloading.

42-49. Guess the Output of Code Snippets

Let’s look at 8 code snippets and guess their output.

  1. String s1 = "abc";
    String s2 = "abc";
    System.out.println("s1 == s2 is:" + s1 == s2);
    

    Output: false Explanation: The given statements output will be “false” because in java + operator precedence is more than == operator. So the given expression will be evaluated to “s1 == s2 is:abc” == “abc” i.e false.

  2. String s3 = "JournalDev";
    int start = 1;
    char end = 5;
    System.out.println(start + end);
    System.out.println(s3.substring(start, end));
    

    Output: ourn Explanation: The given statements output will be “ourn”. First character will be automatically type caste to int. After that since in java first character index is 0, so it will start from ‘o’ and print till ‘n’. Note that in String substring function it leaves the end index.

  3. HashSet shortSet = new HashSet();
    for (short i = 0; i < 100; i++) {
    	shortSet.add(i);
    	shortSet.remove(i - 1);
    }
    System.out.println(shortSet.size());
    

    Output: 100 Explanation: The size of the shortSet will be 100. Java Autoboxing feature has been introduced in JDK 5, so while adding the short to HashSet<Short> it will automatically convert it to Short object. Now “i-1” will be converted to an int while evaluation and after that it will autoboxed to Integer object but there is no Integer object in the HashSet, so it will not remove anything from the HashSet and finally its size will be 100.

  4. What will be the boolean “flag” value to reach the finally block?

    try {
    	if (flag) {
    		while (true) {
    		}
    	} else {
    		System.exit(1);
    	}
    } finally {
    	System.out.println("In Finally");
    }
    

    Explanation: The finally block will never be reached here. If flag will be TRUE, it will go into an infinite loop and if it’s false it’s exiting the JVM. So finally block will never be reached here.

  5. String str = null;
    String str1="abc";
    System.out.println(str1.equals("abc") | str.equals(null));
    

    Output: NullPointerException Explanation: The given print statement will throw java.lang.NullPointerException because while evaluating the OR logical operator it will first evaluate both the literals and since str is null, .equals() method will throw exception. Its always advisable to use short circuit logical operators i.e “||” and “&&” which evaluates the literals values from left and since the first literal will return true, it will skip the second literal evaluation.

  6. String x = "abc";
    String y = "abc";
    x.concat(y);
    System.out.print(x);
    

    Output: abc Explanation: The x.concat(y) will create a new string but it’s not assigned to x, so the value of x is not changed.

  7. public class MathTest {
    
    	public void main(String[] args) {
    		
    		int x = 10*10-10;
    		
    		System.out.println(x);
    	}
    
    }
    

    Output: Runtime error Explanation: This is a tricky question, it looks like the test is about the order of execution of the mathematical operators and syntax of main method will get overlooked. It will produce Runtime error because main method is not static, something like below.

    pankaj:bin pankaj$ java MathTest
    Error: Main method is not static in class MathTest, please define the main method as:
       public static void main(String[] args)
    
  8. public class Test {
    
    	public static void main(String[] args) {
    		try {
    			throw new IOException("Hello");
    		}catch(IOException | Exception e) {
    			System.out.println(e.getMessage());
    		}
    	}
    }
    

    Output: Compile-Time Error Explanation: It will be a compile time error as The exception IOException is already caught by the alternative Exception.

UPDATE: Head over to some more java coding interview questions.

50. Find 5 mistakes in the following code snippet

package com.journaldev.programming-interviews;

public class String Programs {

	static void main(String[10] args) {
		String s = "abc"
		System.out.println(s);
	}
}
  1. Package name can’t have hyphens.
  2. Class name can’t have whitespaces.
  3. The main method is not public, so it won’t run.
  4. The main method argument shouldn’t specify the size.
  5. The semicolon is missing in the string definition.

Conclusion

I have tried my best to include easy as well as slightly complex programming questions in this tutorial. Also, I have added code snippets and questions related to recent changes in the Java features.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

“Find 5 mistakes in the following code snippet” “public class String Programs” Never seen a class returning something. It won’t compile either.

- S3QQ

    lvoed to read this complex questions dude. keep it up this kind of great work.

    - vijay

      I really enjoyed to practice this article. Thank you for sharing with all.

      - Purnima

        6th solution is incorrect, it should be allMatch instead of anyMatch.

        - WASEEM Hawaldar

          For this code String s3 = “JournalDev”; int start = 1; char end = 5; System.out.println(start + end); System.out.println(s3.substring(start, end)); Output : 6 ourn

          - Nikesh Urkude

            question no:1 for loop is wrong it won’t print all characters, you have to add >= for total length iteration. for (int i = chars.length - 1; i >= 0; i–) {}

            - Pratik

              Question 4 — finally block is of course reacheable if the flag is null -> the if statement causes null pointer exception and will end in finally try { if (flag) { while (true) { } } else { System.exit(1); } } finally { System.out.println(“In Finally”); }

              - user5

                Thanks For these good Questions

                - Vaibhav

                  Hi, Nice questions. Just wanna add one thing to question 4, if you do something like- if (flag=1/0==1) { it will run the finally block.

                  - Yugaank

                    Thank you very much Pankaj., good Job. It will really helps lot.

                    - Nagaraju