Coding is an integral part of any programming language. It is the most important phase of an interview. Interviewee checks the capability of thinking of any particular. I think one should never be hired without testing coding skill. Most of the tech giants like Google, Amazon, and Facebook highly test the coding skill of the developer they hire. Some companies like Amazon, filter the developer who can code by their pre-online test of coding.
Coding is an art that shows the creativity level of any developer. Most of the time, interviewee follows the following schema for technical round.
- They will give you output and tell you to create a program for that particular output.
- They will give you the pattern or string to print.
- They will give you an algorithm.
- They will give you any mathematical formula or problem.
Coding is like art and creativity. I will suggest you have a comprehensive study of data structure and algorithm.
In this tutorial, I have tried to pull out the most important questions and their answers for the interview. But you should have more practice on these problems and other similar problem because coding is not just remembering the things.
Some most important java programming/ coding interview questions-
Let’s have a look at some questions for the technical round in interview-
Question 1: what are OOPs concepts in Java?
Answer-the term OOP stands for object-oriented programming. These concepts are the main ideas for making java a secure and object-oriented programming language. These concepts are
- Class
- object
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Question 2: Explain the final keyword in java.
Answer- Final is a non-access modifier. It is used in different context like
- Final Variable
- Final Methods
- Final classes
Final variable-
- If a variable is declared with final keyword, it is called the final variable.
- Its value can’t be modified.
- A final variable should be initialized.
- We can re-assign value to a normal variable, but we cannot change the value of a final variable once assigned.So we use the final variable for the values we want to remain constant throughout the program.
E.g. –
class Car{
finalintspeed=120;//final variable
void run(){
speed=250;
}
publicstaticvoid main(String args[]){
Car c1=new Car();
c1.run();
}
Output- compile time error.
Final method-
- When a method declared with final keyword it is called final method.
- Final methods can’t override.
- We declare methods as final for required to follow the same implementation throughout all the derived classes.
e.g.
class Car{
finalvoid run()
{
System.out.println("speed is 120km/h");}
}
class Suzuki extends Car{
voidrun()
{
System.out.println("speed is 200km/h");
}
publicstaticvoid main(String args[]){
Suzuki s1= new Suzuki();
Suzuki.run();
}
}
Output- compile time error
Finalclass-
- A class declared with final keyword is known as final class.
- We cannot inherit a final class.
- A final class is created to prevent the class be inherited and making it immutable.
finalclass X
{
// methods and fields
}
class Y extendsX
{
// methods and fields
}
Output- compile time error.
Question 3: Does java support multiple inheritance, explain?
Answer- Java doesn't support multiple inheritance through classes, but It can be achieved through interfaces. Multiple inheritance has some conflict like
diamond problem that is why java developers excluded this feature from java.
some other languages like c++, common lisp support multiple inheritance, but java avoids it. It prevents multiple inheritance to avoid ambiguity.
Question 4: Explain diamond problem in java.
Answer-
The diamond problem-The following diagram and program will clear the image of the diamond problem.
classA
{
void m1()
{
System.out.println("class A");
}}
classBextends A
{
void m1()
{
System.out.println("Class B");
}
}
class C extends A
{
void m1()
{
System.out.println("Class C");
}
}
class Test extends A, B
{
publicstaticvoid main(String args[])
{
Test d1 = new Test();
d1.m1();
}
}
Output- this program will produce compile time error.
As we can see in the above program on calling method m1() using D class object will cause complication. The program got confused whether it calls A's method m1() or B's method m1() because class D inheriting both class A and B. this complication is called diamond problem.
Question 5: Explain statement System.out.println(), describe every word of this statement in JAVA.
Answer-This is the print statement in the Java programming language. It prints the arguments passed in system.out which is generally called sysout. It is also the most compiled statement in the history of java. Let’s understand the meaning of this statement.
The system is a final class of the package
java.lang, the
out is a static member of the System class
, and the
printlnis a method of
java.io.PrintStream.
out is also an instance of java.io.PrintStream.
Question 6- what is the super keyword in java?
Answer-Super is a reference variable that refers to the parent class object. Super keyword uses inheritance, so for understanding super keyword in java, one should have understood the concept of inheritance.
Super can be used in the following context.
- Use of super with variables
- Use of super with methods
- Use of super with constructors
Use of super with variables-
It is used if a child class and parent class have same data members, in this case ambiguity may occur for JVM. Let’s have a look on following example.
class X{
String color= "red";}
class Y extends X{
String color="black";
void printColor()
{
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1{
publicstaticvoid main(String args[]){
Y obj= new Y();
obj.printColor();
}
}
Output-
black
red
In this example, we have used the super keyword for accessing the parent class variable.
Use of super with methods-
It is used if a parent and child class have the same method.
class Car{
void speed(){System.out.println("speed is 120 km/h");}
}
class Alto extends Car{
void average(){System.out.println("40 km/ltr");}
void work(){
super.speed();
average();
}
}
class TestSuper2{
publicstaticvoid main(String args[]){
Alto d=new Alto();
d.work();
}}
Output-
speed is 120 km/h
40 km/ltr
Use of super with constructor-
In case of constructor, super is also used for accessing the parent class constructor. Super can call parametric as well as non-parametric constructor. Let’s have a look on following example-
class Vehicle{
Vehicle()
{System.out.println("Vehicle has Designed");}
}
class Model extends Vehicle{
Model(){
super();
System.out.println("Latest model has launched");
}
}
class TestSuper3{
publicstaticvoid main(String args[]){
Model m=new Model();
}}
Output-
Vehicle has Designed
Latest model has launched
Question 7:What is the output of following statement?
String s1 = "abc";
String s2 = "abc";
System.out.println("s1 == s2 is:" + s1 == s2);
Answer- In java,‘+’ operator precedence is more than ‘==’ operator. So the given expression will be evaluated to abc” == “abc” i.e false.
So the output will be "false".
Question 8: what is the output of the following statement?
public class Test {
public static void main(String[] args) {
try {
throw new IOException("Hello");
}catch(IOException | Exception e) {
System.out.println(e.getMessage());
}
}
}
Answer- It will produce a compile time error like “
The exception IOException already caught by an alternative exception”.
Question 9: Write a program to print Fibonacci series.
In this series, the next number is the sum of the previous two numbers.
Example
This is the first 11 numbers Fibonacci series- 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc
As the series limit of the series will increase, it will continue in this pattern.
0 and 1 always be the first two number of the series.
Answer-
importjava.util.Scanner;
class Fibonacci{
publicstaticvoid main(String args[])
{
intn1=0,n2=1,n3,i,num=10;
System.out.print(n1+" "+n2);
for(i=2;i<num;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Output-
0 1 1 2 3 5 8 13 21 34
Question 10: Write a java program to check the given number is Armstrong or not.
Answer-
An Armstrong number is the cubic sum of its digits.
Example- 0, 153, 370, 371, 407…. Etc.
153= (1*1*1) + (3*3*3) + (5*5*5)=1+125+27=153
Let’s see the java program to check the number whether it is Armstrong or not.
publicclassArmStrong {
publicstaticvoid main(String[] args) {
intnumber=372, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + ":it’s an armstrong.");
else
System.out.println(number + ":it’s not an Armstrong number.");
}
}
Output-
372 : it's not an Armstrong number.
Question 11-Write a java program to swap two numbers
Answer- In this program, I have used the
Scannerclassfor command line argument. I have assigned the value of ‘a’ in a third variable (temp) and the value of b in ‘a’, again assign the value of y in a third variable.
Required program is-
importjava.util.Scanner;
publicclassSwapNumber {
publicstaticvoid main(String[] args) {
inta, b, temp;
System.out.println("Enter the numbers for swapping");
Scanner in = new Scanner(System.in);
a= in.nextInt();
b = in.nextInt();
System.out.println("Before Swapping: " + a + b);
temp = a;
a = b;b = temp;
System.out.println("After Swapping:" + a + b);
}
}
Output-
Enter the numbers
25
45
Before Swapping: 2545
After Swapping:4525
Here values of the number are user values you can take any other numbers for swapping.
Question 12: Write a Java Program to count the number of words in a string with the help of HashMap.
Answer- It is a collection class program. Firstly I have used a split function so that string can split into multiple words, after that I have declared HashMap and iterated using for loop.
The required program is-
import java.util.HashMap;
publicclass WordCount {
publicstaticvoid main(String[] args) {
String str = "aayega to modi hi aayega to modi hi";
String[] split = str.split(" ");
HashMap<String,Integer>map = new HashMap<String,Integer>();
for (inti=0; i<split.length-1; i++) {
if (map.containsKey(split[i])) {
intcount = map.get(split[i]);
map.put(split[i], count+1);
}
else {
map.put(split[i], 1);
}
}
System.out.println(map);
}
}
Output-
{hi=1, aayega=2, modi=2, to=2}
Question 13:Write a Java Program to take a number from user and check thatthe number is prime or not.
Answer-
import java.util.Scanner;
publicclass Prime {
publicstaticvoid main(String[] args) {
inttemp, n;
System.out.println(" Enter the number for checking-");
booleanisPrime = true;
Scanner sc = new Scanner(System.in);
n= sc.nextInt();
for (inti = 2; i<= n/2; i++) {
temp = n%i;
if (temp == 0) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(n + ": it is a prime number");
else
System.out.println(n + ":it is not a prime number");
}
}
Output-
Enter the number for checking-
5
5:it is a prime number
Question 14-Write a Java Program to find whether a string or number is palindrome or not.
Answer-
I have used reverse string program for checking the number/string palindrome or not with the use of if-else statement. If the string equals to reverse string then number is palindrome, otherwise not.
import java.util.Scanner;
publicclass Palindrome {
publicstaticvoid main (String[] args) {
String a, reverse = "";
Scanner in = new Scanner(System.in);
intlength;
System.out.println("Enter the number or String");
a = in.nextLine();
length = a.length();
for (inti =length -1; i>=0; i--) {
reverse = reverse + a.charAt(i);
}
System.out.println("reverse is:" +reverse);
if(a.contentEquals(reverse))
System.out.println(" Given number is palindrome");
else
System.out.println(" number is not a palindrome");
}
}
Output-
Enter the number or String
12321
reverse is:12321
Given number is palindrome
Or for string
Enter the number or String
armaan
reverse is:naamra
number is not a palindrome
Question 15: Write a program to remove all the white spaces in a string.
Answer-
I have used replaceAll() method for this program, and It will remove all the white spaces in a string. The required program is-
publicclass RemoveWs {
publicstaticvoid main(String[] args)
{
String s = "India is best";
String s1 = s.replaceAll("\\s", "");
System.out.println(s1);
}
}
Output-
Indiaisbest
Question 16: Write a java program that prints the number from 1 to 30 but the multiples of 3 prints “Nice”, multiples of 5 prints “pic” and multiples of both 5 and 3 prints "nice pic dear."
Answer-required program is-
publicclass NicePic{
publicstaticvoid main(String args[])
{
inti;
for(i=0;i<=30;i++)
if(i%(3*5)==0)
System.out.println(i+"-nice pic dear");
elseif(i%5==0)
System.out.println(i+"-pic");
elseif(i%3==0)
System.out.println(i+"-nice");
}
}
Output-
0-nice pic dear
3-nice
5-pic
6-nice
9-nice
10-pic
12-nice
15-nice pic dear
18-nice
20-pic
21-nice
24-nice
25-pic
27-nice
30-nice pic dear
Question 17: Write a java program to find the square root of a number with math.sqrt() function and without using math.sqrt() function.
Answer-
With the use of math.sqrt()-
In the following program, we have to use the predefined method
math.sqrt() of JDK.
import java.util.Scanner;
publicclassSqrt {
publicstaticvoid main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number : ");
doublesquare = scanner.nextDouble();
doublesquareRoot = Math.sqrt(square);
System.out.printf("Square root of number: %f is : %f %n" , square, squareRoot);
}
}
Output-
Enter the number :
121
Square root of number: 121.000000 is : 11.000000
Without using math.sqrt-
In the following program, we have to add a method called squareRoot() for obtaining the square root of any number. In the squareRoot() method, we have described the process for finding the square root.
import java.util.Scanner;
publicclass Sqrt2 {
publicstaticdouble squareRoot(intnumber) {
doubletemp;
doublesr = number / 2;
do {
temp = sr;
sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);
returnsr;
}
publicstaticvoid main(String[] args)
{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
intnum = scanner.nextInt();
scanner.close();
System.out.println("Square root of "+ num+ " is: "+squareRoot(num));
}
}
Output-
Enter any number:121
Square root of 121 is: 11.0
Question 18:Write a java program to find the factorial of a number.
Answer-
Required program is-
import java.util.Scanner;
publicclass Fact {
publicstaticvoid main(String[] args){
Scanner in = newScanner(System.in);
System.out.println("Enter the number: ");
intn = in.nextInt();
intf =1;
for(inti=n; i>0; i--){
f = f*i;
}
System.out.println("Factorial of "+n+" is "+f);
}
}
Output-
Enter the number:
6
Factorial of 6 is 720
Question 19: Write a java program for Binary search.
Answer-
Binary search-
Binary search is a popular algorithm for searching elements from an array. It is efficient and most commonly used the searching algorithm. It works on an already sorted set of the elements of an array. To use the binary search, be assured that the collection set is sorted.
- It is a fast search algorithm
- It is based on divide and conquers.
- Data items should be in sorted order
In the binary search, the number of operation can be reduced based on the value that is being searched.
Let's have a look at the following array-
Linear search will determine the position of 4 in 5
th iteration while binary search reduced the number of iteration. Let’s see-
We have starting and ending point say low (l) and high (h).
l=0;
h=n-1;
left=0 right=5
Arr
item=2 mid=2
A[mid]=2
In the given array lower bound is 0 and the upper bound is 5, and the median of given array is 2.
First, we compare elements and will follow the below process.
Here value (v) = 4.
If v=A[mid]
Return mid
If v>A[mid]
Low=mid+1
else high=mid-1
Return nill.
In simple language-
- Compare v with the mid.
- If v matches with mid, we return the mid index.
- Else If v is higher than the mid element, then v can only lie in right half subarray after the mid element. So we come back for the right half.
- Else (v is smaller) recur for the left half.
Java program for binary search-
import java.util.Arrays;
import java.util.Scanner;
publicclass Searching {
publicstaticvoid main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");//it should be zero otherwise it will throw exception
intsize = sc.nextInt();
int[] array = newint[size];
System.out.println("Enter the Array Elements: ");
for(inti=0; i<size; i++){
array[i] = sc.nextInt();
}
System.out.println("Enter the element for searching: ");
ints = sc.nextInt();
Arrays.sort(array);
intf, l, m;
f=0;
l = size-1;
m = (f+l)/2;
inti=0;
for(; i<size; i++){
if(s>array[m]){
f = m+1;
}elseif(s<array[m]){
l = m-1;
}else{
printArray(array);
System.out.println("Element "+s+" found in the array.");
break;
}
m= (f+l)/2;
}
if(i==size){
printArray(array);
System.out.println("Element "+s+" is not found in the array");
}
}
publicstaticvoid printArray(int[] a){
System.out.println("Array of elements: ");
System.out.print("{");
for(inti:a){
System.out.print(i+",");
}
System.out.println("}");
}
}
Output-
Enter the size of the array
5
Enter the Array Elements:
5
7
6
4
9
Enter the element for searching:
5
Array of elements:
{4,5,6,7,9,}
Element 5 found in the array.
Question 20: write a java program for Bubble sort algorithm.
Answer-
Bubble sort- It is the most straightforward sorting algorithm. It merely compares with its neighbor element if they are in the wrong order then swaps them repeatedly.
Have a look at the following example-
e.g.
first pass-
A[0]<A[1]
array will remain unchanged because it is in right order.
A[1]<A[2]
Array will not change.
A[2]<A[3]
Array will not change.
A[3]>A[4]
Swap both
A[4]>A[5]
Swap both
Second pass-similarly we compare in the second pass and follow this technique until we didn't get sorted array.
A[2]>A[3]
Swap A[2] and A[3].
This is the sorted array.
Java program for bubble sorting-
import java.util.Scanner;
publicclassBubbleSort {
publicstaticvoid main(String []args) {
intnumber, i, j, swap;
Scanner sc = newScanner(System.in);
System.out.println("enter the number to sort");
number = sc.nextInt();
intarray[] = newint[number];
System.out.println("Enter " + number + " integers");
for (i = 0; i<number; i++)
array[i] = sc.nextInt();
for (i = 0; i< ( number - 1 ); i++) {
for (j = 0; j<number - i - 1; j++) {
if (array[j] >array[j+1]) /* For descending order use < */
{
swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}
}
}
System.out.println("Sorted numbers:");
for (i = 0; i<number; i++)
System.out.println(array[i]);
}
}
Output-
enter the number to sort
6
Enter 6 integers
0
1
3
5
2
4
Sorted numbers:
0
1
2
3
4
5