0% found this document useful (0 votes)
23 views50 pages

Top Java Coding Interview Questions (With Answers) _ DigitalOcean

The document provides a comprehensive list of common Java coding interview questions along with their answers, aimed at helping candidates prepare for Java programming roles. Topics covered include string manipulation, number swapping, prime number checking, Fibonacci sequence generation, and more. Each question is accompanied by example code to illustrate the solution effectively.

Uploaded by

bhushanseelan786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views50 pages

Top Java Coding Interview Questions (With Answers) _ DigitalOcean

The document provides a comprehensive list of common Java coding interview questions along with their answers, aimed at helping candidates prepare for Java programming roles. Topics covered include string manipulation, number swapping, prime number checking, Fibonacci sequence generation, and more. Each question is accompanied by example code to illustrate the solution effectively.

Uploaded by

bhushanseelan786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

CONTENTS 

1. How do you reverse a string in Java?


2. How do you swap two numbers without using a third variable in Java?
3. Write a Java program to check if a vowel is present in a string
4. Write a Java program to check if the given number is a prime number
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics, AGREE & PROCEED
5. Write a Java program to print a Fibonacci sequence using recursion
enhanced user experience, or advertising. You may choose to consent to
6. use
our How do you
of these check if ora manage
technologies, list of integers contains Please
your own preferences. only odd numbers in CHOICES
MANAGE
visit our cookie policy for more information.
Java?
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 1/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

7. How do you check whether a string is a palindrome in Java? 

8. How do you remove spaces from a string in Java?


9. How do you remove leading and trailing spaces from a string in Java?
10. How do you sort an array in Java?
11. How do you create a deadlock scenario programmatically in Java?
12. How can you find the factorial of an integer in Java?
13. How do you reverse a linked list in Java?
14. How do you implement a binary search in Java?
15. Write a Java program that illustrates merge sort
16. Can you create a pyramid of characters in Java?
17. Write Java program that checks if two arrays contain the same
elements
18. How do you get the sum of all elements in an integer array in Java?
19. How do you find the second largest number in an array in Java?

// TUTORIAL //

Top Java Coding Interview Questions (With Answers)

Updated on April 17, 2025

Interview Questions Java

By Pankaj Kumar and Anish Singh Walia

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 2/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Introduction

If you’re interviewing for a Java programming role, then your coding skills will probably be
tested. Whether you’re a beginner in Java or an expert programmer, this article provides
some common Java interview questions and answers to help you prepare.

1. How do you reverse a string in Java?

There is no reverse() utility method in the String class. However, you can create a
character array from the string and then iterate it from the end to the start. You can append
the characters to a string builder and finally return the reversed string.
The following example code shows one way to reverse a string:

Copy

public class StringPrograms {

This site uses cookies and related technologies, as described in


public static void main(String[] args) {
our privacy policy, for purposes that may include site operation, analytics,
String str = "123";
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
System.out.println(reverse(str));
visit our cookie policy for more information.
}
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 3/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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 for adding null check in the method and using StringBuilder for appending
the characters. Note that the indexing in Java starts from 0, so you need to start at
chars.length - 1 in the for loop.

2. How do you swap two numbers without using a third

variable in Java?

Swapping numbers without using a third variable is a three-step process that’s better
visualized in code:

Copy

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)

The following example code shows one way to implement the number swap method:

Copy

This site uses cookies and related technologies, as described in


public policy,
our privacy class for
SwapNumbers { may include site operation, analytics,
purposes that
enhanced user experience, or advertising. You may choose to consent to
public
our use static
of these void main(String[]
technologies, args)
or manage your own{ preferences. Please
intcookie
visit our a = 10;
policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 4/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

int b = 20;

System.out.println("a is " + a + " and b is " + b);

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

System.out.println("After swapping, a is " + a + " and b is " + b);


}

The output shows that the integer values are swapped:

Copy

Output
a is 10 and b is 20
After swapping, a is 20 and b is 10

3. Write a Java program to check if a vowel is present in

a string

The following example code shows how to use a regular expression to check whether the
string contains vowels:

Copy

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) {


This site uses cookies and related technologies, as described in
return input.toLowerCase().matches(".*[aeiou].*");
our privacy policy, for purposes that may include site operation, analytics,
}
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
}
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 5/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

4. Write a Java program to check if the given number is

a prime number

