[Go to site: main page, start]

0% found this document useful (0 votes)
47 views28 pages

Intermediate Java Interview Questions

This document contains a collection of intermediate Java interview practice questions and solutions, covering various topics such as string manipulation, array operations, and algorithmic challenges. Each question includes a brief description of the logic and a code example demonstrating the solution. The document serves as a resource for candidates preparing for Java programming interviews.

Uploaded by

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

Intermediate Java Interview Questions

This document contains a collection of intermediate Java interview practice questions and solutions, covering various topics such as string manipulation, array operations, and algorithmic challenges. Each question includes a brief description of the logic and a code example demonstrating the solution. The document serves as a resource for candidates preparing for Java programming interviews.

Uploaded by

Aditya Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🔥 Level: Intermediate Java Interview Practice

Questions
✅ 1. Reverse a String (Without using built-in reverse)

public class ReverseString {


public static void main(String[] args) {
String input = "interview";
String reversed = "";
for (int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);
}
[Link]("Reversed: " + reversed);
}
}
🔸 Interview Use: String manipulation, loop understanding.

✅ 2. Check if String is Palindrome

public class PalindromeCheck {


public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
[Link]([Link](rev) ? "Palindrome" : "Not Palindrome");
}
}
✅ 3. Find Duplicate Characters in a String

import [Link];
import [Link];

public class DuplicateCharacters {


public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> countMap = new HashMap<>();

for (char c : [Link]()) {


[Link](c, [Link](c, 0) + 1);
}

for ([Link]<Character, Integer> entry : [Link]()) {


if ([Link]() > 1)
[Link]([Link]() + " : " + [Link]());
}
}
}

✅ 4. Find Maximum & Minimum in an Array

public class MaxMinArray {


public static void main(String[] args) {
int[] arr = {2, 5, 1, 9, 3};
int max = arr[0], min = arr[0];

for (int num : arr) {


if (num > max) max = num;
if (num < min) min = num;
}

[Link]("Max: " + max + ", Min: " + min);


}
}

✅ 5. Count Occurrence of Each Word in a Sentence

import [Link].*;

public class WordFrequency {


public static void main(String[] args) {
String sentence = "Java is is platform independent";
String[] words = [Link](" ");
Map<String, Integer> wordCount = new HashMap<>();

for (String word : words) {


[Link](word, [Link](word, 0) + 1);
}

[Link](wordCount);
}
}

✅ 6. Fibonacci Series (Without Recursion)

public class FibonacciSeries {


public static void main(String[] args) {
int a = 0, b = 1, n = 10;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
[Link](" " + next);
a = b;
b = next;
}
}
}

✅ 7. Factorial Using Recursion

public class FactorialRec {


static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
[Link]("Factorial of 5: " + factorial(5));
}
}

✅ 8. Swap Two Numbers Without Third Variable

public class SwapNumbers {


public static void main(String[] args) {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
[Link]("a: " + a + ", b: " + b);
}
}

✅ 9. Check Prime Number

public class PrimeCheck {


public static void main(String[] args) {
int num = 13, count = 0;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
count++;
break;
}
}
[Link](count == 0 ? "Prime" : "Not Prime");
}
}

✅ 10. Remove Duplicates from ArrayList

import [Link].*;

public class RemoveDuplicates {


public static void main(String[] args) {
List<String> names = [Link]("Rahul", "Ajay", "Rahul", "Vijay", "Ajay");
Set<String> uniqueNames = new LinkedHashSet<>(names);
[Link]("Unique Names: " + uniqueNames);
}
}
🔥 Level: Intermediate Java Interview Practice
Questions

✅ 11. Count vowels and consonants in a string

public class VowelConsonant {


public static void main(String[] args) {
String input = "Automation";
input = [Link]();
int vowels = 0, consonants = 0;

for (char c : [Link]()) {


if ([Link](c)) {
if ("aeiou".indexOf(c) != -1)
vowels++;
else
consonants++;
}
}

[Link]("Vowels: " + vowels + ", Consonants: " + consonants);


}
}

✅ 12. Anagram Check (e.g., "listen" and "silent")

import [Link];

public class AnagramCheck {


public static void main(String[] args) {
String str1 = "listen", str2 = "silent";
char[] a1 = [Link]();
char[] a2 = [Link]();
[Link](a1);
[Link](a2);
[Link]([Link](a1, a2) ? "Anagram" : "Not Anagram");
}
}

✅ 13. Print Only Duplicate Elements from Array

import [Link].*;

