Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Top 30 Java Programming interview questions

Last Updated on March 10, 2022 by Ria Pathak

1. Check if a given number is palindrome or not.
Ans. A palindrome is a number which is when reversed give the same number. We find the reverse and check whether it is equal to the given number or not.

``````public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int length = str.length();
boolean isPalindrome = true;
for(int i = 0; i < length; i++)
{
if(str.charAt(i) != str.charAt(length-1-i)) {
System.out.println("Snot a palindrome.");
isPalindrome = false;
break;
}
}
if(isPalindrome) {
System.out.println("palindrome.");
}
}``````
2. Count the occurrence of a given character in string.
Ans.

``````public static void main(String args[]){
String str = "this is a string";
char ch = 's';
int count = 0;
for(char c:strArr){
if(c == 's'){
count++;
}
}
System.out.println(count);
}``````
3. Find the GCD of two numbers in logn time.
Ans.

``````public static int gcd(int a, int b) {
while (((a > 0) && (b > 0))) {
if ((a > b)) {
a = (a % b);
} else {
b = (b % a);
}
}
if ((a == 0)) {
return b;
} else {
return a;
}
}
public static void main(String[] args) {
int a = new Scanner(System.in);
int b = new Scanner(System.in);
System.out.println(GCD.gcd(a, b));
}``````
4. Can you code the Binary Search Algorithm in Java?
Ans.

``````public int binarySearch(int a[], int num)
{
if(num>a[a.length-1]||num<a[0])return -1;
int start=0;
int end =a.length-1;
int mid=(start+end)/2;
while(a[mid]!=num){
if(num<mid){
end=mid;
}else{
start=mid;
}
mid = (start+end)/2;
}
return mid;
}``````
5. Implement the merge Sort algorithm.
Ans. This is a Divide and conquer algorithm.

``````
public static void main(String[] args) {
int[] list = {4,5,2,1,3};
mergeSort(list, 0, list.length - 1);
}
public static void mergeSort(int[] a, int first, int last)
{
if(last - first == 0)
{
}
else if (last - first == 1)
{
if(a[first] > a[last])
{
int temp = a[first];
a[first] = a[last];
a[last] = temp;
}
}
else
{
int mid = (first + last) / 2;
mergeSort(a, first, mid);
mergeSort(a, mid + 1, last);
merge(a, first, mid, last);
}
}
private static void merge(int[] a, int first, int mid, int last)
{
int[] temp = new int[last - first + 1];
int i = first; int j = mid + 1;
for(int k = first; k <= last; k++)
{
if(i > mid || j > last)
{
if(i > mid && j <= last)
{
System.out.println("a[j]: " + a[j]);
temp[k - first] = a[j];
j++;
}
else if(i <= mid && j > last)
{
System.out.println("a[i]: " + a[i]);
temp[k - first] = a[i];
i++;
}
else
{
break;
}
}
else
{
if(a[i] < a[j])
{
temp[k - first] = a[i];
i++;
}
else
{
temp[k - first] = a[j];
j++;
}
}
}
for(int count = 0; count < temp.length; count++)
{
a[first + count] = temp[count];
}
}``````
6. Implement a quicksort algorithm.
Ans.

``````public int partition(ArrayList list, int start, int end)  {
double pivot = list.get(end);
int i = (start - 1);
for (int j = start; j < end; j++) {
if (list.get(j) <= pivot) {
i++;
double temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
} double temp = list.get(i + 1);
list.set((i + 1), list.get(end));
list.set(end, temp);
return i + 1;
}
public ArrayList sort(ArrayList list, int start, int end) {
if (start < end) {
int pi = partition(list, start, end);
sort(list, start, pi - 1);
sort(list, pi + 1, end);
}  return list;
}
public ArrayList Solve(double[] nums, int a, int b, int c) {
ArrayList newList = new ArrayList();
double xyz;
for (int i = 0; i < nums.length; i++) {
xyz = ((a * nums[i]) * nums[i]) + b * nums[i] + c;
} return newList;
}
public static void main (String[] args) {
QuickSort obj = new QuickSort();
double nums[] = {1,2,4, 9,5,3,0};
int a = 1, b = 0, c = 0;
ArrayList list = obj.Solve(nums, a, b, c);
list = obj.sort(list, 0, (nums.length - 1));
for (int i = 0; i ");
current = current.next();
count++;
if(count == 10)
break;
}
return sb.toString();
}
public static class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return this.data;
}
}
}
public class LoopInLinkedListTest {
public static void main(String args[]) {
if(false){
}else{
}
System.out.println("contains loop");
}
else{
System.out.println("no loop");
}

}
}``````
7. Check if a linked list is a palindrome or not.
Ans.

