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 to show a single thread in Java. |
|
Answer» Java Program to show Single Thread public class Main {public static void main(String[] args) { Thread t = Thread.currentThread(); t.setName("My Main Thread"); t.setPriority(7); System.out.println(t); System.out.println(t.getName()); System.out.println(t.getPriority()); } } Output Thread[My Main Thread,7,main]My Main Thread 7 |
|
| 2. |
Write a program in Java to show a basic “divide by 0 exception”. |
|
Answer» Divide by zero exception occurs when we try to divide a number by 0 in Java. Following is the program showing divide by 0 exception. import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); System.out.println("Dividing this number by 0"); try { System.out.println(n/0); } catch(Exception e) { System.out.println(e); } System.out.println("Program completed"); } } Output Input: 3Output: Dividing this number by 0 java.lang.ArithmeticException: / by zero Program completed Important: In this question, we used the try and catch block for handling the divide by 0 exception. Hence, the complete execution of the program took place. Otherwise, the program would have stopped at the exception, and “Program completed” would not have been printed. |
|
| 3. |
Write a program in Java to show inheritance in Java. |
|
Answer» This program is for testing the concepts of inheritance in Java and the usage of extends keyword. Following is an example program in which a class SmartPhone extends a class Phone. This is a real-life example as a phone has basic features of calling and messaging whereas a smartphone has several other features like clicking pictures, playing music, etc. Java Code for showing Inheritance class Phone {private int number; Phone() { } void setNumber(int number) { this.number = number; } int getNumber() { return number; } public void call() { System.out.println("Call is made"); } public void message() { System.out.println("Message is sent"); } } class SmartPhone extends Phone { int cameraMegaPX; public void click() { System.out.println("A photograph was clicked"); } public void playMusic() { System.out.println("Music Started Playing"); } public void pauseMusic() { System.out.println("Music Paused"); } public void stopMusic() { System.out.println("Music Stopped"); } } class Main { public static void main(String args[]) { // Your code goes here SmartPhone p1 = new SmartPhone(); p1.setNumber(9863472); System.out.println("Phone number is: " + p1.getNumber()); p1.call(); p1.playMusic(); } } Sample Output Phone number is: 9863472Call is made Music Started Playing |
|
| 4. |
Write a class “Programmer”. Give some properties and methods to it and show how you will access them in the main method by creating object(s) of this class. |
|
Answer» The following is the example code. Java Code for Custom Class import java.util.*;class Programmer { private int age; private String name; Programmer() { } Programmer(int age, String name) { this.age = age; this.name = name; } void setAge(int age) { this.age = age; } void setName(String name) { this.name = name; } int getAge() { return age; } String getName() { return name; } public void codes() { System.out.println(this.name + " writes codes"); } public void drinksCoffee() { System.out.println(this.name + " drinks coffee and can then convert exponential complexity codes to polynomial"); } } class Main { public static void main(String args[]) { // Your code goes here Programmer p1 = new Programmer(22,"Guneet"); p1.codes(); p1.drinksCoffee(); } } Sample Output Guneet writes codesGuneet drinks coffee and can then convert exponential complexity codes to polynomial.
|
|
| 5. |
Write a program in Java to print the elements of the matrix in Wave Order as shown below. (The matrix can have different numbers of rows and columns). |
|
Answer» It is clear from the image itself that we are traversing column-wise. Now, when we traverse an even column, we traverse it from top to bottom and when we traverse an odd column, we traverse it from bottom to top direction. Code for Wave Print a Matrix in Java import java.io.*;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 m = scn.nextInt(); int[][] mat = new int[n][m]; //input the matrix for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { mat[i][j] = scn.nextInt(); } } for(int j=0;j<mat[0].length;j++) { if(j% 2 == 0) { for(int i=0;i<mat.length;i++) { System.out.print(mat[i][j] + " "); } } else { for(int i=mat.length-1;i>=0;i--) { System.out.print(mat[i][j] + " "); } } System.out.println(); } } } Sample Output Input:1 2 3 4 5 6 7 8 9 Output: 1 4 7 8 5 2 3 6 9
|
|
| 6. |
Write a program in Java to input an NxN matrix and display it row-wise and column-wise. |
|
Answer» Simply input the matrix. Now, display the matrix row-wise by starting from the first row and moving to the next elements within the same row. For displaying column-wise, start from the first column and keep moving in the same column to the next elements. This is shown below. Java Code to input and display 2-D Matrix import java.util.*;class Main { public static void main(String args[]) { // Your code goes 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(); } } //Display Row wise for(int i=0;i<N;i++) { System.out.print("Row " + i + " : "); for(int j=0;j<N;j++) { System.out.print(mat[i][j] + " "); } System.out.println("\t"); } System.out.println(); //Display Col wise for(int j=0;j<N;j++) { System.out.print("Col " + j + " : "); for(int i=0;i<N;i++) { System.out.print(mat[i][j] + " "); } System.out.println("\t"); } } } Sample Output Input:3 1 2 3 4 5 6 7 8 9 Output: Row 0 : 1 2 3 Row 1 : 4 5 6 Row 2 : 7 8 9 Col 0 : 1 4 7 Col 1 : 2 5 8 Col 2 : 3 6 9
|
|
| 7. |
Write a program to find the index of first occurrence and last occurrence of an element in the array in a single iteration. |
|
Answer» You cannot use extra space. The first index of occurrence and the last index of occurrence will be -1, if the element is not present inside the array. We will keep three variables. The 2 variables (that are) firstIndex and lastIndex will be initialized to -1. The third will be a boolean type variable found which will be initially false. If the element is found, we will make it true, and store the current index in firstIndex and lastIndex variables. If the element is found further, only the lastIndex variable will change. The fact that the number has already been found in the array will be denoted by the found boolean variable. Java Program to find the First and Last Occurrence of an element in the Array import java.util.*;class Main { 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]; // input the array for(int i=0;i<n;i++) { arr[i] = scn.nextInt(); } int target = scn.nextInt(); int fIndex = -1, lIndex = -1; boolean found = false; for(int i=0;i<n;i++) { if(arr[i] == target) { if(!found) { fIndex = i; lIndex = i; found = true; //found for the first time } else { lIndex = i; } } } if(found == false) { System.out.println("The element does not exist in the array"); } else { System.out.println("First Index = " + fIndex + " Last Index = " + lIndex); } } } Sample Output When element exists Input:5 1 2 3 2 5 2 Output: First Index = 1 Last Index = 3 When the element does not exist Input:5 1 2 3 2 5 2 Output:The element does not exist in the array.
|
|
| 8. |
Write a program in Java to Reverse an Array without using extra space. |
|
Answer» We keep to variables i and j at both the ends of the array as shown below.
Now, swap the element at index i with the element at index j increment the i variable, and decrement the j variable. Keep doing this till i is less than j. This is shown in the image below. import java.util.*;class Main { 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(); } System.out.println("The reversed array is"); int i = 0; int j = arr.length - 1; while(i < j) { //swapping ith and jth index elements int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } //displaying the array for(int it=0;it<arr.length;it++) { System.out.print(arr[it] + " "); } } } Sample Output Input:5 1 2 3 4 5 Output: The reversed array is 5 4 3 2 1
|
|
| 9. |
Write a program in Java to prove that the strings are immutable in Java. |
|
Answer» Strings are immutable in Java. This can be proven by making changes to a string and comparing them with the == operator. Since this operator compares only the references, i.e. the addresses of the objects, it will be able to tell us if the changes are made to the same object or not. If after making changes to a string we compare it by == and we get no equals, this means that the strings are immutable. Java program to prove Strings are Immutable class Main {public static void main(String args[]) { // Your code goes here String s1 = "InterviewBit"; String s2 = s1; System.out.println(s1 == s2); //they are equal s1 += "Scaler"; System.out.println(s1 == s2); //not equal } } Output truefalse So, let us now discuss an array of programs related to Java interviews. |
|
| 10. |
Write a program to print all the unique characters in a String. For instance, if the input string is “abcb”, the output will be the characters ‘a’ and ‘c’ as they are unique. The character ‘b’ repeats twice and so it will not be printed. |
|
Answer» We can use a HashSet in order to store the characters of the String. When we arrive at a character in the String, if it is already present in the HashSet, we remove it from the HashSet as that character is not unique. If it is not present inside the HashSet, we add it to it. After traversing the entire string, we print the elements inside the HashMap. Java Code to Print All Unique Characters in a String. import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str = scn.nextLine(); HashSet<Character> unique = new HashSet<>(); for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(unique.contains(ch) == true) { //this character has already occured unique.remove(ch); } else { unique.add(ch); } } if(unique.size() == 0) { System.out.println("There are no unique characters"); } for(Character ch : unique) { System.out.print(ch + " "); } } } Sample Output Input: abcabOutput: c
|
|
| 11. |
Write a program in Java to count the total number of vowels and consonants in a String. The string can contain all the alphanumeric and other special characters as well. However, only the lowercase English alphabets are allowed in the String. |
|
Answer» We just have to traverse the string. If we get any vowel (a,e,i,o,u), we increment the variable corresponding to the vowel count and if we get a consonant, we increment the variable corresponding to the consonant count. Java Code to Count Vowels and Consonants in a String import java.util.*;class Main { public static boolean isVowel(char ch) { if(ch == 'a' || ch =='e' || ch =='i' || ch =='o' || ch =='u') return true; return false; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str = scn.nextLine(); int vowelCount = 0; int consCount = 0; for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(isVowel(ch) == true) vowelCount++; else if(ch >='a' && ch<='z' && isVowel(ch) == false) consCount++; } System.out.println("Number of vowels are: " + vowelCount); System.out.println("Number of consonants are: " + consCount); System.out.println("Number of other characters are: " + (int)(str.length() - vowelCount -consCount)); } } Sample Output Input: ae#zyu*Output: The number of vowels is: 3 The number of consonants is: 2 The number of other characters is: 2
|
|
| 12. |
Write a program in Java to Toggle the case of every character of a string. For instance, if the input string is “ApPLe”, the output should be “aPplE”. |
|
Answer» We know that in Java, we cannot make changes to the same string as it is immutable. So, we have to return a new String. The lowercase ASCII characters differ from the uppercase ASCII characters by 32. This means ‘a’ - 32 = ‘A’. So, we will use this concept to Toggle the String cases. Java Code to Toggle Cases import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str = scn.nextLine(); StringBuilder res = new StringBuilder(""); for(int i=0;i<str.length();i++) { char ch = str.charAt(i); //current character if(ch >='A' && ch <= 'Z') { res.append((char)(ch + 32)); } else if(ch >='a' && ch<='z'){ res.append((char)(ch - 32)); } else { res.append(ch); } } String ans = res.toString(); System.out.println("The string after toggling becomes: " + ans); } } Sample Output: Input: Ab#$CdOutput: aB#$cD
|
|
| 13. |
Write a program in Java to calculate pow(x,n) using recursion. The expected time complexity is O(log2N) where N is the power. You cannot use any extra space apart from the recursion call stack space. |
|
Answer» We have seen how we can calculate the pow(x,n) in linear time. We can optimize our approach by changing the recurrence relation. Let us understand this with the help of an example shown below: So, we can see that if the power is even, we can divide the power by 2 and can multiply x to the power n/2 by itself to get our answer. What if the power of the number is odd? In that case, we multiply the number x once to the term x to the power n/2 multiplied by itself. Here, n/2 will be the floor value of (n/2). You can verify this for any pair of x and n. So, doing this will reduce the time complexity from O(N) to O(log2N). This happens because of the change in recurrence relation and the recursion tree as shown below. Solving these recurrence relations gives us the respective time complexities. So, the code for O(log2N) approach is shown below Java Code for (x to the power N) in Logarithmic Time Complexity import java.util.*;class Main { public static double power(double x, int n) { if(n == 0) return 1.0; double xpnby2 = power(x,n/2); //xpnby2 = x power n by 2 if(n % 2 == 0) return xpnby2 * xpnby2; //if power is even return x * xpnby2 * xpnby2; //if power is odd } public static double pow(double x, int n) { if(n < 0) { return 1.0 / power(x,-n); } return power(x,n); } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); double x = scn.nextDouble(); int n = scn.nextInt(); System.out.println(pow(x,n)); } } Sample Output:
1.10 3 Output: 1.3676310000000003
1.110 -3 Output: 0.7311913813009502
|
|
| 14. |
Write a Java Program to calculate xn (x to the power n) using Recursion. You can use O(N) time but can’t use any extra space apart from the Recursion Call Stack Space. |
|
Answer» In a recursive function, we need to find a relation between the smaller problem and the larger problem. Here, we have a clear mathematical relationship between the large problem xn and the problem that is smaller than it i.e. x to the power (n-1). The relation is: xn = x * xn-1{"detectHand":false}The relation is: (x to the power n) = x * x to the power(n-1) In terms of programming (using functions), we can write this relation as: power(x,n) = x * power(x,n-1) For example, 2 to the power 5 = 32. This can be calculated as 2 * (2 to the power 4) = 2 * 16 = 32. So, we have found the recurrence relation in the above equation. Now, what will be the base case? The base case will be the smallest such problem that we can solve. So, the smallest problem is calculating the power of 0 to any number. We know that any number to the power 0 gives the result as 1. So, this will be our base case. Now, let us write the code for the same. Java Code to Calculate x to the power n import java.util.*;class Main { public static double power(double x, int n) { if(n == 0) return 1.0; double xpnm1 = power(x,n-1); //x power n-1 (xpnm1) return x * xpnm1; } public static double pow(double x, int n) { if(n < 0) { return 1.0 / power(x,-n); } return power(x,n); } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); double x = scn.nextDouble(); int n = scn.nextInt(); System.out.println(pow(x,n)); } } Sample Output:
1.10 3 Output: 1.3676310000000003
1.110 -3 Output: 0.7311913813009502
|
|
| 15. |
Write a program in Java to calculate the number of times a digit ‘D’ appears in a number N. You have to take N and D as inputs from the user. |
|
Answer» This is the follow-up question to the previous question. In the previous question, we discussed how you can check the value of a digit using the modulus (%) operator. So, we will just use the previous code and in every iteration, we will check whether the digit is “D” or not. If it is D, increment the counter. The program for the same is shown below: Java Code for Calculating Frequency of a Digit D in a Number N import java.util.*;class Main { public static int countDigitFreq(int n,int D) { if(n == 0 && D == 0) return 1; //number 0 has 1 frequency of 0 //if a negative number is entered if(n < 0) n = -n; int counter = 0; while(n != 0) { int digit = n % 10; //calculate the digit if(digit == D) counter++; n = n/10; } return counter; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); //input the number int d = scn.nextInt(); //input the digit int x = countDigitFreq(n,d); System.out.println("The digit " + d + " occurs " + x + " times in " + n); } } Sample Input/Output Input: 142454Output: The digit 4 occurs 3 times in 142454
|
|
| 16. |
Write a program in Java to count the digits in a number. |
|
Answer» Let us consider the number 12345. This is a 5 digit number. The number of digits can be counted as follows: In the image above, we have shown the way of extracting the digits of a number. However, in our questions, we just need to count the digits in the number. So, we have to count the number of times we can divide our input number by 10 before it becomes 0. Let us write the code based on the above algorithm. Java Program to Count the Number of Digits in a Number. import java.util.*;class Main { public static int countDigits(int n) { if(n == 0) return 1; //if a negative number is entered if(n < 0) n = -n; int res = 0; while(n != 0) { n = n/10; res++; } return res; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); //input the number System.out.println("The number of digits in " + n + " are: " + countDigits(n)); } } Output
Output: The number of digits in 1234 is: 4
Output: The number of digits in 0 is: 1
Output: The number of digits in -12345 is: 5
|
|
| 17. |
Write a program in Java to generate the Nth Fibonacci Number using Iteration and Constant Space. |
|
Answer» Fibonacci Series is a series in which the Nth term is the sum of the previous 2 terms i.e. (N-1)th and (N-2)th terms. The first 2 terms of the Fibonacci sequence are always known. They are 0 and 1 respectively. After this, the further terms can be generated as follows: So, in general, we can derive a generic term i.e.
So, let us now write a program to find the Nth Fibonacci Number using iteration. a. Java Program to generate Nth Fibonacci Number using Iteration. import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int a = 0; //0th fibonacci number int b = 1; //1st fibonacci number if(n < 0) { System.out.println("N cannot be negative"); return; } if(n == 0) System.out.println(a); else if(n == 1) System.out.println(b); else { int c = 0; for(int i=2;i<=n;i++) { c = a + b; a = b; b = c; } System.out.println(c); } } } Sample Input/Output: Run Code Input: 7Output: 13
|
|