Programming Interview Questions And Answers In Java

Top Programming Interview Questions and Answers In Java

“Programming Interview Questions and Answers In Java”

In an interview whether if you are an fresher or experienced professional you will be judged on one main scale i.e your coding skills. So having a command on your Programming skills is very much important.

Having a confident personality and a good resume is very much important to clear the HR Round. But Technical Interview always revolves around your knowledge so it’s better to brush up your coding knowledge before going for a face to face Interview.

Go through the page in detailed to know more about Programming Interview Questions and Answers In Java.

programming interview questions and answers in java

Programming : Introduction

This page is all about Programming Interview Questions and Answers in Java. Coding can be done in 4 preferred language. You can opt any language according to your convenience. Four languages are:

  1. C
  2. C++
  3. JAVA
  4. Python

This page is all about Programming Interview Questions and Answers In Java”. Go through the page in detailed to know more Interview Questions.

Commonly Asked Programming Interview Questions and Answers In Java

1. Write a Java Program to reverse a string without using String inbuilt function reverse().

Solution:-

There are several ways with which you can reverse your string if you are allowed to use the other string inbuilt functions.

In this method, we are initializing a string variable called str with the value of your given string. Then, we are converting that string into a character array with the toCharArray() function. Thereafter, we are using for loop to iterate between each character in reverse order and printing each character.

public class FinalReverseWithoutUsingInbuiltFunction {
    public static void main(String[] args) {
        String str = "Saket Saurav";
        char chars[] = str.toCharArray(); // converted to character array and printed in reverse order
        for(int i= chars.length-1; i>=0; i--) {
   System.out.print(chars[i]);
    }
  }
}

Output:

varuaS tekaS

2. Why is Java called the ‘Platform Independent Programming Language’?

Solution:-

Platform independence means that the execution of your program does not depend on the type of operating system(it could be any: Linux, Windows, Mac ..etc). To compile code only once and run it on any System (In C/C++, we need to compile the code for every machine on which we run it). Java is both compiler(javac) and interpreter(JVM) based language.

Your java source code is first compiled into byte code using the javac compiler. This byte code can be easily converted to equivalent machine code using JVM. JVM(Java Virtual Machine) is available in all operating systems we install.

Hence, byte code generated by javac is universal and can be converted to machine code on any operating system, this is the reason why java is platform-independent.

3. Armstrong number program in java

Solution:-

A number is called an Armstrong number if it is equal to sum of its digits each raised to the power of number of digits in it.

For example: 153, 371, 407, 9474, 54748 are some Armstrong numbers.

Java Program To Check Whether Given Number Is An Armstrong Number Or Not :

public class MainClass
{
    static void checkArmstrongNumber(int number)
    {
        int copyOfNumber = number;

        int noOfDigits = String.valueOf(number).length();

        int sum = 0;

        while (copyOfNumber != 0)
        {
            int lastDigit = copyOfNumber % 10;

            int lastDigitToThePowerOfNoOfDigits = 1;

            for(int i = 0; i < noOfDigits; i++)
            {
            lastDigitToThePowerOfNoOfDigits = lastDigitToThePowerOfNoOfDigits * lastDigit;
            }

            sum = sum + lastDigitToThePowerOfNoOfDigits;

            copyOfNumber = copyOfNumber / 10;
        }

        if (sum == number)
        {
            System.out.println(number+" is an armstrong number");
        }
        else
        {
            System.out.println(number+" is not an armstrong number");
        }
    }

    public static void main(String[] args)
    {
        checkArmstrongNumber(153);

        checkArmstrongNumber(371);

        checkArmstrongNumber(9474);

        checkArmstrongNumber(54748);

        checkArmstrongNumber(407);

        checkArmstrongNumber(1674);
    }
}
Output :

153 is an armstrong number
371 is an armstrong number
9474 is an armstrong number
54748 is an armstrong number
407 is an armstrong number
1674 is not an armstrong number

 4. Explain public static void main(String args[]) in Java.

Solution:-

main() in Java is the entry point for any Java program.

It is always written as public static void main(String[] args).

  • public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static: It is a keyword in java that identifies it as class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[]: It is the parameter passed to the main method.
5. Write a Java program to print the Fibonacci series up to a given number or create a simple Java program to calculate Fibonacci number

Solution:-

import java.util.Scanner;

/**
 * Java program to calculate and print Fibonacci number using both recursion
 * and Iteration.
 * Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2
 * first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
 *
 * @author Javin
 */
public class FibonacciCalculator {