public class PrintDuplicates {


public static void main(String[] args) {
int[] arr = {1, 5, 2, 1, 7, 5, 3, 2};
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();

for (int num : arr) {


if (![Link](num)) {
[Link](num);
}
}

[Link]("Duplicates: " + duplicates);


}
}
✅ 14. Sort Array Without Built-in Function

public class BubbleSort {


public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
int n = [Link];

for (int i = 0; i < n - 1; i++)


for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}

for (int num : arr)


[Link](num + " ");
}
}

✅ 15. Find Second Largest Element in Array

public class SecondLargest {


public static void main(String[] args) {
int[] arr = {10, 20, 25, 63, 96, 57};
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int num : arr) {


if (num > max) {
second = max;
max = num;
} else if (num > second && num != max) {
second = num;
}
}

[Link]("Second largest: " + second);


}
}

✅ 16. Remove All Whitespaces from String (without


using replaceAll)
java

public class RemoveSpaces {


public static void main(String[] args) {
String input = " Java Interview Prep ";
StringBuilder result = new StringBuilder();

for (char c : [Link]()) {


if (c != ' ') {
[Link](c);
}
}

[Link]("Without spaces: " + [Link]());


}
}

✅ 17. Find Missing Number in Array (1 to n)


public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6}; // missing 3
int n = 6; // including missing number
int total = n * (n + 1) / 2;

int sum = 0;
for (int num : arr)
sum += num;

[Link]("Missing Number: " + (total - sum));


}
}

✅ 18. Print Pattern (Right Angle Triangle)

public class PatternTriangle {


public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++)
[Link]("* ");
[Link]();
}
}
}

✅ 19. Reverse Words in a Sentence

public class ReverseWords {


public static void main(String[] args) {
String sentence = "Java is awesome";
String[] words = [Link](" ");
StringBuilder reversed = new StringBuilder();

for (int i = [Link] - 1; i >= 0; i--)


[Link](words[i]).append(" ");

[Link]("Reversed Words: " + [Link]().trim());


}
}

✅ 20. Count frequency of each digit in a number

import [Link];
import [Link];

public class DigitFrequency {


public static void main(String[] args) {
int number = 112345123;
String str = [Link](number);
Map<Character, Integer> map = new HashMap<>();

for (char c : [Link]()) {


[Link](c, [Link](c, 0) + 1);
}

[Link](map);
}
}
Arrays
✅ 1. Merge Two Arrays (Unsorted + Simple Merge)
🔹 Logic:
Just copy all elements of both arrays into a new array.

import [Link];

public class MergeArrays {


public static void main(String[] args) {
int[] arr1 = {10, 20, 30};
int[] arr2 = {40, 50};

int[] merged = new int[[Link] + [Link]];

// Copy elements of arr1


for (int i = 0; i < [Link]; i++) {
merged[i] = arr1[i];
}

// Copy elements of arr2


for (int i = 0; i < [Link]; i++) {
merged[[Link] + i] = arr2[i];
}

[Link]("Merged Array: " + [Link](merged));


}
}

✅ 2. Merge and Sort Two Arrays


🔹 Logic:
After merging, sort the final array using [Link]()

import [Link];

public class MergeSortArrays {


public static void main(String[] args) {
int[] arr1 = {5, 1, 9};
int[] arr2 = {2, 8, 3};

int[] merged = new int[[Link] + [Link]];

[Link](arr1, 0, merged, 0, [Link]);


[Link](arr2, 0, merged, [Link], [Link]);

[Link](merged);

[Link]("Merged & Sorted Array: " + [Link](merged));


}
}

✅ 3. Merge Two Sorted Arrays Without Using Sort


(Interview-Optimized)
🔹 Logic: Two pointer technique

import [Link];

public class MergeSortedArrays {


public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] result = new int[[Link] + [Link]];
int i = 0, j = 0, k = 0;

// Merge using two pointers


while (i < [Link] && j < [Link]) {
if (arr1[i] < arr2[j])
result[k++] = arr1[i++];
else
result[k++] = arr2[j++];
}

// Copy remaining elements


while (i < [Link])
result[k++] = arr1[i++];
while (j < [Link])
result[k++] = arr2[j++];

[Link]("Merged Sorted Array: " + [Link](result));


}
}

✅ Bonus: Merge 3 Arrays

import [Link];

