0% found this document useful (0 votes)
23 views

Java

The document provides solutions to common Java coding interview questions. It includes programs to reverse a string, find the largest number in an array, check if a number is prime, find a factorial, remove duplicate elements from an array, find the second largest number in an array, check if two strings are anagrams, reverse a linked list, find the first non-repeating character in a string, check if a string is a palindrome, find the minimum coins to make change, find the intersection of two linked lists, find the maximum sum subarray, calculate the nth Fibonacci number, swap two numbers without a third variable, check if a string contains vowels, sort an array, and implement a binary search.

Uploaded by

beshahashenafe20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java

The document provides solutions to common Java coding interview questions. It includes programs to reverse a string, find the largest number in an array, check if a number is prime, find a factorial, remove duplicate elements from an array, find the second largest number in an array, check if two strings are anagrams, reverse a linked list, find the first non-repeating character in a string, check if a string is a palindrome, find the minimum coins to make change, find the intersection of two linked lists, find the maximum sum subarray, calculate the nth Fibonacci number, swap two numbers without a third variable, check if a string contains vowels, sort an array, and implement a binary search.

Uploaded by

beshahashenafe20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Search

Write

Sign up
Sign in

Java Coding Interview Questions


and Solutions

Diptendu Das
·

Follow
7 min read

Apr 24, 2023

50
1
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. Write a program to reverse a string in Java.

public class StringReverse {


public static void main(String[] args) {
String str = "Hello World";
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse().toString());
}
}

2. Write a program to find the largest number in an array in Java.

public class LargestNumber {


public static void main(String[] args) {
int[] nums = {1, 5, 3, 9, 7};
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
System.out.println("Largest number: " + max);
}
}

3. Write a program to check if a given number is prime in Java.

public class PrimeNumber {


public static void main(String[] args) {
int num = 7;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}

4. Write a program to find the factorial of a given number in Java.

public class Factorial {


public static void main(String[] args) {
int num = 5;
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is " + fact);
}
}

5. Write a program to remove duplicate elements from an array in Java.

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicates {


public static void main(String[] args) {
int[] nums = {1, 2, 3, 1, 2, 4, 5};
Set<Integer> set = new LinkedHashSet<>();
for (int num : nums) {
set.add(num);
}
Integer[] result = set.toArray(new Integer[set.size()]);
System.out.println(Arrays.toString(result));
}
}

6. Write a program to find the second largest number in an array in Java.

public class SecondLargestNumber {


public static void main(String[] args) {
int[] nums = {1, 5, 3, 9, 7};
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
secondMax = max;
max = nums[i];
} else if (nums[i] > secondMax && nums[i] != max) {
secondMax = nums[i];
}
}
System.out.println("Second largest number: " + secondMax);
}
}

7. Write a program to check if two strings are anagrams in Java.

import java.util.Arrays;

public class AnagramCheck {


public static void main(String[] args) {
String str1 = "silent";
String str2 = "listen";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
if (Arrays.equals(arr1, arr2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}

8. Write a program to reverse a linked list in Java.

class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}

public class LinkedListReverse {


public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
head = prev;
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}

9. Write a program to find the first non-repeating character in a string in


Java.

public class NonRepeatingChar {


public static void main(String[] args) {
String str = "leetcode";
int[] freq = new int[26];
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i) - 'a']++;
}
for (int i = 0; i < str.length(); i++) {
if (freq[str.charAt(i) - 'a'] == 1) {
System.out.println("First non-repeating character: " + str.charAt(i));
return;
}
}
System.out.println("There are no non-repeating characters in the string.");
}
}

10. Write a program to check if a given string is a palindrome in Java.

public class PalindromeCheck {


public static void main(String[] args) {
String str = "racecar";
int i = 0;
int j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
System.out.println(str + " is not a palindrome.");
return;
}
i++;
j--;
}
System.out.println(str + " is a palindrome.");

11. Write a program to find the minimum number of coins needed to make
change for a given amount in Java.
public class CoinChange {
public static void main(String[] args) {
int[] coins = {1, 5, 10, 25};
int amount = 30;
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if (i >= coins[j]) {
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
}
}
}
System.out.println("Minimum number of coins needed: " + dp[amount]);
}
}

12. Write a program to find the intersection of two linked lists in Java.

class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}