    public static void main(String args[]) {
    
       //input to print Fibonacci series upto how many numbers
        System.out.println("Enter number upto which Fibonacci series to print: ");
        int number = new Scanner(System.in).nextInt();
      
        System.out.println("Fibonacci series upto " + number +" numbers : ");
        //printing Fibonacci series upto number
        for(int i=1; i<=number; i++){
            System.out.print(fibonacci2(i) +" ");
        }
  
    
    } 
  

    /*
     * Java program for Fibonacci number using recursion.
     * This program uses tail recursion to calculate Fibonacci number 
     * for a given number
     * @return Fibonacci number
     */
    public static int fibonacci(int number){
        if(number == 1 || number == 2){
            return 1;
        }
      
        return fibonacci(number-1) + fibonacci(number -2); //tail recursion
    }
  


    /*
     * Java program to calculate Fibonacci number using loop or Iteration.
     * @return Fibonacci number
     */
    public static int fibonacci2(int number){
        if(number == 1 || number == 2){
            return 1;
        }
        int fibo1=1, fibo2=1, fibonacci=1;
        for(int i= 3; i<= number; i++){
           
            //Fibonacci number is sum of previous two Fibonacci number
            fibonacci = fibo1 + fibo2;             
            fibo1 = fibo2;
            fibo2 = fibonacci;
          
        }
        return fibonacci; //Fibonacci number
      
    }   
  
}
Output:
Enter number upto which Fibonacci series to print:
12
Fibonacci series upto 12 numbers :
1 1 2 3 5 8 13 21 34 55 89 144
 6. How to remove duplicates from an array in place?

Solution:-

import java.util.Arrays;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

/**

 * Java program to remove duplicates from this array. You don't

 * need to physically delete duplicate elements, replacing with null, or

 * empty or default value is ok.

 *

 * @author http://javarevisited.blogspot.com

 */

public class TechnicalInterviewTest {

    private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class);

    public static void main(String args[]) {

        int[][] test = new int[][]{

            {1, 1, 2, 2, 3, 4, 5},

            {1, 1, 1, 1, 1, 1, 1},

            {1, 2, 3, 4, 5, 6, 7},

            {1, 2, 1, 1, 1, 1, 1},};

        for (int[] input : test) {

            System.out.println("Array with Duplicates       : " + Arrays.toString(input));

            System.out.println("After removing duplicates   : " + Arrays.toString(removeDuplicates(input)));

        }

    }

    /*

     * Method to remove duplicates from array in Java, without using

     * Collection classes e.g. Set or ArrayList. Algorithm for this

     * method is simple, it first sort the array and then compare adjacent

     * objects, leaving out duplicates, which is already in the result.

     */

    public static int[] removeDuplicates(int[] numbersWithDuplicates) {

        // Sorting array to bring duplicates together      

        Arrays.sort(numbersWithDuplicates);     

      

        int[] result = new int[numbersWithDuplicates.length];

        int previous = numbersWithDuplicates[0];

        result[0] = previous;

        for (int i = 1; i < numbersWithDuplicates.length; i++) {

            int ch = numbersWithDuplicates[i];

            if (previous != ch) {

                result[i] = ch;

            }

            previous = ch;

        }

        return result;

    }

}

Output :

Array with Duplicates       : [1, 1, 2, 2, 3, 4, 5]

After removing duplicates   : [1, 0, 2, 0, 3, 4, 5]

Array with Duplicates       : [1, 1, 1, 1, 1, 1, 1]

After removing duplicates   : [1, 0, 0, 0, 0, 0, 0]

Array with Duplicates       : [1, 2, 3, 4, 5, 6, 7]

After removing duplicates   : [1, 2, 3, 4, 5, 6, 7]

Array with Duplicates       : [1, 2, 1, 1, 1, 1, 1]
After removing duplicates   : [1, 0, 0, 0, 0, 0, 2]

 7. What are Loops in Java? What are three types of loops?

Solution-

Looping is used in programming to execute a statement or a block of statement repeatedly. 

There are three types of loops in Java:

  • For Loops

For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to the programmer.

  • While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, the condition is checked first before the execution of statements.

  • Do While Loops

Do While Loop is the same as While loop with the only difference that condition is checked after execution of a block of statements.

Hence in the case of the do-while loop, statements are executed at least once.

8. Write a Java Program to swap two numbers using the third variable.

Solution:-

In this example, we have made use of the Scanner class to declare an object with a predefined standard input object. This program will accept the values of x and y through the command line (when executed).

We have used nextInt() which will input the value of an integer variable ‘x’ and ‘y’ from the user. A temp variable is also declared.

Now, the logic of the program goes like this – we are assigning temp or third variable with the value of x, and then assigning x with the value of y and again assigning y with the value of temp. So, after the first complete iteration, the temp will have a value of x, x will have a value of y and y will have a value of temp (which is x).

import java.util.Scanner;

