InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Write a program in Java to show Thread Synchronization. |
|
Answer» Here, you can create any 2 threads and synchronize them by using the synchronized keyword. An example program is given below. Java Program to show Thread Synchronization class Table {public synchronized void display(int n) { for (int i = 1; i <= 10; i++) { System.out.println(n * i); } } } class Thread1 extends Thread { Table t; public Thread1(Table t) { this.t = t; } public void run() { t.display(5); } } class Thread2 extends Thread { Table t; public Thread2(Table t) { this.t = t; } public void run() { t.display(6); } } public class Main { public static void main(String[] args) { Table table = new Table(); Thread1 th1 = new Thread1(table); Thread2 th2 = new Thread2(table); th1.start(); th2.start(); } } Output 510 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 Additional Resources
|
|
| 2. |
Write a program in Java to show isAlive() and join() operations in multithreading. |
|
Answer» The isAlive() method tells whether a thread is alive or terminated. These alive and terminated are the states of a thread in Java. Also, the join() operation joins a thread to another. This means that the thread will wait for the complete execution of the thread to which it is joined even if its own work is completed. Then, they both will terminate together. Java Code to show isAlive() and join() operations class DemoThread extends Thread {public DemoThread(String name) { super(name); setPriority(MAX_PRIORITY); } } class DemoThread2 extends Thread { public void run() { int count = 1; while (true) { System.out.println(count); count++; try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println(e); } } } } public class Main { public static void main(String[] args) { DemoThread t = new DemoThread("Thread 1"); System.out.println("ID " + t.getId()); System.out.println("NAME " + t.getName()); System.out.println("PRIORITY " + t.getPriority()); t.start(); System.out.println("STATE " + t.getState()); System.out.println("ALIVE " + t.isAlive()); DemoThread2 t2 = new DemoThread2(); try { Thread.sleep(100); } catch (Exception e) { } t2.setDaemon(true); t2.start(); // t2.interrupt(); Thread mainThread = Thread.currentThread(); try { mainThread.join(); // Now main will not terminate till the daemon thread is terminated } catch (Exception e) { } } } Output ID 13NAME Thread 1 PRIORITY 10 STATE RUNNABLE ALIVE false 1 2 3 4 5 6 7 |
|
| 3. |
Write a program in Java to show the Diamond Problem. |
|
Answer» The Diamond Problem is a problem of Multiple inheritance. It is one of the major reasons why multiple inheritance is not supported in Java. Have a look at the diagram given below. Here, class D extends from classes B and C and they extend from Class A. Let us say that class A has a function called print(). This function is overridden in Class B and C respectively. Now, when class D extends B and C both, say it calls super.print(). Which function should be called? This is an anomaly called the diamond problem or deadly diamond of death. Java Code for Diamond Problem class A {public void print() { System.out.println("Class A print method"); } } class B extends A { @Override public void print() { System.out.println("Class B print method"); } } class C extends A { @Override public void print() { System.out.println("Class C print method"); } } //multiple inheritance not allowed in Java class D extends A,B { @Override public void print() { System.out.println("Class D print method"); } } class Main { public static void main(String args[]) { // Your code goes here D obj = new D(); obj.print(); } } Output This compilation error occurs because multiple inheritance is not allowed in Java. |
|
| 4. |
Write a program in Java, to show nesting of classes. |
|
Answer» Nesting of classes means writing a class inside another class. The inner classes in Java are usually static. This happens when we don’t want to use the variable of the outer class in the inner class. This helps to create an instance/object of the inner class without creating an instance of the Outer class. Following is a program to show the nesting of classes in Java. Java Code public class Main {public static void main(String[] args) { Outer obj1 = new Outer(10, 20); Outer.Inner2 obj2 = new Outer.Inner2(40); obj2.showData(); Outer.Inner3.z = 100; System.out.println(Outer.Inner3.z); } } class Outer { private int x, y; Outer() { System.out.println("Outer class default constructor called"); } Outer(int x, int y) { this.x = x; this.y = y; } void showData() { System.out.println("the value of x is:" + x + " and the value of y is: " + y); } class Inner1 { int z = 0; Inner1() { System.out.println("Inner class default constructor called"); } Inner1(int z) { this.z = z; } void showData() { System.out.println("The value of x is: " + x + " the value of y is: " + y + " and z is: " + z); } } static class Inner2 { int z = 0; Inner2() { System.out.println("Inner class default constructor called"); } Inner2(int z) { this.z = z; } void showData() { System.out.println("The value of z is: " + z); } } static class Inner3 { static int z = 0; Inner3() { System.out.println("Inner class default constructor called"); } Inner3(int a) { z = a; } void showData() { System.out.println("The value of z is: " + z); } } } Output The value of z is: 40100 |
|
| 5. |
Write a program in Java to show multiple inheritance. |
|
Answer» Multiple inheritance is not possible in Java. So, we can use Interfaces in Java to create a scenario of multiple inheritance. In our example below, we have a class called Phone and a class called SmartPhone. We know that a SmartPhone is a Phone, however, it has various other features as well. For instance, a SmartPhone has a camera, a music player, etc. Notice that a SmartPhone is a Phone and has a camera and has a Music Player. So, there is one is-A relationship and multiple has-A relationships. The is-A relationship denotes extending the features and the has-A relationship denotes implementing the features. This means that a SmartPhone is a Phone i.e. it extends the features of a Phone however, it just implements the features of a Music Player and a Camera. It itself is not a music player or a camera. Following is the code for the above discussion. Java Code for Multiple Inheritance public class Main {public static void main(String[] args) { SmartPhone sp1 = new SmartPhone(); Phone p1 = new SmartPhone(); ICamera c1 = new SmartPhone(); IMusicplayer m1 = new SmartPhone(); sp1.videocall(); p1.call(); p1.message(); c1.click(); c1.record(); m1.play(); m1.pause(); m1.stop(); } } class Phone { void call() { System.out.println("call"); } void message() { System.out.println("Message"); } } interface ICamera { void click(); void record(); } interface IMusicplayer { void play(); void pause(); void stop(); } class SmartPhone extends Phone implements ICamera, IMusicplayer { void videocall() { System.out.println("Video call"); } @Override public void click() { System.out.println("Picture click"); } @Override public void record() { System.out.println("Record video"); } @Override public void play() { System.out.println("Play music"); } @Override public void pause() { System.out.println("Pause Music"); } @Override public void stop() { System.out.println("Stop music"); } } Output Video callCall Message Picture click Record Video Play music Pause Music Stop music |
|
| 6. |
Write a program in Java to create a user defined exception and also show it working means when it throws an exception. |
|
Answer» Here, you have to explain and write a user-defined exception of your own. This code is just for reference purposes. So, we are going to create an exception called LowBalanceException for a bank. So, whenever a person comes to the bank to create a bank account, the minimum account balance should be 5000. So, if the balance is less than 5000, the exception will be thrown. Let us write the code for the same. Java Code for User-Defined Exception public class Main {public static void main(String[] args) { Account a1 = new Account(500); Account a2 = new Account(); a2.setBalance(500); Account a3 = new Account(10000); System.out.println("a1 balance = " + a1.getBalance() + " a2 balance = " + a2.getBalance() + " a3 balance = " + a3.getBalance()); } } class Account { private int balance; Account() { balance = 5000; } Account(int balance) { try { if(balance>=5000) { this.balance = balance; System.out.println("The account is created and the balance is set to: "+ balance); } else { this.balance=0; System.out.println("Account can not be created"); throw new LowBalanceException(); } } catch(LowBalanceException e) { System.out.println(e); } } void setBalance(int balance) { try { if(balance>=5000) { this.balance = balance; System.out.println("The account is created and the balance is set to: "+ balance); } else { this.balance=0; System.out.println("Account can not be created"); throw new LowBalanceException(); } } catch(LowBalanceException e) { System.out.println(e); } } int getBalance() { return balance; } } class LowBalanceException extends Exception { public String toString() { return "Low Balance: The balance cannot be less than Rs.5000/-"; } } Output The account can not be createdLow Balance: The balance cannot be less than Rs.5000/- The account can not be created Low Balance: The balance cannot be less than Rs.5000/- The account is created and the balance is set to 10000 a1 balance = 0 a2 balance = 0 a3 balance =10000 |
|
| 7. |
Write a program in Java to search an element in a row-wise and column-wise sorted 2-D matrix of size M x N. |
|
Answer» You have to search the element in O(N + M) time complexity without using any extra space. Print “true” if the element exists in the matrix else print “false”. The normal searching technique will take O(N2) time complexity as we will search every element in the matrix and see if it matches our target or not. The other approach uses the fact that the elements are sorted row-wise. We can apply binary search on every row. Hence, the time complexity will be O(Nlog2N) Let us say we want to search for 21. We know that 21 is larger than 15. Since the matrix is row-wise sorted, element 15 is the largest element of this row. So, we are not going to find 21 in this row. So, we move directly to the last element of the next row. The Same is the case here as well. So, we move to the next row. Here, the element is 22. So, 21 might be present in this row. So, we move one step backwards in this row only. On moving one step backwards, we see that we reach 16. Since this number is smaller than our target of 21, we know that we will not find our target in this row. Hence, we move to the last element of the next row and the same happens here too. Now, we are in the last row. We know that element might exist in this row. So, we keep on moving back in this row and find element 21. So, we will implement this same algorithm. This is called staircase search. Java Code for Staircase Search import java.util.*;class Main { public static boolean staircaseSearch(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int j = matrix[0].length - 1 ; int i = 0; while(i < matrix.length && j>=0) { if(matrix[i][j] == target) return true; else if(matrix[i][j] < target) { i++; } else { j--; } } return false; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int N = scn.nextInt(); int M = scn.nextInt(); int[][] mat = new int[N][M]; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { mat[i][j] = scn.nextInt(); } } int target = scn.nextInt(); System.out.println(staircaseSearch(mat,target)); } } Sample Output 5 51 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 21 Output: true
|
|
| 8. |
You are given a 2-D array of size N x N. You have to print the elements of the array in diagonal order as shown below |
|
Answer» So, we have travelled the upper triangular half of the matrix diagonally. We can clearly see that the first diagonal has row = col i.e. the gap between them is 0. In the next diagonal, the column index is always greater than the row index by 1. The max gap up to which we can go is N-1, where N is the number of columns. So, we will use this gap strategy to traverse the matrix diagonally as shown below. Java Code for Diagonal Traversal import java.util.*;public class Main { public static void main(String[] args) throws Exception { // write your code here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[][] mat = new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j] = scn.nextInt(); } } diagonalTraversal(mat); } public static void diagonalTraversal(int[][] mat) { int maxGap = mat[0].length - 1; for(int gap=0;gap<=maxGap;gap++) { for(int i=0,j=gap;i<mat.length && j<mat[0].length;i++,j++) { System.out.print(mat[i][j] + " "); } System.out.println(); } } } Sample Output Input:5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Output: 1 7 13 19 25 2 8 14 20 3 9 15 4 10 5
|
|
| 9. |
You are given an array of integers. Your task is to Wave sort the array. For example, let us say the array is arr = {9,8,6,3,4,7,2}. Currently, the graph for the array of elements looks like this: |
|
Answer» We want the graph to look like this: It is not necessary that you print the same order of elements as shown above. You can print any other order but the shape of the graph of elements of the array should look like a wave. The graph should always start with the peak and not a valley. You are not allowed to use any extra space and you have to solve this problem in O(N) time complexity. One basic approach to solve this problem is to sort the array and then swap the adjacent elements. The time complexity for which is O(NLog2N). Since we have to solve the problem in O(N) time complexity, we can solve it using the Wave Sort algorithm. Our aim is to generate the Wave Graph. The aim can be accomplished by aiming at generating the peaks in the array or aiming at generating the valleys in the array. So, let us try to generate peaks in the array. Since we want the first array to be the peak, we will leave it as it is and start from the index = 2. Here, since we want to generate a peak, we need to have the previous and next elements smaller than our current elements. So, we will check that if our previous element is larger than our element, we will swap them. Again, at the same position, we will also check that the next element should be smaller than our current element. If it is not, swap these 2 elements. This is shown below. So, we have to take a jump of 2 indices every time till we reach the end of the array. Hence, we will be able to wave sort the array in O(N) time and O(1) space. Java Code for Wave Sort import java.util.*;class Main { public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void waveSort(int[] arr) { for(int i=0;i<arr.length;i=i+2) { if(i>0 && arr[i-1] > arr[i]) { swap(arr,i-1,i); } if(i<arr.length-1 && arr[i+1] > arr[i]) { swap(arr,i,i+1); } } } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = scn.nextInt(); } waveSort(arr); System.out.println("After wave sort"); for(int i=0;i<arr.length;i++) { System.out.print(arr[i] + " "); } } } Sample Output Input:7 9 8 6 3 4 7 2 Output: After wave sort 9 6 8 3 7 2 4
|
|
| 10. |
You are given a sorted array of integers. It is given that each element in the array is unique. |
|
Answer» You have to find the index where the element is located in the array. If it is not located in the array, you have to return the index at which it should be inserted in the array so that the array remains sorted. You can’t use extra space and the expected time complexity is O(log2N) where N is the number of elements in the array. Since the array is sorted, we will use Binary Search to find the element. If the element is not found, the index at which we insert an element is always the ceil Index. So, what is the ceil index? At the end of the binary search, ceil index is where the low (or left) pointer points. So, the code for the same is shown below. Java Code to Search Element/Insert Position import java.util.*;class Main { public static int ceilIndex(int[] nums, int target) { int lo = 0; int hi = nums.length-1; while(lo <= hi) { int mid = lo + (hi-lo)/2; if(nums[mid] == target) { return mid; } else if(nums[mid] < target) { lo = mid + 1; } else { hi = mid - 1; } } return lo; //ceil } public static int search(int[] nums, int target) { //insert position is actually the ceil of the element return ceilIndex(nums,target); } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = scn.nextInt(); } int target = scn.nextInt(); System.out.println(search(arr,target)); } } Sample Output When the element is present in the array Input:4 1 3 5 6 5 Output: 2 When the element is not present in the array Input:4 1 3 5 6 4 Output: 2
|
|
| 11. |
You are given 2 strings as input. You have to check whether they are anagrams or not. |
|
Answer» Anagrams are those strings that have the same characters occurring an equal number of times in both the strings. However, the order can be different. For example “anagram” and “nagrama” are Anagrams. We will use HashMap to store the frequency of each character of the first string. Then, we will traverse the second string and keep on decrementing the frequency in the HashMap. If for any character in the second string, either the character is not present in the HashMap or its frequency is already 0, we will return false. Else, if we have scanned the entire second String and there are no discrepancies, the two strings will be anagrams. Java Code to check Anagrams import java.util.*;class Main { public static boolean isAnagram(String s1, String s2) { if(s1.length() != s2.length()) return false; HashMap<Character,Integer> fmap = new HashMap<>(); for(int i=0;i<s1.length();i++) { int ofreq = fmap.getOrDefault(s1.charAt(i),0); fmap.put(s1.charAt(i),ofreq+1); } for(int i=0;i<s2.length();i++) { if(!fmap.containsKey(s2.charAt(i)) || fmap.get(s2.charAt(i)) == 0) { return false; } else { int ofreq = fmap.get(s2.charAt(i)); fmap.put(s2.charAt(i),ofreq-1); } } return true; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str1 = scn.nextLine(); String str2 = scn.nextLine(); if(isAnagram(str1,str2)) System.out.println(true); else System.out.println(false); } } Sample Output When the strings are anagrams Input:anagram nagrama Output: true Input: anagram nagrame Output: false
|
|
| 12. |
Add two Binary Strings and return a Binary String as a result. The addition should be performed as per the rules of binary addition. |
|
Answer» So, the question is basically to add 2 binary numbers given in the form of strings. We should know the basic rules of binary addition: 0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 0 and Carry = 1 This shows that whenever the result exceeds 1, the answer of addition becomes 0 and carry becomes 1. So, using these rules, we will add 2 binary strings starting from their LSBs i.e. from the last index of each string moving towards the first index. Java Code for Binary Addition of Strings import java.util.*;class Main { public static String add(String a, String b) { String ans = ""; if(a.equals("0") && b.equals("0")) return "0"; int i = a.length() -1; int j = b.length() -1; int ca = 0; while(i >=0 || j>=0 || ca >0) { int d1 = (i >= 0) ? (a.charAt(i) - '0') : 0; int d2 = (j >= 0) ? (b.charAt(j) - '0') : 0; int digit = 0; if(d1 + d2 + ca >= 2) { digit = (d1 + d2 + ca) % 2; ca = (d1 + d2 + ca) / 2; } else { digit = d1 + d2 + ca; ca = 0; } i--; j--; ans = digit + ans; } return ans; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String a = scn.nextLine(); String b = scn.nextLine(); System.out.println("The sum is: " + add(a,b)); } } Sample Output Input:1 0111 Output: The sum is: 1000
|
|
| 13. |
A sentence is said to be a palindrome if we convert all its alphabets to lowercase, include the numerics but exclude all the spaces, whitespaces, and other special characters and it reads the same from left to right and right to left. |
|
Answer» For instance, consider the following sentence: “2 Race, e cAr 2”. This sentence will be converted to “2raceecar2”. The string is a palindrome, hence this sentence is a palindrome. You have to take a sentence input from the user and print “true” if it is a palindrome, or else print “false”. A sentence is said to be a palindrome if we convert all its alphabets to lowercase, include the numerics but exclude all the spaces, whitespaces, and other special characters and it reads the same from left to right and right to left. So, the approach is pretty simple. We convert the sentence into a string by including all the alphanumeric characters and excluding all the other characters. The alphabets will be included only in their lowercase format. Then, we simply have to check whether a string is a palindrome or not. For this, we keep a pointer “lo” at the beginning of the string and a pointer “hi” at the end of the string. We keep incrementing lo and decrementing hi while checking whether the characters at these indices are equal or not. If at any place, we find that the characters are not equal, the string is not a palindrome. If lo becomes greater than hi and the characters at lo and hi were the same throughout, the string is a palindrome. Java Code to check Palindromic Sentence import java.util.*;class Main { public static boolean isStrPalindrome(String str) { int lo = 0; int hi = str.length()-1; while(lo < hi) { char ch1 = str.charAt(lo); char ch2 = str.charAt(hi); if(ch1 != ch2) return false; lo++; hi--; } return true; } public static boolean isSentencePalindrome(String s) { String res = ""; for(int i=0;i<s.length();i++) { char ch = s.charAt(i); if((ch >='a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >='0' && ch<='9')) { if(ch >='A' && ch <= 'Z') res += (char)(ch + 32); else res += ch; } else continue; } if(isStrPalindrome(res)) return true; return false; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String sentence = scn.nextLine(); if(isSentencePalindrome(sentence)) System.out.println(true); else System.out.println(false); } } Sample Output When the sentence is a palindrome Input: 2 Race, e cAr 2Output: true When the sentence is not a palindrome Input: 2 Race, a cAr 2Output: false
|
|