``````class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public int size;
public Node head = null;
public Node tail = null;
public void addNode(int data) {
Node node = new Node(data);
if(head == null) {
tail = node;
} else {
tail.next = node;
tail = node;
}
size++;
}
public Node reverseList(Node temp) {
Node current = temp;
Node prevNode = null;
Node nextNode = null;
while(current != null) {
nextNode = current.next;
current.next = prevNode;
prevNode = current;
current = nextNode;
}
return prevNode;
}
public void isPalindrome() {
Node current = head;
boolean flag = true;
int mid = (size % 2 == 0) ? (size/2) : ((size+1)/2);
for(int i = 1; i < mid; i++) {
current = current.next;
}
Node revHead = reverseList(current.next);
while(head != null && revHead != null) {
flag = false;
break;
}
}
if(flag) {
System.out.println("\nPalondrome !");
} else {
System.out.println("\nnot Palindrome !");
}
}
public void display() {
Node current = head;
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println(" ");
}
public static void main(String[] args) {
}``````
8. Find pairs in the array such that its sum is closest to 0.
Ans.

``````public static void PairWithMinSum(int arr[]) {
int minimumSum = arr[0] + arr[1];
int pair1stIndex = 0;
int pair2ndIndex = 1;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int tempSum = arr[i] + arr[j];
if (Math.abs(tempSum) < Math.abs(minimumSum)) {
pair1stIndex = i;
pair2ndIndex = j;
minimumSum = tempSum;
}
}
}
System.out.println( arr[pair1stIndex] + "  " + arr[pair2ndIndex]);
}
public static void main(String[] args) {
int[] arr = { 2, 3, -1, 5, 6, -3};
PairWithMinSum(arr);
}``````
9. Given an array of 0’s and 1’s in random order, you need to separate 0’s and 1’s in an array.
Ans.

``````public static int[] separate0s1sSolution1(int arr[]){
int count=0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]==0)
{
count++;
}
}
for (int i = 0; i < count; i++) {
arr[i]=0;
}
for (int i = count; i < arr.length; i++) {
arr[i]=1;
}
return arr;
}``````
10. You are given an array, find the subarray with a given sum.
Ans.

``````public void findSubarraySum(int arr[], int target) {
int left = 0;
int right = left + 1;
int sum = 0;
if (arr.length == 0) {
System.out.println("-1");
return;
}
if (arr.length == 1) {
if (arr[0] == target) {
System.out.println((arr[0] + 1) + " " + (arr[0] + 1));
} else {
System.out.println("-1");
}
}
sum += arr[left] + arr[right];
while (right < arr.length) {
if (sum == target) {
System.out.println((left + 1) + " " + (right + 1));
return;
} else if (sum < target) {
right++;
if (right = 0) {
int n = in.nextInt();
int target = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
ss.findSubarraySum(arr, target);
}
}``````
11. You are given an array, find the maximum subarray sum.
Ans. We will use Kadane’s algorithm here

``````public static void main(String[] args) {
int[] Arr = {5,2,-1,-2,3,-5,1};
findMaxSubArray(Arr);
}
public static void findMaxSubArray(int[] inputArray) {
int maxStartIndex = 0;
int maxEndIndex = 0;
int maxSum = Integer.MIN_VALUE;
int cumulativeSum = 0;
int maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex  maxSum) {
maxSum = cumulativeSum;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (cumulativeSum < 0) {
maxStartIndexUntilNow = currentIndex + 1;
cumulativeSum = 0;
}
}
System.out.println(maxSum);
}``````
12. Write a function to add two numbers represented by two linked list.
Ans.

``````public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return l1 == null ? l2 : l1;
}
Stack s1 = new Stack();
Stack s2 = new Stack();
Stack result = new Stack();
while (l1 != null) {
s1.push(l1);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2);
l2 = l2.next;
}
int carry = 0;
while (!s1.isEmpty() || !s2.isEmpty()) {
int sum = carry;
if (!s1.isEmpty()) {
sum += s1.pop().val;
}
if (!s2.isEmpty()) {
sum += s2.pop().val;
}
carry = sum / 10;
sum = sum % 10;
result.push(new ListNode(sum));
}
if (carry != 0) {
result.push(new ListNode(carry));
}
ListNode node = new ListNode(-1);
ListNode temp = node;
while (!result.isEmpty()) {
node.next = result.pop();
node = node.next;
}
return temp.next;
}``````
13. Write a program to find the first non-repeating character of a string.
Ans.

