×

Top 20 Java Programming Coding Interview Questions for 2024

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-
  1. If a variable is declared with final keyword, it is called the final variable.
  2. Its value can’t be modified.
  3. A final variable should be initialized.
  4. 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-
  1. When a method declared with final keyword it is called final method.
  2. Final methods can’t override.
  3. 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-
  1. A class declared with final keyword is known as final class.
  2. We cannot inherit a final class.
  3. 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. Java Multiple Inheritence example 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.  Diamond Problem in Java
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 packagejava.lang, the out is a static member of the System class, and theprintlnis 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-
0 1 2 3 4 5
Linear search will determine the position of 4 in 5th 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
0 1 2 3 4 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-
0 1 3 5 2 4
A[0]<A[1] array will remain unchanged because it is in right order.
0 1 3 5 2 4
A[1]<A[2] Array will not change.
0 1 3 5 2 4
A[2]<A[3] Array will not change.
0 1 3 5 2 4
A[3]>A[4] Swap both
0 1 3 2 5 4
A[4]>A[5] Swap both
0 1 3 2 4 5
 Second pass-similarly we compare in the second pass and follow this technique until we didn't get sorted array.
0 1 3 2 4 5
A[2]>A[3] Swap A[2] and A[3].
0 1 2 3 4 5
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

Related Topics

Top 15 Electron Interview Question for 2024

1) What is Electron? Electron is an open source library developed by Github. It is used to develop cross platform desktop application. 2) Which technology Electron uses? Electron uses Chromium and Node.js with...

3 minutes read.

Top 15 PhantomJS Interview Question for 2024

1) What is PhantomJS? PhantomJS is a lightweight headless scripted browser built on WebKit. It is used for automation web page interaction. 2) Why it is called as headless browser? PhantomJS called as...

4 minutes read.

Top 30 JSF Interview Questions for 2024

1) What is JSF? JSF stands for Java Server Faces is a Java-Based web application framework. JSF (Java Server Faces) provides a facility to connect UI widgets with data sources. 2) What are...

4 minutes read.

Top 31 Dart Programming Interview Questions for 2024

1) What is Dart? Dart is an application programming language. It is used to build web, server and mobile applications. 2) Who is the developer of Dart? Google is the developer of Dart. 3)...

6 minutes read.

Top 30 Sencha Touch Interview Questions for 2024

1) What is Sencha Touch? Sencha Touch is an UI (User Interface) JavaScript library. It is written in JavaScript. It is used to build mobile interface quickly and easily. It works...

6 minutes read.

Top 14 MathML Interview Questions for 2024

1) What is MathML? MathL stands for Mathematical Markup Language. It is extended form of XML. It is used to describe mathematical and scientific notations. 2) Who is the developer of MathML? World...

3 minutes read.

Top 22 MariaDB Interview Question for 2024

1) What is MariaDB? It is a community based database devoloped by MySQL Devolopers. It provides same features as MySQL also, can be said that it is a replacement of MySQL. 2)...

3 minutes read.

Top 30 Ruby on Rails Interview Questions for 2024

1) What is Ruby on Rails? It is a server-side web application framework. It is an open source ruby framework which is used for developing database-backed web applications. Here, no compilation phase is...

4 minutes read.

Ember.js Interview questions

1) What is Ember.js? Ember.js is a JavaScript front-end Framework. It provides developer both features for managing complexity in modern web-apps as well as integrated development kit. 2) Why choose Ember.js? Logical...

2 minutes read.

Top 15 PostgreSQL Interview Questions for 2024

1) What is PostgreSQL? PostgreSQL is a most advance open source database system. PostgreSQL is an object Oriented Relational Database Management System (ORDBMS). PostgreSQL source code is available free of charge...

3 minutes read.

Top 15 ASP.NET MVC Framework Interview Questions for 2024

1) What is ASP.NET MVC Framework? ASP.NET MVC framework is a software architecture pattern for developing web applications. It is used to split the application's implementation logic into three components: models,...

4 minutes read.

Top 25 CoffeeScript Interview Questions for 2024

1) What is CoffeeScript? It is a language that compiles into JavaScript. CoffeeScript is an attempt to expose good parts of JavaScript so, that user can code more easily. 2) Name the...

3 minutes read.

Top 31 PHP Interview Questions for 2024

1) What is PHP? PHP is a object-oriented scripting language, open source, interpreted and executed at server side. It is also used to develop web applications. 2) What are the features of PHP? Features...

4 minutes read.

Top 43 React Native Interview Questions for 2024

1. What is React Native? React native is an open-source JavaScript framework designed by Facebook for native mobile applications development. It is based on a JavaScript library-React. React Native saves your development...

11 minutes read.

Top 30 PyTorch Interview Questions and Answers

Q1: What is PyTorch? Answer: PyTorch is a machine learning library for the programming language Python, based on Torch library, used for application such as natural language processing. It is free...

9 minutes read.

Top 15 NodeJS Interview Questions for 2024

1) What is NodeJs? NodeJs is open source JavaScript based feamework used to develop I/O intensive web application. It is collections of JavaScript library and runtime environment. It is used to...

3 minutes read.

Top 30 Flex Interview Questions for 2024

1) What is Flex? Flex is an open source framework which is used to build applications for mobile, browser and desktop. It provides FLEX SDK consisting of the Flex class library, Flex...

4 minutes read.

Top 30 SASS Interview Questions for 2024

1) What is Sass? SASS: Systematically Awesome Style Sheets is an extension of CSS. It is also known as CSS pre-processor which helps to reduce repetition with CSS and saves time. It is...

4 minutes read.

Top 15 Java Collections Interview Questions for 2024

1) What is Collections in Java? It is a framework which is used to store and manipulate the group of objects. 2) What are the commonly used methods of Collection interface in...

2 minutes read.

Top 15 XHTML Interview Questions for 202

1) What is XHTML? XHTML (Extensible Hyper Text Markup Language) it is similar to the HTML but has some strict rule than HTML. It is said to be HTML defined as...

3 minutes read.