public class MergeThreeArrays {


public static void main(String[] args) {
int[] a = {1, 2};
int[] b = {3, 4};
int[] c = {5, 6};
int[] merged = new int[[Link] + [Link] + [Link]];

[Link](a, 0, merged, 0, [Link]);


[Link](b, 0, merged, [Link], [Link]);
[Link](c, 0, merged, [Link] + [Link], [Link]);

[Link]("Merged Array: " + [Link](merged));


}
}

🔥 Top 10 Complex Java Coding Questions for


Interviews

✅ 1. Merge Two Sorted Arrays and Remove Duplicates


(No Sorting Allowed After Merge)

import [Link].*;

public class MergeRemoveDuplicates {


public static void main(String[] args) {
int[] a = {1, 3, 5, 7};
int[] b = {2, 3, 5, 8};

Set<Integer> set = new LinkedHashSet<>();


for (int num : a) [Link](num);
for (int num : b) [Link](num);

[Link]("Merged without Duplicates: " + set);


}
}

✅ 2. Find First Non-Repeated Character in a String

import [Link].*;

public class FirstNonRepeated {


public static void main(String[] args) {
String str = "aabccdeff";
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

for (char c : [Link]())


[Link](c, [Link](c, 0) + 1);

for ([Link]<Character, Integer> entry : [Link]()) {


if ([Link]() == 1) {
[Link]("First non-repeating: " + [Link]());
break;
}
}
}
}

✅ 3. Rotate an Array to the Right by k Steps

import [Link];

public class RotateArray {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2;
int n = [Link];

k = k % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);

[Link]("Rotated: " + [Link](arr));


}

static void reverse(int[] arr, int start, int end) {


while (start < end) {
int tmp = arr[start];
arr[start++] = arr[end];
arr[end--] = tmp;
}
}
}

✅ 4. Find Longest Substring Without Repeating


Characters

import [Link].*;

public class LongestUniqueSubstring {


public static void main(String[] args) {
String s = "abcabcbb";
Set<Character> set = new HashSet<>();
int left = 0, maxLen = 0;
for (int right = 0; right < [Link](); right++) {
while ([Link]([Link](right))) {
[Link]([Link](left++));
}
[Link]([Link](right));
maxLen = [Link](maxLen, right - left + 1);
}

[Link]("Longest unique substring length: " + maxLen);


}
}

✅ 5. Find Pairs With Given Sum in Array

import [Link].*;

public class PairSum {


public static void main(String[] args) {
int[] arr = {2, 4, 3, 5, 7, 8, 9};
int target = 10;
Set<Integer> set = new HashSet<>();

for (int num : arr) {


int diff = target - num;
if ([Link](diff)) {
[Link]("Pair: (" + num + ", " + diff + ")");
}
[Link](num);
}
}
}
✅ 6. Find Majority Element (>n/2 times)

public class MajorityElement {


public static void main(String[] args) {
int[] arr = {2, 2, 1, 2, 3, 2, 2};
int count = 0, candidate = -1;

// Boyer-Moore Voting
for (int num : arr) {
if (count == 0) candidate = num;
count += (num == candidate) ? 1 : -1;
}

// Validation
count = 0;
for (int num : arr)
if (num == candidate) count++;

[Link](count > [Link] / 2 ? "Majority: " + candidate : "No Majority");


}
}

✅ 7. Move All Zeros to End (Maintain Order)

import [Link];

public class MoveZeros {


public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
int index = 0;

for (int num : arr) {


if (num != 0)
arr[index++] = num;
}

while (index < [Link])


arr[index++] = 0;

[Link]("After Moving Zeros: " + [Link](arr));


}
}

✅ 8. Find All Duplicates in Array (No Extra Space, Range:


1 to n)

import [Link].*;

public class FindDuplicates {


public static void main(String[] args) {
int[] arr = {4, 3, 2, 7, 8, 2, 3, 1};
List<Integer> result = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {


int idx = [Link](arr[i]) - 1;
if (arr[idx] < 0)
[Link]([Link](arr[i]));
else
arr[idx] = -arr[idx];
}
[Link]("Duplicates: " + result);
}
}

✅ 9. Print All Permutations of a String

public class Permutations {


public static void main(String[] args) {
permute("", "abc");
}

static void permute(String prefix, String str) {


if ([Link]() == 0)
[Link](prefix);
else {
for (int i = 0; i < [Link](); i++) {
permute(prefix + [Link](i), [Link](0, i) + [Link](i + 1));
}
}
}
}

✅ 10. Find Missing + Repeating Number in Array (1 to n)