``````public static charsolve(String word) {
Set duplicate = new HashSet();
List nonDuplicate = new ArrayList();
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
if (duplicate.contains(letter)) {
continue;
}
if (nonDuplicate.contains(letter)) {
nonDuplicate.remove((Character) letter);
} else {
}
}
return nonDuplicate.get(0);
}``````
14. Write a program to find the duplicate characters in a string.
Ans.

``````public static void main(String[] args) {
String str = new String("duplicatestring");
int count = 0;
char[] chars = str.toCharArray();
for (int i=0; i<str.length();i++) {
for(int j=i+1; j<str.length();j++) {
if (chars[i] == chars[j]) {
System.out.println(chars[j]);
count++;
break;
}
}
}
}``````
15. Print all the substrings of a string.
Ans.

``````public static void PrintSubstring(String str, int length) {
for (int i = 0; i < length; i++) {
for (int j = i + 1; j  -1; i--) {
sb.append(arr[i]).append(" ");
}
return sb.toString().trim();
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
in.close();
System.out.println(reverseLine(s));
}``````
16. Implement an algorithm of counting sort.
Ans.

``````public static void countingSort(int[] input, int k) {
int counter[] = new int[k + 1];
for(int i : input) {
counter[i]++;
}
int ndx = 0;
for(int i = 0; i < counter.length; i++) {
while( 0 < counter[i]) {
input[ndx++] = i;
counter[i]--;
}
}
}
public static void main(String[] args) {
int[] input = { 60, 40, 30, 20, 10, 40, 30, 60, 60, 20, 40, 30, 40 };
int k = 60;
countingSort(input, k);
System.out.println(Arrays.toString(input));
}``````
17. Give a recursive function for Inorder traversal of a Binary Tree.
Ans.

``````void inOrderTraversal2(TreeNode node) {
if (node == null) {
return;
}
inOrderTraversal2(node.left);
System.out.println(node.val);
inOrderTraversal2(node.right);
}``````
18. Check if a given Binary tree is height balanced or not. You will be given a root to that tree.
Ans.

``````class TreeNode {
int value;
TreeNode left, right;
}
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
int left = getHeight(root.left);
int right = getHeight(root.right);
if (Math.abs(left - right) <= 1)
return isBalanced(root.left) && isBalanced(root.right);
else
return false;
}
public int getHeight(TreeNode root) {
if (root == null)
return 0;
else {
int left = getHeight(root.left);
int right = getHeight(root.right);
return Math.max(left, right) + 1;
}
}``````
19. Write a program to invert a Binary Tree.
Ans.

``````class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
TreeNode result = new TreeNode(root.val);
result.right = this.invertTree(root.left);
result.left = this.invertTree(root.right);
return result;
}``````
20. Write a program to sort a stack recursively.
Ans.

``````public static void main(String args[]) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(4);
stack.push(3);
stack.push(-2);
for (Integer i: stack) {
System.out.print(i + ", ");
}
System.out.println();
sort(stack);
for (Integer i: stack) {
System.out.print(i + ", ");
}
System.out.println();
}
public static void sort(Stack stack) {
removeElement(stack);
}
private static void removeElement(Stack stack) {
if(!stack.isEmpty()) {
int tmp = stack.pop();
removeElement(stack);
insertElement(tmp, stack);
}
}
private static void insertElement(int tmp, Stack stack) {
if(stack.isEmpty() || tmp >= stack.peek()) {
stack.push(tmp);
}
else {
int poped = stack.pop();
insertElement(tmp, stack);
stack.push(poped);
}
}``````
21. Implement a queue using two stacks.
Ans.

``````Stack entryStack;
Stack exitStack;
public MyQueue() {
this.entryStack = new Stack();
this.exitStack = new Stack();
}
public void push(int x) {
this.entryStack.push(x);
}
public int pop() {
while(!this.entryStack.isEmpty()){
this.exitStack.push(this.entryStack.pop());
}
int retValue = this.exitStack.pop();
while(!this.exitStack.isEmpty()){
this.entryStack.push(this.exitStack.pop());
}
return retValue;
}
public int peek() {
while(!this.entryStack.isEmpty()){
this.exitStack.push(this.entryStack.pop());
}
int retValue = this.exitStack.peek();
while(!this.exitStack.isEmpty()){
this.entryStack.push(this.exitStack.pop());
}
return retValue;
}
public boolean empty() {
return this.entryStack.isEmpty();
}``````
22. Implement an LRU cache in Java.
Ans.