You can write a program to divide the given number n , by a number from 2 to n /2 and
check the remainder. If the remainder is 0, then it’s not a prime number. The following
example code shows one way to check if a given number is a Prime number:

Copy

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;
}

Although this program works, it’s not very memory and time-efficient. Consider that, 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. site
This Write a Java
uses cookies program
and related to
technologies, asprint
describedain Fibonacci sequence
our privacy policy, for purposes that may include site operation, analytics,
using recursion
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 6/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

A Fibonacci sequence is one in which each number is the sum of the two previous
numbers. In this example, the sequence begins with 0 and 1 . The following example code
shows how to use a for loop to print a Fibonacci sequence:

Copy

public class PrintFibonacci {

public static void printFibonacciSequence(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;
}
}

public static void main(String[] args) {


printFibonacciSequence(10);
}

Copy

Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

You can also use recursion to print a Fibonacci sequence, because the Fibonacci number is
generated by adding the previous two numbers in the sequence:

Copy
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
F(N) =user
enhanced F(N-1) + F(N-2)
experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 7/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

The following example class shows how to use recursion to calculate a Fibonacci sequence
that is 10 numbers long:

Copy

public class PrintFibonacciRecursive {

public static int fibonacci(int count) {


if (count <= 1)
return count;

return fibonacci(count - 1) + fibonacci(count - 2);


}

public static void main(String args[]) {


int seqLength = 10;

System.out.print("A Fibonacci sequence of " + seqLength + " numbers: ");

for (int i = 0; i < seqLength; i++) {


System.out.print(fibonacci(i) + " ");
}
}

Copy

Output
A Fibonacci sequence of 10 numbers: 0 1 1 2 3 5 8 13 21 34

6. How do you check if a list of integers contains only

odd numbers in Java?

You can use a for loop and check whether each element is odd:

This site uses cookies and related technologies, as described in


Copy
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these
public technologies,
static or manage your own preferences.list)
boolean onlyOddNumbers(List<Integer> Please{
visit our cookie policy for
for (int i : list) { more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 8/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

if (i % 2 == 0)
return false;
}

return true;
}

If the list is large, you can use parallel stream for faster processing, as shown in the
following example code:

Copy

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
}

To learn more about the math behind determining if an integer is odd, refer to the Modulo
operation on Wikipedia.

7. How do you check whether a string is a palindrome in

Java?

A palindrome string is the same string backwards or forwards. To check for a palindrome,
you can reverse the input string and check if the result is equal to the input. The following
example code shows how to use the String charAt(int index) method to check for
palindrome strings:

Copy

boolean checkPalindromeString(String input) {


boolean result = true;
int length = input.length();

for (int i = 0; i < length/2; i++) {


This site
ifuses cookies and related
(input.charAt(i) technologies, as described
!= input.charAt(length - i -in1)) {
our privacy policy,
result for purposes that may include site operation, analytics,
= false;
enhanced user
break; experience, or advertising. You may choose to consent to
our use} of these technologies, or manage your own preferences. Please
visit our
} cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 9/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

return result;
}

8. How do you remove spaces from a string in Java?

Products
The following example code shows one way to remove spaces from a string using with the
Character.isWhitespace() method:
Solutions

Developers Copy

Partners
String removeWhiteSpaces(String input) {
StringBuilder output = new StringBuilder();
Pricing
char[] charArray = input.toCharArray();

for (char c : charArray) {


Log in
if (!Character.isWhitespace(c)) Sign up
output.append(c);
}

return output.toString(); Blog


}

Docs
Learn more about removing spaces and other characters from a string in Java.
Get Support
9. How do you remove leading and trailing spaces from a

string in Java? Contact Sales

The String class contains two methods to remove leading and trailing whitespaces: trim()
Tutorials
and Questions
strip() . The Product
strip() method Docs to theCloud
was added Chats
String class in Java 11. Search Community
The strip()
method uses the Character.isWhitespace() method to check if the character is a
whitespace. This method uses Unicode code points, while the trim() method identifies any
character with a 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
This site uses
Unicode cookies and
standard. Therelated technologies,
following exampleascode
described
showsinhow to use the strip() method to
our privacy policy, for purposes that may include site operation, analytics,
remove whitespaces:
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 10/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

String s = " abc def\t";

s = s.strip();

System.out.println(s);

Because String is immutable, you have to assign the strip() output to the string.

10. How do you sort an array in Java?

The Arrays utility class has many overloaded sort() methods to sort primitive and to
object arrays. If you are sorting a primitive array in the natural order, then you can use the
Arrays.sort() method, as shown in the following example:

Copy

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

Arrays.sort(array);

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

However, if you want to sort an array of objects, then the object must implement the
Comparable interface. If you want to specify the sorting criteria, then you can pass the
Comparator for the sorting logic. Learn more about Comparable and Comparator in Java.

11. How do you create a deadlock scenario

programmatically in Java?

Deadlock is a scenario in a multi-threaded Java environment where two or more threads


are blocked forever. The deadlock situation arises with at two or more threads. The
following example code creates a deadlock scenario:

This site uses cookies and related technologies, as described in Copy


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
public class ThreadDeadlock {
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
public static void main(String[] args) throws InterruptedException {
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 11/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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.");
}
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhancedprivate void work()
user experience, {
or advertising. You may choose to consent to
try {
our use of these technologies, or manage your own preferences. Please
Thread.sleep(30000);
visit our cookie policy for more information.
} catch (InterruptedException e) {
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 12/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

e.printStackTrace();
}
}

All three threads will be able to acquire a lock on the first object. However, they are using
shared resources and are started in such a way that they will keep on waiting indefinitely to
acquire the lock on the second object. You can use the Java thread dump to detect the
deadlocks. Learn more about deadlock in Java.

12. How can you find the factorial of an integer in Java?

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given
number:

Copy

F(n) = F(1)*F(2)...F(n-1)*F(n)

The following example code shows how to use recursion to find the factorial of an integer:

Copy

public static long factorial(long n) {


if (n == 1)
return 1;
else
return (n * factorial(n - 1));
}

13. How do you reverse a linked list in Java?

This site uses cookies and related technologies, as described in


LinkedList descendingIterator() returns an iterator that iterates over the element in reverse
our privacy policy, for purposes that may include site operation, analytics,
order. The
enhanced following
user example
experience, code shows
or advertising. You mayhow to use
choose this iterator
to consent to to create a new Linked
Listusewith
our elements
of these listed inorthe
technologies, reverse
manage yourorder:
own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 13/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Copy

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);

Learn more about reversing a linked list from a data structures and algorithms perspective.

14. How do you implement a binary search in Java?

The array elements must be sorted to implement binary search. The binary search
algorithm is based on the following conditions:
If the key is less than the middle element, then you now need to search only in the first
half of the array.
If the key is greater than the middle element, then you need to search only in the
second half of the array.
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.

The following example code implements a binary search:

Copy

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

This site uses


while cookies
(low and related
<= high) { technologies, as described in
our privacy policy, for <purposes
if (arr[mid] key) { that may include site operation, analytics,
enhanced user experience,
low = mid + 1; or advertising. You may choose to consent to
our use} ofelse
theseiftechnologies,
(arr[mid] == or key)
manage
{ your own preferences. Please
visit ourreturn
cookie policy
mid; for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 14/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

} else {
high = mid - 1;
}
mid = (low + high) / 2;
}

if (low > high) {


return -1;
}

return -1;
}

15. Write a Java program that illustrates merge sort

Merge sort is one of the most efficient sorting algorithms. It works on the principle of
“divide and conquer”. It is based on the idea of breaking down a list into several sub-lists
until each sub-list consists of a single element, and then merging those sub-lists in a
manner that results in a sorted list. The following example code shows one way to use
merge sort:

Copy

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;
This site uses cookies and related technologies, as described in
int kpolicy,
= 0; for purposes that may include site operation, analytics,
our privacy
enhanced user experience, or advertising. You may choose to consent to
while (i < one.length && j < two.length) {
our use of these technologies, or manage your own preferences. Please
visit ourif (one[i]
cookie policy< for
two[j]) {
more information.
sorted[k] = one[i];
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 15/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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;
} uses cookies and related technologies, as described in
This site
our privacy policy, for purposes that may include site operation, analytics,
}
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 16/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

16. Can you create a pyramid of characters in Java?

Pattern programs are a very popular interview topic. This type of question is used to
understand the logical thinking abilities of the interviewee. Refer to Pyramid Pattern
Programs in Java for examples of different ways to create pyramid patterns.

17. Write Java program that checks if two arrays contain

the same elements

To check if two arrays contain the same elements, you need to first create a set of
elements from both the arrays, and then compare the elements in these sets to find if there
is an element that is not present in both sets. The following example code shows how to
check if two arrays only contain common elements:

Copy

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
This site (Object
uses obj
cookies and: related
uniqueElements1)
technologies,{as described in
// element not present inmay
both?
our privacy policy, for purposes that include site operation, analytics,
enhanced if user
(!uniqueElements2.contains(obj))
experience, or advertising. You mayreturn
choosefalse;
to consent to
}
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
return true;
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 17/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Copy

Output
true
false

18. How do you get the sum of all elements in an integer

array in Java?

You can use a for loop to iterate over the array elements and add them to get the final
sum:

Copy

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

int sum = 0;

for (int i : array)


sum += i;

System.out.println(sum);

19. How do you find the second largest number in an

array in Java?

There are many ways to solve this problem. You can sort the array in natural ascending
order and take the second last value. However, sorting is an expensive operation. You can
also use two variables to find the second largest value in a single iteration, as shown in the
This site uses cookies and related technologies, as described in
following example:
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information. Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 18/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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 do you shuffle an array in Java?

The following example code shows how to use the Random class to generate random index
numbers and shuffle the elements:

Copy

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));

You can run the shuffling code inside another for loop to shuffle multiple rounds.
This site uses cookies and related technologies, as described in
21.
our How
privacy can
policy, you find
for purposes ainclude
that may string in a text
site operation, file in Java?
analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
The following example code shows how to use the Scanner class to read the file contents
visit our cookie policy for more information.
line by line and then use the String contains() method to check if the string is present in
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 19/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

the file:

Copy

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;
}

Note that the example code assumes that the string that you’re searching for in the file
doesn’t contain newline characters.

22. How do you print a date in specific format in Java?

The following example code shows how to use the SimpleDateFormat class to format the
date string:

Copy

String pattern = "MM-dd-yyyy";


SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());


System.out.println(date); // 06-23-2020

This site uses cookies and related technologies, as described in


Lear
our morepolicy,
privacy aboutforthe Java SimpleDateFormat.
purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
23.
visit ourHow do you
cookie policy for moremerge
information.two lists in Java?

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 20/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

The following example code shows how to use the addAll() method to merge multiple lists
in Java:

Copy

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. Write a Java program that sorts HashMap by value

HashMap is not an ordered collection. The following example code shows how to sort the
entries based on value and store them into LinkedHashMap , which maintains the order of
insertion:

Copy

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);
This site uses cookies and related
scores.put("Lisa", 78); technologies, as described in
our privacy policy, for purposes
scores.put("Dino", that may include site operation, analytics,
65);
enhanced user experience, or advertising. You may choose to consent to
our useSystem.out.println(scores);
of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 21/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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. How do you remove all occurrences of a given

character from an input string in Java?

The String class doesn’t have a method to remove characters. The following example code
shows how to use the replace() method to create a new string without the given character:

Copy

String str1 = "abcdABCDabcdABCD";

This str1 = str1.replace("a",


site uses cookies and related"");
technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
System.out.println(str1);
enhanced // bcdABCDbcdABCD
user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 22/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

String is immutable in Java. All the string manipulation methods return a new string, which
is why you need to assign it to another variable. Learn more about removing characters
from a string in Java.

26. How do you get distinct characters and their count

in a string in Java?

You 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. The following example code shows how
to extract and count the characters of a string:

Copy

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. Can you prove that a String object in Java is

immutable programmatically?

The following example code shows how to prove that a String object is immutable and the
comments in the code explain each step:

Copy
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
String s1 = "Java"; // "Java" String created in pool and reference assigned to s1
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
String s2 = s1; //s2 also has the same reference to "Java" in the pool
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 23/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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

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

//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 Stri

28. Can you write some code to showcase inheritance in

Java?
 

The following example code shows how to use the extends keyword to create a subclass of
the class Animal . The new class Cat inherits the variable from the Animal class and adds
more code that only belongs to the Cat class.

Copy

class Animal {
String color;
}

class Cat extends Animal {


void meow() {
System.out.println("Meow");
}
}

29. How do you show a diamond problem with multiple


This site uses cookies and
inheritance inrelated
Java? technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
The
our usediamond problem occurs
of these technologies, when your
or manage a class
owninherits fromPlease
preferences. multiple classes and ambiguity
occurs when it’s unclear which method to execute from which class. Java doesn’t allow
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 24/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

extending multiple classes to avoid the diamond problem illustrated by the following
example:

Copy

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();
}
}

30. How do you illustrate a try catch example in Java?