public class MissingRepeating {


public static void main(String[] args) {
int[] arr = {4, 3, 6, 2, 1, 1};

int n = [Link];
int sum = n * (n + 1) / 2;
int sumSq = n * (n + 1) * (2 * n + 1) / 6;

int actualSum = 0, actualSq = 0;


for (int num : arr) {
actualSum += num;
actualSq += num * num;
}

int diff = actualSum - sum; // x - y


int sqDiff = actualSq - sumSq; // x^2 - y^2 = (x - y)(x + y)

int sumXY = sqDiff / diff; // x + y

int x = (diff + sumXY) / 2;


int y = x - diff;

[Link]("Repeating: " + x);


[Link]("Missing : " + y);
}
}

🔥 Top 10 Java 8 Coding Questions for


Interviews

✅ 1. Filter Even Numbers from List using Stream

import [Link];
import [Link];
public class EvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = [Link](2, 5, 6, 7, 8, 10);

[Link]()
.filter(n -> n % 2 == 0)
.forEach([Link]::println);
}
}

✅ 2. Find First Non-Repeated Character Using Java 8

import [Link].*;
import [Link];
import [Link];

public class FirstNonRepeating {


public static void main(String[] args) {
String input = "interview";

Character result = [Link]()


.mapToObj(c -> (char) c)
.collect([Link]([Link](), LinkedHashMap::new,
[Link]()))
.entrySet().stream()
.filter(entry -> [Link]() == 1)
.map([Link]::getKey)
.findFirst()
.orElse(null);

[Link]("First non-repeating: " + result);


}
}

✅ 3. Count Frequency of Each Character in a String

import [Link].*;
import [Link];
import [Link];

public class CharFrequency {


public static void main(String[] args) {
String str = "banana";

Map<Character, Long> freq = [Link]()


.mapToObj(c -> (char) c)
.collect([Link]([Link](), [Link]()));

[Link](freq);
}
}

✅ 4. Find Max and Min in List using Stream

import [Link].*;

public class MaxMin {


public static void main(String[] args) {
List<Integer> nums = [Link](4, 10, 3, 99, 24);

int max = [Link]().max(Integer::compare).get();


int min = [Link]().min(Integer::compare).get();

[Link]("Max: " + max + ", Min: " + min);


}
}

✅ 5. Sort a List in Reverse Order using Java 8

import [Link].*;

public class ReverseSort {


public static void main(String[] args) {
List<String> names = [Link]("Rahul", "Amit", "Vikas");

[Link]()
.sorted([Link]())
.forEach([Link]::println);
}
}

✅ 6. Convert List<String> to UpperCase using Stream

import [Link];
import [Link];

public class UpperCaseConvert {


public static void main(String[] args) {
List<String> list = [Link]("apple", "banana", "grapes");

[Link]()
.map(String::toUpperCase)
.forEach([Link]::println);
}
}

✅ 7. Remove Duplicates from List Using Java 8

import [Link].*;

public class RemoveDuplicates {


public static void main(String[] args) {
List<Integer> list = [Link](1, 2, 3, 2, 4, 1, 5);

[Link]()
.distinct()
.forEach([Link]::println);
}
}

✅ 8. Convert List<String> to a Single Comma-


Separated String

import [Link];
import [Link];
import [Link];

public class JoinStrings {


public static void main(String[] args) {
List<String> list = [Link]("Java", "Spring", "Hibernate");
String result = [Link]()
.collect([Link](", "));

[Link](result); // Output: Java, Spring, Hibernate


}
}

✅ 9. Get Employees Whose Salary > 50000 (using filter)

import [Link].*;
import [Link].*;

class Employee {
String name;
int salary;

Employee(String name, int salary) {


[Link] = name;
[Link] = salary;
}
}

public class FilterEmployees {


public static void main(String[] args) {
List<Employee> employees = [Link](
new Employee("Rahul", 60000),
new Employee("Ankit", 40000),
new Employee("Vikas", 70000)
);

[Link]()
.filter(e -> [Link] > 50000)
.map(e -> [Link])
.forEach([Link]::println);
}
}

✅ 10. Optional Example: Handle Null Safely

import [Link];

public class OptionalExample {


public static void main(String[] args) {
String name = null;

// Avoid NullPointer using Optional


Optional<String> optionalName = [Link](name);

String result = [Link]("Default Name");

[Link](result);
}
}

Common questions

Powered by AI

To determine if two strings are anagrams, first convert the strings into character arrays, sort the arrays, and then compare them for equality. In Java, use Arrays.sort on both character arrays and then check with Arrays.equals if they are identical. Here's how you can implement this: `String str1 = "listen", str2 = "silent"; char[] a1 = str1.toCharArray(); char[] a2 = str2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); System.out.println(Arrays.equals(a1, a2) ? "Anagram" : "Not Anagram");` .