public class SwapTwoNumbers {

public static void main(String[] args) {
// TODO Auto-generated method stub
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping" + x + y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping" + x + y);

}
}

Output:

Enter x and y
45
98
Before Swapping4598
After Swapping9845

9. What is the difference between ‘throw’ and ‘throws’ in Java Exception Handling?

Solution:-

Following are the differences between the two:

  • the throw keyword is used to throw Exception from any method or static block whereas throws are used to indicate which Exception can possibly be thrown by this method
  • If any method throws a checked Exception, then the caller can either handle this exception(using try-catch block )or can re-throw it by declaring another ‘throws’ clause in the method declaration.
  • throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method

Example : 
throw
throw new Exception(“You have some exception”)
throw new IOException(“Connection failed!!”)
throws
throws IOException, NullPointerException, ArithmeticException

10. How to find the largest number less than a given number and without a given digit?

Solution:-

We keep on decrementing the given number by 1 until we get the number that does not contain a given digit. For this, we convert the given number to string ( Integer.toString(i) ) and given digit to character ( char c = Integer.toString(digit).charAt(0) ). And check whether that string contains the character ‘c’ or not ( Integer.toString(i).indexOf(c) ).

If it contains, again we decrement the given number and convert it to string and check whether this string contains the character ‘c’ or not. We will continue this until we get the number that does not contain a given digit.

 public class LargestNumber
{
static int getLLessThanN(int number, int digit)
{
//Converting digit to char

char c = Integer.toString(digit).charAt(0);

//Decrementing number & checking whether it contains digit

for (int i = number; i > 0; --i)
{
if(Integer.toString(i).indexOf(c) == -1)
{
//If 'i' doesn't contain 'c'

return i;
}
}

return -1;
}

public static void main(String[] args)
{
System.out.println(getLLessThanN(123, 2));

System.out.println(getLLessThanN(4582, 5));

System.out.println(getLLessThanN(98512, 5));

System.out.println(getLLessThanN(548624, 8));
}
}

Output :

119
4499
98499
547999

11.  What are constructors in Java?

Solution-

In Java, a constructor refers to a block of code that is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 
  2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.
12.  Write a Java program which will result in deadlock?

Solution-

/**
* Java program to create a deadlock by imposing circular wait.
*
* @author WINDOWS 8
*
*/
public class DeadLockDemo {

/*
* This method request two locks, first String and then Integer
*/
public void method1() {
synchronized (String.class) {
System.out.println(“Aquired lock on String.class object”);

synchronized (Integer.class) {
System.out.println(“Aquired lock on Integer.class object”);
}
}
}

/*
* This method also requests same two lock but in exactly
* Opposite order i.e. first Integer and then String.
* This creates potential deadlock, if one thread holds String lock
* and other holds Integer lock and they wait for each other, forever.
*/
public void method2() {
synchronized (Integer.class) {
System.out.println(“Aquired lock on Integer.class object”);

synchronized (String.class) {
System.out.println(“Aquired lock on String.class object”);
}
}
}
}

13.  Java Program to find the largest and smallest element in an array?

Solution:-

 import java.util.Arrays;