The following example code shows an example of try-catch:

Copy

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

From Java 7 onwards, you can also catch multiple exceptions in a single catch block, as
shown in the following example. It’s useful when you have the same code in all the catch
blocks.
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information. Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 25/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

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 Java program to show a

NullPointerException

If you are calling a function on null , it will throw a NullPointerException , as shown in the
following example code:

Copy

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.NullPoint
}
}

 

You should have null check in place for early validation, as shown in the following example
code:

This site uses cookies and related technologies, as described in Copy


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
static void printString(String s, int count) {
our use of these technologies, or manage your own preferences. Please
if (s == null) return;
visit our cookie policy for more information.
for (int i = 0; i < count; i++) {
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 26/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

System.out.println(s.toUpperCase());
}
}

You can also throw IllegalArgumentException based on the project requirements.

32. How do you create a record in Java?

Records was added as a standard feature in Java 16. Records enable you to create a POJO
class with minimal code. Records automatically generates hashCode() , equals() , getter
methods, and toString() method code for the class. Records are final and implicitly extend
the java.lang.Record class. The following example code shows one way to cerate a record:

Copy

import java.util.Map;

public record EmpRecord(int id, String name, long salary, Map<String, String> addresses)
}

 

Learn more about records in Java. For details about POJO, refer to Plain old Java object on
Wikipedia.

33. How do you create text blocks in Java?

Java 15 added the text blocks feature. You can create multiline strings using text blocks.
The multiline string has to be written inside of a pair of triple-double quotes, as shown in
the following example:

Copy

String textBlock = """


Hi
Hello
This site uses cookies and related technologies, as described in
Yes""";
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
It’suse
our theofsame
theseas creating aorstring,
technologies, such
manage youras
own .
preferences. Please
Hi\\nHello\\nYes
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 27/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

34. Show an example of switch expressions and multi-

label case statements in Java

The switch expressions were added as a standard feature in Java 14. The following
examples show switch expressions as well as multi-label case statements:

Copy

int choice = 2;

int x = switch (choice) {


case 1, 2, 3:
yield choice;
default:
yield -1;
};

System.out.println("x = " + x); // x = 2

You can also use lambda expressions in switch expressions.

Copy

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

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
35. How
enhanced do youorcompile
user experience, advertising. Youand runtoaconsent
may choose Java to class from the
our use of these technologies, or manage your own preferences. Please
command line?
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 28/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

This example refers to the following Java file:

Copy

public class Test {

public static void main(String args[]) {


System.out.println("Hi");
}

You can compile it using the following command in your terminal:

Copy

$ javac Test.java

To run the class, use the following command in your terminal:

Copy

$ java Test

For the recent releases, the java command will also compile the program if the class file is
not present. If the class is in a package, such as com.example , then it should be inside the
folder com/example . The command to compile and run is:

Copy

$ java com/example/Test.java

If your class requires some additional JARs to compile and run, you can use the java -cp
option.
This For example:
site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information. Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 29/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

$ java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar com/example/Test.jav

 

36. How do you create an enum in Java?

The following example code shows how to create a basic enum:

Copy

public enum ThreadStates {


START,
RUNNING,
WAITING,
DEAD;
}

ThreadStates is the enum with fixed constants fields START , RUNNING , WAITING , and DEAD . All
enums implicitly extend the java.lang.Enum class and implement the Serializable and
Comparable interfaces. Enum can have methods also. Learn more about enums in Java.

37. How do you use the forEach() method in Java?

The forEach() method provides a shortcut to perform an action on all the elements of an
iterable. The following example code shows how to iterate over the list elements and print
them:

Copy

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

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

while (it.hasNext()) {
System.out.println(it.next());
This }site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
You
our can
use use the
of these forEach()ormethod
technologies, managewith
your a lambda
own expression
preferences. Pleaseto reduce the code size, as
shown
visit in thepolicy
our cookie following example
for more code:
information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 30/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Copy

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

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

38. How do you write an interface with default and

static method?

Java 8 introduced default and static methods in interfaces. This bridged the gap between
interfaces and abstract classes. The following example code shows one way to write an
interface with the default and static method:

Copy

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;


}

Learn more about about default and static methods in interfaces in Java 8 interface
changes.

39.
This siteHow do you
uses cookies create
and related a functional
technologies, as described in interface?
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience,
An interface with exactlyor one
advertising. You
abstract may choose
method to consent
is called to
a functional interface. The major
our use of these technologies, or manage your own preferences. Please
benefit of functional interfaces is that you can use lambda expressions to instantiate them
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 31/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