public class LinkedListIntersection {


public static void main(String[] args) {
ListNode headA = new ListNode(4);
headA.next = new ListNode(1);
headA.next.next = new ListNode(8);
headA.next.next.next = new ListNode(4);
headA.next.next.next.next = new ListNode(5);
ListNode headB = new ListNode(5);
headB.next = new ListNode(0);
headB.next.next = new ListNode(1);
headB.next.next.next = headA.next.next;
ListNode ptrA = headA;
ListNode ptrB = headB;
while (ptrA != ptrB) {
ptrA = ptrA == null ? headB : ptrA.next;
ptrB = ptrB == null ? headA : ptrB.next;
}
System.out.println("Intersection node: " + ptrA.val);
}
}

13. Write a program to find the maximum sum subarray in an array in Java.

public class MaxSubarraySum {


public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSum = Integer.MIN_VALUE;
int currSum = 0;
for (int i = 0; i < nums.length; i++) {
currSum += nums[i];
if (currSum > maxSum) {
maxSum = currSum;
}
if (currSum < 0) {
currSum = 0;
}
}
System.out.println("Maximum sum subarray: " + maxSum);
}
}

14. Write a program to find the nth Fibonacci number in Java.

public class Fibonacci {


public static void main(String[] args) {
int n = 10;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
System.out.println("The " + n + "th Fibonacci number: " + dp[n]);
}
}

15. How do you swap two numbers without using a third variable in Java?

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)

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

public class StringContainsVowels {

public static void main(String[] args) {


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

public static boolean stringContainsVowels(String input) {


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

}
17. How do you sort an array in Java?

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

Arrays.sort(array);

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

18. 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:

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

while (low <= high) {


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

if (low > high) {


return -1;
}

return -1;
}

19. 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:

public class MergeSort {

public static void main(String[] args) {


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

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

for (int val : merged) {


System.out.print(val + " ");
}
}

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


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

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

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


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

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

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

return sorted;
}

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


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

return br;
}

int mid = (lo + hi) / 2;

int[] fh = mergeSort(arr, lo, mid);


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

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

return merged;
}

}
Check this website specially designed by Coder for Coding Community

https://greatmindslab.com/

Java Interview Questions

Java Coding Practices

Java Coding

Java Coding Problems

Java Course

50
1
Written by Diptendu Das

488 Followers
Solution Architect

Follow

More from Diptendu Das


Diptendu Das

GitHub Setup on Mac OS


Setting up GitHub on your Macbook Pro involves a few steps. Here’s a step-by-step guide to
get you started:

2 min read·Sep 20, 2023

11
Diptendu Das

Most Common CI CD Interview Questions & Answers


Here are the most common CI/CD (Continuous Integration/Continuous Deployment) interview
questions and sample answers asked by MNC…

7 min read·Sep 16, 2023

138
Diptendu Das

Java Memory Management Interview Questions and Answers


Q: What is memory management in Java?

5 min read·Apr 20, 2023

63

1
Diptendu Das

Difference Between AES and SHA256


AES (Advanced Encryption Standard) and SHA-256 (Secure Hash Algorithm 256-bit) are two
cryptographic algorithms, but they serve different…

2 min read·Oct 10, 2023

See all from Diptendu Das

Recommended from Medium


Vishal Garg

Senior Java Backend Developer Interview — 2

JAVA

1 min read·Oct 27, 2023

10
Ajay Rathod
Barclays Java Spring-Boot Micro-service Interview Question with answer
2024

Hello folks welcome to another real life interview transcript from a banking giant. This was
for Java backend role for experienced…

19 min read·Mar 30, 2024

179

Lists

Staff Picks
616 stories·886 saves
Stories to Help You Level-Up at Work
19 stories·557 saves

Self-Improvement 101
20 stories·1586 saves

Productivity 101
20 stories·1469 saves
Devendu

I Solved 300+ Leetcode problems , Here is what I learnt.

3 min read·Mar 22, 2024

550

13
AKCoding.com

Java Interview Questions for 5 Years Experience


For candidates with 5 years of Java experience, interview questions may delve into
intermediate to advanced topics, focusing on deeper…

4 min read·Feb 13, 2024

3
Abhishek Singh

in

ILLUMINATION
Java 8 Stream API Commonly Asked Interview Questions
Java Streams can be used to process a series of components and are essentially a pipeline
of aggregating operations.

5 min read·Nov 29, 2023

529

4
KARAN VERMA

Microservices Concepts In 2024


Micro services learning are must if you are interviewing in 2024, so be prepared by brushing
up the following concepts:

2 min read·Feb 5, 2024

See more recommendations

Help

Status

About

Careers

Blog

Privacy

Terms

Text to speech

Teams

You might also like