Java Programming Questions for Technical Interviews
Preparing for a Java technical interview requires more than memorizing definitions. Interviewers often ask candidates to write code, analyze output, solve programming problems and explain their approach.
For freshers and junior developers, these programming questions are designed to test your understanding of Core Java, Object-Oriented Programming, strings, arrays, collections, exception handling, Java 8 features and basic problem-solving.
In this guide, we'll cover practical Java programming questions that can help you prepare for technical interviews.
Table of Contents
- Reverse a String
- Check if a String Is a Palindrome
- Find Duplicate Characters
- Count Character Occurrences
- Check Anagrams
- Reverse an Integer
- Check Prime Number
- Generate Fibonacci Series
- Find Factorial
- Find Largest Element in an Array
- Find Second Largest Element
- Find Smallest Element
- Find Duplicate Numbers
- Sort an Array
- Find Missing Number
- Find Even and Odd Numbers
- Remove Duplicates
- Find Common Elements
- Count Words
- Swap Two Numbers
- Check Armstrong Number
- Sum of Digits
- Find Frequency of Elements
- Reverse an Array
- Find Maximum and Minimum
- Check Leap Year
- Find Vowels
- Remove Spaces
- Count Digits
- Check Perfect Number
- HashMap-Based Problems
- ArrayList Problems
- Stream API Problems
- OOP Programming Problems
- Exception Handling Problems
- Interview Tips
1. How Do You Reverse a String in Java?
Question
Write a Java program to reverse a string without using a built-in reverse method.
Solution
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println(reversed);
}
}
Output
avaJ
Interview Tip
The interviewer may ask you to implement the same solution using StringBuilder.
String reversed = new StringBuilder(str)
.reverse()
.toString();
2. How Do You Check Whether a String Is a Palindrome?
A palindrome reads the same forward and backward.
Examples:
madam
level
racecar
Solution
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str)
.reverse()
.toString();
if (str.equals(reversed)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
}
3. How Do You Find Duplicate Characters in a String?
import java.util.HashMap;
import java.util.Map;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> count = new HashMap<>();
for (char ch : str.toCharArray()) {
count.put(ch, count.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : count.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(
entry.getKey() + " = " + entry.getValue()
);
}
}
}
}
This tests your understanding of HashMap and character frequency counting.
4. How Do You Count the Occurrence of Each Character?
A common technical interview problem is to determine how many times each character appears.
String str = "java";
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
System.out.println(map);
Possible output:
{j=1, a=2, v=1}
5. How Do You Check Whether Two Strings Are Anagrams?
Two strings are anagrams if they contain the same characters with the same frequencies.
For example:
listen
silent
Solution
import java.util.Arrays;
public class Anagram {
public static void main(String[] args) {
String first = "listen";
String second = "silent";
char[] a = first.toCharArray();
char[] b = second.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
if (Arrays.equals(a, b)) {
System.out.println("Anagram");
} else {
System.out.println("Not an anagram");
}
}
}
6. How Do You Reverse an Integer?
Example
Input: 12345
Output: 54321
int number = 12345;
int reverse = 0;
while (number != 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
System.out.println(reverse);
7. How Do You Check Whether a Number Is Prime?
A prime number has exactly two positive divisors: 1 and itself.
int number = 29;
boolean prime = true;
if (number < 2) {
prime = false;
}
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
prime = false;
break;
}
}
System.out.println(prime ? "Prime" : "Not Prime");
8. How Do You Generate the Fibonacci Series?
The Fibonacci sequence starts with:
0, 1, 1, 2, 3, 5, 8, 13...
Java Program
int n = 10;
int first = 0;
int second = 1;
for (int i = 0; i < n; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
9. How Do You Find the Factorial of a Number?
The factorial of 5 is:
5 × 4 × 3 × 2 × 1 = 120
Solution
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(factorial);
10. How Do You Find the Largest Element in an Array?
int[] numbers = {10, 25, 7, 42, 18};
int largest = numbers[0];
for (int number : numbers) {
if (number > largest) {
largest = number;
}
}
System.out.println(largest);
Output:
42
11. How Do You Find the Second Largest Number?
int[] numbers = {10, 25, 7, 42, 18};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int number : numbers) {
if (number > largest) {
secondLargest = largest;
largest = number;
} else if (number > secondLargest && number != largest) {
secondLargest = number;
}
}
System.out.println(secondLargest);
This is a popular interview problem because it tests your ability to track multiple values efficiently.
12. How Do You Find Duplicate Numbers in an Array?
int[] numbers = {1, 2, 3, 2, 4, 5, 1};
Set<Integer> seen = new HashSet<>();
for (int number : numbers) {
if (!seen.add(number)) {
System.out.println("Duplicate: " + number);
}
}
This tests your understanding of the Set collection.
13. How Do You Remove Duplicates From an Array?
int[] numbers = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> unique = new LinkedHashSet<>();
for (int number : numbers) {
unique.add(number);
}
System.out.println(unique);
LinkedHashSet preserves insertion order.
14. How Do You Find the Missing Number in an Array?
Suppose the array contains:
1, 2, 3, 5
The missing number is 4.
One approach is:
int[] numbers = {1, 2, 3, 5};
int n = 5;
int expected = n * (n + 1) / 2;
int actual = 0;
for (int number : numbers) {
actual += number;
}
System.out.println(expected - actual);
15. How Do You Find Even and Odd Numbers?
int[] numbers = {1, 2, 3, 4, 5, 6};
for (int number : numbers) {
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
}
16. How Do You Reverse an Array?
int[] numbers = {1, 2, 3, 4, 5};
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
left++;
right--;
}
This approach reverses the array in place.
17. How Do You Find Common Elements Between Two Arrays?
int[] first = {1, 2, 3, 4};
int[] second = {3, 4, 5, 6};
Set<Integer> set = new HashSet<>();
for (int number : first) {
set.add(number);
}
for (int number : second) {
if (set.contains(number)) {
System.out.println(number);
}
}
18. How Do You Count Words in a String?
String sentence = "Java is a powerful programming language";
String[] words = sentence.trim().split("\\s+");
System.out.println("Word count: " + words.length);
Output:
Word count: 6
19. How Do You Swap Two Numbers Without a Third Variable?
One arithmetic approach is:
int a = 10;
int b = 20;
a = a + b;
b = a - b;
a = a - b;
System.out.println(a);
System.out.println(b);
However, in production code, clarity is generally more important than avoiding a temporary variable.
20. How Do You Check an Armstrong Number?
An Armstrong number is a number equal to the sum of its digits raised to the number of digits.
For example:
153 = 1³ + 5³ + 3³
Solution
int number = 153;
int original = number;
int digits = String.valueOf(number).length();
int sum = 0;
while (number != 0) {
int digit = number % 10;
sum += Math.pow(digit, digits);
number /= 10;
}
if (sum == original) {
System.out.println("Armstrong number");
} else {
System.out.println("Not an Armstrong number");
}
21. How Do You Calculate the Sum of Digits?
int number = 12345;
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
System.out.println(sum);
Output:
15
22. How Do You Find the Frequency of Elements in an Array?
int[] numbers = {1, 2, 2, 3, 3, 3};
Map<Integer, Integer> frequency = new HashMap<>();
for (int number : numbers) {
frequency.put(
number,
frequency.getOrDefault(number, 0) + 1
);
}
System.out.println(frequency);
Output:
{1=1, 2=2, 3=3}
23. How Do You Find the Maximum and Minimum Values?
int[] numbers = {10, 5, 25, 3, 40};
int min = numbers[0];
int max = numbers[0];
for (int number : numbers) {
if (number < min) {
min = number;
}
if (number > max) {
max = number;
}
}
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
24. How Do You Check Whether a Year Is a Leap Year?
int year = 2028;
boolean leapYear =
(year % 400 == 0) ||
(year % 4 == 0 && year % 100 != 0);
System.out.println(leapYear ? "Leap Year" : "Not a Leap Year");
25. How Do You Count Vowels in a String?
String str = "Java Programming";
int count = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u') {
count++;
}
}
System.out.println("Vowels: " + count);
26. How Do You Remove Spaces From a String?
String str = "Java Programming Language";
String result = str.replaceAll("\\s+", "");
System.out.println(result);
Output:
JavaProgrammingLanguage
27. How Do You Count Digits in a Number?
int number = 123456;
int count = String.valueOf(Math.abs(number)).length();
System.out.println(count);
Output:
6
28. How Do You Check Whether a Number Is a Perfect Number?
A perfect number is equal to the sum of its proper positive divisors.
For example:
6 = 1 + 2 + 3
Java Program
int number = 6;
int sum = 0;
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
if (sum == number) {
System.out.println("Perfect number");
} else {
System.out.println("Not a perfect number");
}
Java Collection-Based Programming Questions
Technical interviews frequently combine programming problems with Java collections.
29. How Do You Find the First Non-Repeated Character?
String str = "swiss";
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
break;
}
}
Output:
w
The use of LinkedHashMap preserves insertion order.
30. How Do You Sort a List of Integers?
List<Integer> numbers =
new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3));
Collections.sort(numbers);
System.out.println(numbers);
Output:
[1, 2, 3, 5, 8]
31. How Do You Sort a List Using Java Streams?
List<Integer> numbers =
Arrays.asList(5, 2, 8, 1, 3);
List<Integer> sorted =
numbers.stream()
.sorted()
.toList();
System.out.println(sorted);
This tests your understanding of the Stream API.
32. How Do You Find Even Numbers Using Streams?
List<Integer> numbers =
Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers =
numbers.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(evenNumbers);
Output:
[2, 4, 6]
33. How Do You Find the Maximum Number Using Streams?
List<Integer> numbers =
Arrays.asList(10, 20, 5, 40, 15);
int max = numbers.stream()
.max(Integer::compareTo)
.orElseThrow();
System.out.println(max);
Output:
40
34. How Do You Convert a List of Strings to Uppercase?
List<String> names =
Arrays.asList("java", "spring", "sql");
List<String> result =
names.stream()
.map(String::toUpperCase)
.toList();
System.out.println(result);
Output:
[JAVA, SPRING, SQL]
Object-Oriented Programming Questions
Java technical interviews often include programming problems based on OOP.
35. Create a Simple Student Class
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println(name + " - " + age);
}
}
This demonstrates:
- Class
- Object
- Constructor
- Encapsulation
36. Demonstrate Inheritance
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
Here, Dog inherits behavior from Animal.
37. Demonstrate Method Overriding
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
This demonstrates runtime polymorphism.
38. Demonstrate Method Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
This is compile-time polymorphism.
Exception Handling Programming Questions
39. How Do You Handle an Exception?
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Interviewers may ask you to explain what happens when an exception occurs and how Java's exception hierarchy works.
40. How Do You Create a Custom Exception?
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
You can then use it in application logic:
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
41. How Do You Use try-with-resources?
Try-with-resources automatically closes resources that implement AutoCloseable.
Example:
try (BufferedReader reader =
new BufferedReader(new FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
This is preferable to manually managing many close operations.
Multithreading Programming Questions
42. How Do You Create a Thread Using Runnable?
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.start();
}
}
Interviewers may ask why start() should be called instead of directly calling run().
43. What Is the Difference Between start() and run()?
Calling:
thread.start();
asks the JVM to start a new thread of execution.
Calling:
thread.run();
is simply a normal method call and does not start a new thread by itself.
This is a common fresher interview question.
44. How Do You Synchronize a Method?
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
Synchronization can help protect shared mutable state from certain race conditions.
Java Output-Based Questions
Interviewers may also show short Java programs and ask what they print.
45. What Is the Output?
String a = "Java";
String b = "Java";
System.out.println(a == b);
Output:
true
Because identical string literals can refer to the same interned String object.
However:
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
prints:
false
because the two new String() expressions create distinct objects.
46. What Is the Output?
int x = 10;
System.out.println(x++);
System.out.println(++x);
Output:
10
12
The first statement uses the current value and then increments it. The second increments before evaluating the expression.
47. What Happens Here?
String str = null;
System.out.println(str.length());
This results in a:
NullPointerException
because you're attempting to invoke a method on a null reference.
48. What Is the Output?
int a = 10;
int b = 20;
System.out.println(a + b + "Java");
Output:
30Java
But:
System.out.println("Java" + a + b);
outputs:
Java1020
This tests your understanding of Java's + operator and string concatenation.
49. What Is the Difference Between == and equals()?
Consider:
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
System.out.println(a.equals(b));
Output:
false
true
== compares references, while equals() is used for logical equality when the class implements it appropriately.
50. How Would You Approach an Unfamiliar Java Coding Problem?
This is one of the most important interview skills.
Don't immediately start writing code.
Follow a structured approach.
Step 1: Understand the problem
Read the question carefully.
Step 2: Identify the input and output
Determine exactly what the program receives and what it needs to return.
Step 3: Consider edge cases
Think about:
- Empty input
- Null values
- Duplicate values
- Negative numbers
- Very large input
- Single-element input
Step 4: Explain your approach
Before coding, briefly explain the algorithm to the interviewer.
Step 5: Write the code
Keep the implementation readable.
Step 6: Test it
Walk through your code using an example.
Step 7: Discuss complexity
Explain:
Time Complexity
and
Space Complexity
when relevant.
How to Prepare for Java Programming Interviews
Solving 50 problems once isn't enough.
The goal is to develop problem-solving ability.
A good preparation strategy is:
Practice Strings
Work on:
- Reverse string
- Palindrome
- Anagram
- Character frequency
- Duplicate characters
- First non-repeated character
Practice Arrays
Work on:
- Largest element
- Second largest
- Missing number
- Duplicate elements
- Sorting
- Array reversal
- Common elements
Practice Collections
Understand:
- ArrayList
- LinkedList
- HashSet
- TreeSet
- HashMap
- LinkedHashMap
Practice Java 8+
Learn:
- Lambda expressions
- Streams
- Functional interfaces
- Optional
- Method references
Practice OOP
Be able to implement:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
- Interfaces
How to Answer Coding Questions in a Technical Interview
When an interviewer gives you a coding problem, don't remain silent while coding.
Explain your thinking.
For example:
"I'll first store the elements I've already seen in a HashSet. While iterating through the array, if the element already exists in the set, I'll consider it a duplicate."
Then write the code.
This allows the interviewer to evaluate your problem-solving approach, even if your first implementation isn't perfect.
Common Mistakes to Avoid
1. Jumping Directly Into Code
Understand the problem first.
2. Ignoring Edge Cases
Always consider unusual or boundary inputs.
3. Using Complex Code for Simple Problems
Prefer readable solutions.
4. Not Explaining Your Approach
Interviewers want to understand how you think.
5. Forgetting Complexity
Know the basic time and space complexity of your solution.
6. Memorizing Solutions
Practice writing solutions from scratch.
7. Not Testing Your Code
Run through at least one example manually.