and avoid using bulky anonymous class implementation. The @FunctionalInterface


annotation indicates a functional interface, as shown in the following example code:

Copy

@FunctionalInterface
interface Foo {
void test();
}

40. Show an example of using lambda expressions in

Java

Runnable is an excellent example of a functional interface. You can use lambda expressions
to create a runnable, as shown in the following example code:

Copy

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

41. Show examples of overloading and overriding in

Java

When a class has two or more methods with the same name, they are called overloaded
methods. The following example code shows as overloaded method called print :

Copy

class Foo {
void print(String s) {
System.out.println(s);
}
This site uses cookies and related technologies, as described in
void print(String s, int count) {
our privacy policy, for purposes that may include site operation, analytics,
while (count > 0) {
enhanced user experience, or advertising. You may choose to consent to
System.out.println(s);
our use of these technologies, or manage your own preferences. Please
count--;
visit our cookie policy for more information.
}
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 32/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

When a superclass method is also implemented in the child class, it’s called overriding. The
following example code shows how to annotate the printname() method that’s implemented
in both classes:

Copy

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

class Child extends Base {


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

Learn more about overriding and overloading in Java.

42.-49. Guess the Output

Test yourself by guessing the output of the following code snippets.

Copy

String s1 = "abc";
String s2 = "abc";

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

This site uses cookies and related technologies, as described in


our Output
privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 33/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

String s3 = "JournalDev";
int start = 1;
char end = 5;

System.out.println(s3.substring(start, end));

Output

Copy

HashSet shortSet = new HashSet();

for (short i = 0; i < 100; i++) {


shortSet.add(i);
shortSet.remove(i - 1);
}

System.out.println(shortSet.size());

Output

Copy

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

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
Outputuser experience, or advertising. You may choose to consent to
enhanced
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 34/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Copy

String str = null;


String str1="abc";

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

Output

Copy

String x = "abc";
String y = "abc";

x.concat(y);

System.out.print(x);

Output

Copy

public class MathTest {

public void main(String[] args) {


int x = 10 * 10 - 10;

System.out.println(x);
}

Output
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information. Copy
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 35/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

public class Test {

public static void main(String[] args) {


try {
throw new IOException("Hello");
} catch(IOException | Exception e) {
System.out.println(e.getMessage());
}
}
}

Output

50. Find 5 mistakes in the following code snippet

Copy

package com.digitalocean.programming-interviews;

public class String Programs {

static void main(String[10] args) {


String s = "abc"
System.out.println(s);
}
}

Answers

Bonus Questions

Clear comparison between collections vs streams

questions
This site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
Collections
enhanced userand streamsorare
experience, two fundamental
advertising. concepts
You may choose in Java
to consent to that serve different
purposes
our in handling
use of these data.orHere’s
technologies, managea clear comparison
your own between
preferences. Please them:
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 36/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Collections:
A collection is a group of objects that can be manipulated as a single unit.
It is a static data structure that stores elements and provides methods to access,
modify, and manipulate them.
Examples of collections include List, Set, Map, and Queue.
Collections are suitable for scenarios where data needs to be stored and manipulated
in a structured way.

Streams:
A stream is a sequence of elements that can be processed in a pipeline fashion.
It is a dynamic data structure that allows for the creation of a pipeline of operations to
process elements.
Streams are designed for parallel processing and are particularly useful for handling
large datasets.
Streams are suitable for scenarios where data needs to be processed in a more
functional programming style.

Key differences:
Storage: Collections store elements, while streams do not store elements but rather
process them on the fly.
Processing: Collections are processed sequentially, whereas streams can be
processed in parallel.
Lazy vs Eager: Streams are lazy, meaning operations are executed only when the
terminal operation is invoked. Collections are eager, meaning all operations are
executed immediately.

Add Java multithreading and concurrency coding

challenges

Here are some Java multithreading and concurrency coding challenges to help you
practice and improve your skills:
Challenge 1: Implement a thread-safe singleton class.
Challenge 2: Write a program to demonstrate the use of synchronized blocks to achieve
thread
This safety.
site uses cookies and related technologies, as described in
our privacy policy, for purposes that may include site operation, analytics,
enhanced
Challenge user
3:experience,
Implementoraadvertising. You may choose
producer-consumer to consent
problem usingtowait() and notify() methods.
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
Challenge 4: Use Java’s ExecutorService to execute a list of tasks concurrently.
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 37/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Challenge 5: Implement a thread-safe cache using ConcurrentHashMap.


Challenge 6: Write a program to demonstrate the use of atomic variables for thread-safe
operations.
Challenge 7: Implement a deadlock scenario and explain how to avoid it.
Challenge 8: Use Java’s Lock interface to implement a custom lock for thread
synchronization.
Challenge 9: Implement a thread-safe queue using BlockingQueue.
Challenge 10: Write a program to demonstrate the use of CompletableFuture for
asynchronous programming.
These challenges cover various aspects of Java multithreading and concurrency, including
thread safety, synchronization, and asynchronous programming.

FAQs

1. What Java topics should I study for interviews?

For Java interviews, it’s essential to have a solid grasp of the following topics:
Core Java: OOP concepts, data types, operators, control structures, methods, and
exception handling.
Java Collections Framework: Lists, Sets, Maps, and Queues.
Multithreading and Concurrency: Thread creation, synchronization, and concurrent
collections.
Java Standard Library: Familiarity with classes like String, StringBuilder, and Arrays.
Java Best Practices: Code organization, naming conventions, and coding standards.

2. How do I prepare for Java technical interviews?

To prepare for Java technical interviews, follow these steps:


Review the basics: Brush up on core Java concepts, data structures, and algorithms.
Practice coding: Solve problems on platforms like LeetCode, HackerRank, or
CodeWars.
Focus
This site on common
uses cookies interview
and related topics: Study
technologies, multithreading,
as described in concurrency, and Java-
specific
our privacy topics
policy, like serialization
for purposes and reflection.
that may include site operation, analytics,
enhancedPrepare to answer behavioral questions:choose
user experience, or advertising. You may Be ready to discuss
to consent to your past projects,
our usedesign
of thesedecisions,
technologies, or manage your own preferences.
and problem-solving approaches. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 38/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Practice whiteboarding: Practice explaining technical concepts and designing systems


on a whiteboard.

3. What Java version should I focus on for interviews?

For Java interviews, it’s recommended to focus on Java 8 and its features, such as lambda
expressions, functional programming, and the new Date and Time API. However, having
knowledge of Java 11 and its improvements is also beneficial.

4. How important is multithreading in Java interviews?

Multithreading is a crucial topic in Java interviews, as it’s a key aspect of Java


programming. You should be prepared to answer questions on thread creation,
synchronization, deadlocks, and concurrent collections. Multithreading concepts are often
used to evaluate a candidate’s ability to write efficient, scalable, and thread-safe code.
5. What are some good Java coding problems for practice?

Here are some popular Java coding problems for practice:


Reverse a string or an array
Find the middle element of a linked list
Implement a stack using two queues
Find the first duplicate in an array
Implement a binary search tree
Solve the producer-consumer problem using multithreading
Implement a cache using a HashMap
Find the maximum sum of a subarray

Practice these problems to improve your coding skills and prepare for common interview
questions.

Conclusion

This collection of 50 Java programming interview questions included questions from


beginner to expert level, to help you prepare for your interview. For further learning and
practice, we recommend checking out the following tutorials:
This site uses cookies and related technologies, as described in
How to Write Your First Program in Java
our privacy policy, for purposes that may include site operation, analytics,
enhanced How toexperience,
user Use Operators in Java You may choose to consent to
or advertising.
our useJava Generics
of these Example:
technologies, Method,
or manage yourClass, Interface Please
own preferences.
visit ourConstructor
cookie policyin
forJava
more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 39/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

These resources will help you solidify your understanding of Java fundamentals and
prepare you for more advanced topics in Java programming.
Also Read:
Java Tricky Interview Questions
Java String Interview Questions

Thanks for learning with the DigitalOcean Community. Check out our offerings for
compute, storage, networking, and managed databases.
Learn more about our products ->

About the author(s)

Pankaj Kumar

See author profile

Category: Tutorial

Tags: Interview Questions Java

Still looking for an answer? Ask a question

Search for more help

This site uses cookies and related technologies, as described in


Waspolicy,
our privacy this for
helpful? Yesinclude siteNo
purposes that may operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 40/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Comments

JournalDev • March 29, 2011


Really confusing for those who don’t pay attention to the language syntax and
semantics.
- Sandeep

JournalDev • May 27, 2011


Q1 For me the interesting thing is not operator precedence but string comparison.
So explicitly bracket the == in the last line: System.out.println("s1 == s2 is: " + (s1
== s2)); and it will return: s1 == s2 is: true But replace String s2 = “abc”; with
String s2 = “ab”; s2 = s2 + “c”; and it will return s1 == s2 is: false This is because
Java optimizes by giving the strings it knows at compile time the same hash code,
but is doesn’t know what s2 is at compile time - so the second “abc” string gets a
different hash code.
- Adrian Redgers

Show replies

JournalDev • June 8, 2011


Test Question 4: “In Finally” will be reached if flag is null. Console:
=================== In Finally Exception in thread “main”
java.lang.NullPointerException at people.oleg.test.Test1.main(Test1.java:51)
=================== public class Test1 { public static void main(String[]
args) { Boolean flag = null; try { if (flag) { while (true) { } } else { System.exit(1); } }
finally
This site uses {cookies
System.out.println(“In Finally”);
and related technologies, } } } Exception
as described in in thread “main”
our privacy policy, for purposes that may include site operation, analytics,
java.lang.NullPointerException at people.oleg.test.Test1.main(Test1.java:51) In
enhanced user experience, or advertising. You may choose to consent to
our useFinally
of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.
- oleg
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 41/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Show replies

JournalDev • June 25, 2011


Thanks for these questions they are really tricky. I want more questions like these
please help me from where I can get them any site or link will be helpful. Thanks in
Advance.
- Ankit Jain

JournalDev • July 29, 2011


String s1 = “abc”; String s2 = “abc”; System.out.println(“s1 == s2 is:” + s1 == s2);
the output for s1==s2 is false because if you use == it always meant for reference
comparison only if you use s1.equals(s2) it gives true because .equals() method is
always meant for content comparison String s3 = “JournalDev”; int start = 1; char
end = 5; System.out.println(start + end); System.out.println(s3.substring(start,
end)); here output is 6 ourn because start+end in this start is int and end is char in
this it selects max datatype coverts all into that type(widowning) if use
string+something then it always converts into string type only.
- sreenivas

Show replies

JournalDev • January 23, 2013


This is a very great share. I must appreciate! My score is: 2/5. I got Q.2 and Q.4
right, rest I could not make out. Thanks a lot for sharing.
- Rishi
This site Raj and related technologies, as described in
uses cookies
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
Show replies
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 42/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

JournalDev • April 26, 2013


Cool…
- Rishika

JournalDev • July 26, 2013


Really nice set of questions. Thanks.
- Yogesh

JournalDev • December 11, 2013


I need more questions on strings like this… tq
- TIM

JournalDev • April 16, 2014


Excellent Set of Questions :)
- Pawan Soni

Load more comments

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our useThis worktechnologies,
of these is licensed under a Creative
or manage yourCommons Attribution-NonCommercial-
own preferences. Please ShareAlike 4.0
visit our cookie policy for more information.International License.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 43/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Popular Topics

AI/ML
Ubuntu
Linux Basics
JavaScript
Python
MySQL
Docker
Kubernetes

Connect on Discord
Join the conversation in our Discord to connect with fellow developers

Visit Discord

All tutorials ->

This site uses cookies and related technologies, as described in


Talk to an expert ->
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 44/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a
matching donation.

Sign Up

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 45/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Learn more

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 46/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising
funding to marketing your product.

Learn more

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

Email address Submit

New accounts only. By submitting your email you agree to our Privacy Policy

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 47/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

The developer cloud


Scale up as you grow — whether you're running one
virtual machine or ten thousand.

View all products

Get started for free


Sign up and get $200 in credit for your first 60 days
with DigitalOcean.*

This site uses cookies and related technologies,Get started in


as described
our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 48/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

*This promotional offer applies to new accounts only.

Company

Products

Resources

Solutions

Contact

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
© 2025 DigitalOcean, LLC. Sitemap. Cookie
enhanced user experience, or advertising. You may choose to consent to Preferences
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 49/50
30/05/2025, 23:08 Top Java Coding Interview Questions (With Answers) | DigitalOcean

This site uses cookies and related technologies, as described in


our privacy policy, for purposes that may include site operation, analytics,
enhanced user experience, or advertising. You may choose to consent to
our use of these technologies, or manage your own preferences. Please
visit our cookie policy for more information.

https://www.digitalocean.com/community/tutorials/java-programming-interview-questions 50/50

You might also like