To find the maximum and minimum elements in an array, iterate through it. Initialize two variables with the first element of the array, one for max and one for min. Traverse the array, updating the max if the current element is greater, and updating the min if the current element is smaller. Here’s the implementation: `int[] arr = {2, 5, 1, 9, 3}; int max = arr[0], min = arr[0]; for (int num : arr) { if (num > max) max = num; if (num < min) min = num; } System.out.println("Max: " + max + ", Min: " + min);` .

To check if a string is a palindrome, reverse the string and compare it to the original string. In Java, you can achieve this by using the StringBuilder to reverse the string and then checking equality. Here’s a sample code: `String str = "madam"; String rev = new StringBuilder(str).reverse().toString(); System.out.println(str.equals(rev) ? "Palindrome" : "Not Palindrome");` .

To merge two sorted arrays without using a sorting algorithm after merging, employ a two-pointer technique. Start with pointers at the beginning of each array and compare their elements. Add the smaller element to the result array and move the pointer. Continue until all elements from both arrays are in the result array. Here's the code: `int[] arr1 = {1, 3, 5, 7}; int[] arr2 = {2, 4, 6, 8}; int[] result = new int[arr1.length + arr2.length]; int i = 0, j = 0, k = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) result[k++] = arr1[i++]; else result[k++] = arr2[j++]; } while (i < arr1.length) result[k++] = arr1[i++]; while (j < arr2.length) result[k++] = arr2[j++];` .

To find the first non-repeated character in a string using Java 8, you can utilize the Stream API. Convert the string into a stream of characters and then group these characters using Collectors.groupingBy function, counting their occurrences. Finally, filter the entries where the count is 1, and retrieve the first such entry. Here's a code snippet: `String input = "interview"; Character result = input.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() == 1).map(Map.Entry::getKey).findFirst().orElse(null);` .

To rotate an array to the right by k steps, reverse different segments of the array. First, reverse the entire array. Then, reverse the first k elements and, finally, reverse the remaining elements. This approach efficiently rearranges elements without requiring additional space. Here is the implementation: `int[] arr = {1, 2, 3, 4, 5}; int k = 2; int n = arr.length; k = k % n; reverse(arr, 0, n - 1); reverse(arr, 0, k - 1); reverse(arr, k, n - 1); System.out.println("Rotated: " + Arrays.toString(arr));` .

The Boyer-Moore Voting Algorithm is an efficient method to find the majority element in an array, which is an element that appears more than n/2 times. The algorithm operates in linear time with constant space. It keeps a count which increases when the current candidate is encountered and decreases for others. When the count reaches zero, a new candidate is chosen. Here is the code: `int[] arr = {2, 2, 1, 2, 3, 2, 2}; int count = 0, candidate = -1; for (int num : arr) { if (count == 0) candidate = num; count += (num == candidate) ? 1 : -1; } count = 0; for (int num : arr) if (num == candidate) count++; System.out.println(count > arr.length / 2 ? "Majority: " + candidate : "No Majority");` .

To remove duplicates from an unsorted list in Java, one can use a `LinkedHashSet`, which preserves the insertion order and automatically removes duplicate entries. Convert the list to a `LinkedHashSet` and back to a list if needed. Here’s an example: `List<String> names = Arrays.asList("Rahul", "Ajay", "Rahul", "Vijay", "Ajay"); Set<String> uniqueNames = new LinkedHashSet<>(names); System.out.println("Unique Names: " + uniqueNames);` .

To generate the Fibonacci sequence without recursion, use iteration and store only the last two numbers of the sequence to calculate the next one. Begin with the first two numbers, 0 and 1, and iterate to generate subsequent numbers by adding the two previous numbers. Here’s a basic example: `int a = 0, b = 1, n = 10; System.out.print(a + " " + b); for (int i = 2; i < n; i++) { int next = a + b; System.out.print(" " + next); a = b; b = next; }` .

To remove all whitespaces from a string in Java without using the replaceAll method, iterate over the string's characters and append only the non-space characters to a StringBuilder. This process skips over spaces while maintaining the order of other characters. Here's an example: `String input = " Java Interview Prep "; StringBuilder result = new StringBuilder(); for (char c : input.toCharArray()) { if (c != ' ') { result.append(c); } } System.out.println("Without spaces: " + result.toString());` .

You might also like