/**
* Java program to find largest and smallest number from an array in Java.
* You cannot use any library method both from Java and third-party library.
*
* @author http://java67.blogspot.com
*/
public class MaximumMinimumArrayDemo{

public static void main(String args[]) {
largestAndSmallest(new int[]{-20, 34, 21, -87, 92,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{10, Integer.MIN_VALUE, -2});
largestAndSmallest(new int[]{Integer.MAX_VALUE, 40,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{1, -1, 0});
}

public static void largestAndSmallest(int[] numbers) {
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
for (int number : numbers) {
if (number > largest) {
largest = number;
} else if (number < smallest) {
smallest = number;
}
}

System.out.println(“Given integer array : ” + Arrays.toString(numbers));
System.out.println(“Largest number in array is : ” + largest);
System.out.println(“Smallest number in array is : ” + smallest);
}
}
Output:
Given integer array : [-20, 34, 21, -87, 92, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : -87
Given integer array : [10, -2147483648, -2]
Largest number in array is : 10
Smallest number in array is : -2147483648
Given integer array : [2147483647, 40, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : 40
Given integer array : [1, -1, 0]
Largest number in array is : 1
Smallest number in array is : -1

14.What is the difference between continue and break statement?

Solution:-

Break and continue are two important keywords used in Loops.

When a break keyword is used in a loop, a loop is broken instantly while when the continue keyword is used, the current iteration is broken and the loop continues with the next iteration.

In the below example, Loop is broken when the counter reaches 4.

 for (counter = 0; counter & lt; 10; counter++)
system.out.println(counter);

if (counter == 4) {

break;
}

}

In the below example, when the counter reaches 4, the loop jumps to the next iteration, and any statements after the continue keyword are skipped for the current iteration.

for (counter = 0; counter < 10; counter++)
system.out.println(counter);

if (counter == 4) {

continue;
}
system.out.println(“This will not get printed when counter is 4”);
}

15. Write a Java Program to count the number of words in a string using HashMap.

Solution:-

This is a collection class program where we have used HashMap for storing the string.

First of all, we have declared our string variable called str. Then we have used the split() function delimited by a single space so that we can split multiple words in a string.

Thereafter, we have declared HashMap and iterated using for loop. Inside for loop, we have an if-else statement in which wherever at a particular position, the map contains a key, we set the counter at that position and add the object to the map.

Each time, the counter is incremented by 1. Else, the counter is set to 1.

Finally, we are printing the HashMap.

Note: The same program can be used to count the number of characters in a string. All you need to do is to remove one space (remove space delimited in split method) in String[] split = str.split(“”);
import java.util.HashMap;

public class FinalCountWords {

public static void main(String[] args) {
// TODO Auto-generated method stub
String str = “This this is is done by Saket Saket”;
String[] split = str.split(” “);

HashMap<String,Integer> map = new HashMap<String,Integer>();
for (int i=0; i<split.length; i++) {
if (map.containsKey(split[i])) {
int count = map.get(split[i]);
map.put(split[i], count+1);
}
else {
map.put(split[i], 1);
}
}
System.out.println(map);
}

}

Output:

{Saket=2, by=1, this=1, This=1, is=2, done=1}

16. What is finalize() method?

Solution:-

Unlike c++, we don’t need to destroy objects explicitly in Java.

‘Garbage Collector’ does that automatically for us. Garbage Collector checks if no references to an object exist, that object is assumed to be no longer required, and the memory occupied by the object can be freed.

Sometimes an object can hold non-java resources such as file handle or database connection, then you want to make sure these resources are also released before the object is destroyed. To perform such an operation Java provides protected void finalize() in the object class.

You can override this method in your class and do the required tasks. Right before an object is freed, the java run time calls the finalize() method on that object. Refer this for more details.

17. Write a Java Program to iterate ArrayList using for-loop, while-loop, and advance for-loop.

Solution:-

In this program, we have inserted three elements and printed the size of the ArrayList.

Then, we have used While Loop with an iterator. Whenever the iterator has (next) element, it will display that element until we reach the end of the list.

So it will iterate three times.

Likewise, we have done for Advanced For Loop where we have created an object called obj for the ArrayList called list. Then printed the object.

Thereafter, we have put the condition of For Loop where the iterator i is set to 0 index, then it is incremented by 1 until the ArrayList limit or size is reached. Finally, we have printed each element using a get(index) method for each iteration of For Loop.
import java.util.*;

public class arrayList {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(“20”);
list.add(“30”);
list.add(“40”);
System.out.println(list.size());
System.out.println(“While Loop:”);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println(“Advanced For Loop:”);
for(Object obj : list) {
System.out.println(obj);
}
System.out.println(“For Loop:”);
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
}

Output:

3
While Loop:
20
30
40
Advanced For Loop:
20
30
40
For Loop:
20
30
40

18. What is the Final Keyword in Java? Give an example.

Solution:-

In java, a constant is declared using the keyword Final.

Value can be assigned only once and after assignment, the value of a constant can’t be changed.

In the below example, a constant with the name const_val is declared and assigned a value:

Private Final int const_val=100

When a method is declared as final, it can NOT be overridden by the subclasses. This method is faster than any other method because they are resolved at the complied time.

When a class is declared as final, it cannot be subclassed.

Example: String, Integer, and other wrapper classes.

19. Difference in Set and List interface?

Solution:-

Set and List both are child interface of the Collection interface.

There are following two main differences between them

  • The list can hold duplicate values but Set doesn’t allow this.
  • In List interface data is present in the order you inserted but in the case of Set insertion order is not preserved.
20. Java program to check if String is an anagram

Solution:-

import java.util.Arrays;

/**
* Java program – String Anagram Example.
* This program checks if two Strings are anagrams or not
*
* @author Javin Paul
*/
public class AnagramCheck {

/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* @return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}

char[] chars = word.toCharArray();

for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
}else{
return false;
}
}

return anagram.isEmpty();
}

/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* @return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);

return Arrays.equals(charFromWord, charFromAnagram);
}

public static boolean checkAnagram(String first, String second){
char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);

for(char ch : characters){
int index = sbSecond.indexOf(“” + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}

return sbSecond.length()==0 ? true : false;
}
}

Few

Important Pages to check:

Click on the button provided to visit few more Technical Interview Pages commonly asked during Interview.