``````class Node {
int key;
int value;
Node prev;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
Node tail;
public boolean isEmpty(){
return this.head == null;
}
if(this.isEmpty()){
this.head = this.tail = node;
node.prev = null;
node.next = null;
}
else{
node.prev = null;
}
}
public Node deleteFromTail(){
Node node = this.tail;
this.head = this.tail = null;
}
else{
this.tail = this.tail.prev;
this.tail.next = null;
}
return node;
}
public void moveToHead(Node node){
return;
else if(this.tail == node){
this.deleteFromTail();
}
else{
node.prev.next = node.next;
if(node.next != null)
node.next.prev = node.prev;
node.next = null;
node.prev = null;
}
}
}
HashMap nodes;
int count, capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
this.count = 0;
this.nodes = new HashMap();
this.list = new DoublyLinkedList();
}
public int get(int key) {
if(nodes.containsKey(key)){
Node node = nodes.get(key);
return node.value;
}
else
return -1;
}
public void put(int key, int value) {
if(nodes.containsKey(key)){
Node node = nodes.get(key);
node.value = value;
}
else{
Node node = new Node(key, value);
nodes.put(key, node);
this.count++;
if(this.count > this.capacity){
Node toDelete = this.list.deleteFromTail();
this.nodes.remove(toDelete.key);
this.count--;
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/``````
23. Traverse the Binary tree in zig-zag way and print the nodes.
Ans.

``````public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public List<List> zigzagLevelOrder(TreeNode root) {
List<List> result = new LinkedList();
if(root == null) return result;
Queue queue = new LinkedList();
boolean direction = false;
while(queue.size() > 0){
direction = !direction;
Queue level = new LinkedList();
List rlevel = new LinkedList();
while(queue.size() > 0){
TreeNode node = queue.poll();
if(direction){
}else{
}
if(node.left != null) level.add(node.left);
if(node.right != null) level.add(node.right);
}
queue = level;
}
return result;
}``````
24. Write a program to traverse a graph in BFS.
Ans.

``````public class Graph {
private final int v;
public Graph(int v) {
this.v = v;
for (int i = 0; i < v; ++i) {
}
}
void addEdge(int v, int e) {
}
void BFS(int start) {
boolean visited[] = new boolean[v];
visited[start] = true;
while (!queue.isEmpty()) {
start = queue.poll();
System.out.print(start + " ");
Iterator i = adjacents[start].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(4);
graph.BFS(0);
}
}``````
25. Write a function to insert a node in Binary Search Tree.
Ans.

``````static Node Insert(Node root, int value){
Node newNode = new Node();
newNode.data = value;
newNode.left = null;
newNode.right = null;
if (root == null) {
return newNode;    }

return root;
}
static void addNode(Node root, Node newNode) {
if (newNode.data < root.data) {
if (root.left == null) {
root.left = newNode;
} else {
}
} else {
if (root.right == null) {
root.right = newNode;
} else {
}
}
}``````
26. Suppose you are given an array and you are asked to find the triplets whose sum will be a given target sum. If your array contains such a triplet return the sum else -1.
Ans.

``````public ArrayList<ArrayList> threeSum(int[] num) {
ArrayList<ArrayList> result = new ArrayList<ArrayList>();
if (num.length < 3) {
return result;
}

Arrays.sort(num);

for (int i = 0 ; i < num.length - 2 ; i++) {
if (i != 0 && num[i] == num[i-1]) {
continue;
}
int left = i + 1;
int right = num.length - 1;

while (left < right) {
int sum = num[i] + num[left] + num[right];
if (sum  0) {
right--;
} else {
ArrayList temp = new ArrayList();
do {
left++;
} while (left  left && num[right] == num[right+1]);
}
}
}
return result;
}``````
27. Find the Kth largest element in an array.
Ans.

``````public int kthLargestElement(int k, ArrayList nums) {
if (nums == null || nums.size() == 0) {
return 0;
}
return helper(nums, 0, nums.size() - 1, nums.size() - k);
}
public void swap( ArrayListnums, int x, int y){
int temp = nums.get(x);
nums.set(x, nums.get(y));
nums.set(y, temp);
}
public int helper( ArrayList nums, int start, int end, int mid) {
int pivot = end;
int num = nums.get(pivot);
int low = start;
int high = end;
while (low < high) {
while(low < high && nums.get(low) < num) {
low++;
}
while(low = num) {
high--;
}
swap(nums, low, high);
}
swap(nums, low, pivot);
if (low == mid) {
return nums.get(low);
} else if (low < mid) {
return helper(nums, low + 1, end, mid);
} else {
return helper(nums, start, low - 1, mid);
}
}``````