500+ Top Java Interview Questions and Answers in 2022

java interview questions – In this tutorial we have provided a huge list of coding interview questions in java. Contains real logical code examples asked in programming and coding interviews for freshers and experienced candidates.

java interview questions – Top 500+ Core Java Interview Questions and Answers

Contents

Question – 1) Write a Java program to reverse a string without using the inbuilt string function.

Answer: Here, I am initializing a string variable string and using string builder class.

An object of string builder class userInput2 will be further used to append the value stored in the string variable.

Next, I am using the inbuilt function of string builder (reverse()) and storing the new reversed string in userInput2. Finally, I am printing userInput2 .

java interview programs code explains this:

public class FinalReverseWithoutUsingStringMethods {
  
     public static void main(String[] args) {
          
// TODO Auto-generated method stub
          String str = "Automation";
          StringBuilder userInput2 = new StringBuilder();
          userInput2.append(str);
          userInput2 = userInput2.reverse();
// used string builder to reverse
         System.out.println(userInput2);
          }
  
}

Output:

noitamotuA

java interview questions – Don’t Miss : Top 10 ASP.NET MVC Interview Questions And Answers

Question #2) Write a Java program to reverse a string without using the String inbuilt function reverse().

Answer: There are many ways you can reverse your string if you are allowed to use other string inbuilt functions.

Method 1: java interview questions

In this method, I am initializing a string variable named string with the value of your given string.

Then, we’re converting that string to a character array with the toCharArray() function.

Next, we’re using a for loop between each character to print each character in reverse order.

public class FinalReverseWithoutUsingInbuiltFunction {
    public static void main(String[] args) {
        String str = "Pakainfo Website";
        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

Method 2 For java coding questions:

This is another java interview questions way in which you are declaring your string variable and then using the Scanner class to declare an object with a predefined input input object.

This program will accept a string value through the command line (when executed).

We have used nextLine() which will read the input with spaces between the words of the string.

Then, we use a split() method to split the string into its substrings (no delimiters given here).

Finally, we have printed the string in reverse order using a for loop.

import java.util.Scanner;
 
public class ReverseSplit {
 
    public static void main(String[] args) {
        
// TODO Auto-generated method stub
        String str;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your String");
        str = in.nextLine();
        String[] token = str.split("");
//used split method to print in reverse order
        for(int i=token.length-1; i>=0; i--)
        }
            System.out.print(token[i] + "");
        }
         
    }
 
}

Output :- java interview questions

Enter your String
softwaredownloadfree
plehgnitseterawtfoS

Don’t Miss : Top 10 Android Interview Questions And Answers

java programming interview questions Method 3:

It is almost like method 2, but here we have not used split() method.

We have used Scanner class and nextLine() to read input string.

Then, we have declared an integer length containing the length of the input string.

Next, we have printed the string in reverse order using a loop.

However, we have used the charAt(index) method which will return the character at any specific index.

After each iteration, the string variable will be concatenated to reverse the character.

Lastly, we have printed the reverse string variable.

import java.util.Scanner;
 
public class Reverse {
 
    public static void main(String[] args) {
        
// TODO Auto-generated method stub
        String original, reverse = "";
        System.out.println("Enter the string to be reversed");
        Scanner in = new Scanner(System.in);
        original = in.nextLine();
        int length = original.length();
        for(int i=length-1; i>=0; i--) {
            reverse = reverse + original.charAt(i);
//used inbuilt method charAt() to reverse the string
        }
        System.out.println(reverse);
    }
 
}

Output:

Enter the string to be reversed
automation download
gnitset noitamotua

Question # 3) Write a Java program to swap two numbers using the third variable.

Answer: In this example, we have used the Scanner class to declare an object with a predefined standard input object.

This program will accept the value of x and y through the command line (when executed).

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

Now, the logic of the program is something like this – I am assigning to temp or a third variable with the value of x, and then assigning x with the value of y and again to y with the value of temp are assigned.

So, after the first complete iteration, the value of temporary will be x, the value of x will be the value of y and the value of temporary of y (which is x).

Also Read This 👉   Laravel Soft Delete Example Tutorial From Scratch

java interview questions

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

Don’t Miss : JQuery AJAX Interview Questions And Answers

Question # 4) Write a Java program to swap two numbers using the third variable.

Answer: Everything else will be same as above program. Only the logic will change.

Here, I am assigning x with the value x + y which means that x will be the sum of both x and y.

Then, we’re assigning y with the value of x – y, which means we’re subtracting the value of y from the sum of (x + +).

Even so, x still contains the sum of both x and y. But y has a value of x.

Finally, in the third step, we’re assigning x with the value x – y, which means we’re subtracting y (which has the value of x) from the total (x + y). This will assign x with the value of y and vice versa.

Example program for java programming interview questions

import java.util.Scanner;
  
class SwapTwoNumberWithoutThirdVariable
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
  
      x = in.nextInt();
      y = in.nextInt();
  
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
  
      x = x + y;
      y = x - y;
      x = x - y;
  
      System.out.println("After Swapping without third variable\nx = "+x+"\ny = "+y);
   }
}

Output:

Enter x and y
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45

Question #5) Write a Java Program to count the number of words in a string using HashMap.

Answer: This is a collection class program where we have used HashMap to store the string.

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

After this, we have declared HashMap and used for loop.

In a for loop, we have an if-else statement in which wherever there is a key in the map, at a particular position,

We set the counter at that position and add the object to the map.

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

Finally, I am 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 a space in String[] split = str.split(“”) (remove the space delimited in split method);

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 Pakainfo Pakainfo";
        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:

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

Don’t Miss : Top 10 Advanced VueJS Interview Questions Answers

Question #6) Write a Java Program to iterate HashMap using While and advance for loop.

Answer: Here we have inserted three elements in HashMap using put() function.

You can get the size of the map using the size() method. Next, we’ve used a loop to iterate through the map containing a key-value pair for each element.

Keys and values ​​can be obtained through getKey() and getValue().

Similarly, we have used advanced for loop, where we have “me2” object for HashMap.

Program for coding interview questions in java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class HashMapIteration {
 
    public static void main(String[] args) {
        
// TODO Auto-generated method stub
        HashMap<Integer,String> map = new HashMap<Integer,String>();
        map.put(2, "Pakainfo");
        map.put(25, "Website");
        map.put(12, "HashMap");
        System.out.println(map.size());
        System.out.println("While Loop:");
        Iterator itr = map.entrySet().iterator();
        while(itr.hasNext()) {
            Map.Entry me = (Map.Entry) itr.next();
            System.out.println("Key is " + me.getKey() + " Value is " + me.getValue());
        }
        System.out.println("For Loop:");
        for(Map.Entry me2: map.entrySet()) {
            System.out.println("Key is: " + me2.getKey() + " Value is: " + me2.getValue());
        }
    }
 
}

Output:

3
While Loop:
Key is 2 Value is Pakainfo
Key is 25 Value is Website
Key is 12 Value is HashMap
For Loop:
Key is: 2 Value is: Pakainfo
Key is: 25 Value is: Website
Key is: 12 Value is: HashMap

Question #7) Write a Java Program to find whether a number is prime or not.

Answer: Here, we have used Scanner class with temp and number and next of two integers (since we have integer).

A Boolean variable .Prime is set to true. Next, we have used a for loop starting from 2, for each iteration a number less than 1 is entered and increased by 1.

The temp will be the remainder for each iteration. If the remainder is 0, error will be set to false.

Based on our value, I am coming to the conclusion whether our number is prime or not.

Example of java interview programs

import java.util.Scanner;
 
public class Prime {
 
    public static void main(String[] args) {
        
// TODO Auto-generated method stub
        int temp, num;
        boolean isPrime = true;
        Scanner in = new Scanner(System.in);
        num = in.nextInt();
        in.close();
        for (int i = 2; i<= num/2; i++) {
            temp = num%i;
            if (temp == 0) {
                isPrime = false;
                break;
            }
        }
        if(isPrime)
            System.out.println(num + "number is prime");
            else
                System.out.println(num + "number is not a prime");
             
         
    }
 
}

Output:

445
445number is not a prime

Question #8) Write a Java Program to find whether a string or number is palindrome or not.

Answer: You can use any of the string string program mentioned above to check whether a number or a string is a palindrome.

What you need to do is include an if-else statement. If the original string is equal to the reversed string then the number is a palindrome, otherwise not.

java basic programs for interview
import java.util.Scanner;
 
public class Palindrome {
    public static void main (String[] args) {
        String original, reverse = "";
        Scanner in = new Scanner(System.in);
        int length;
        System.out.println("Enter the number or String");
        original = in.nextLine();
        length = original.length();
        for (int i =length -1; i>;=0; i--) {
            reverse = reverse + original.charAt(i);
        }
        System.out.println("reverse is:" +reverse);
         
        if(original.equals(reverse))
            System.out.println("The number is palindrome");
        else
            System.out.println("The number is not a palindrome");
         
    }
}

Output:

For String-


Enter the number or String
vijay
reverse is:yajiv
The number is not a palindrome


For Number-


Enter the number or String
99
reverse is:99
The number is palindrome

Question #9) Write a Java Program for the Fibonacci series.

Answer: The Fibonacci series is a series of numbers where, after the initial two numbers, each subsequent number is the sum of the two preceding numbers.

For example 0,1,1,2,3,5,8,13,21………

In this program, we have used the Scanner class again with the next one (discussed above).

Initially, I am entering (via command line) the time at which Fibonacci is to run.

We have declared integer numbers and initialized a with zero and c with b. Then, we have used loop to iterate.

The logic is such that a is set with a value of b which is 0, then b is set with a value of c which is 1. Then, c is set with the sum of both a and b.

java programs asked in interview
import java.util.Scanner;
 
public class Fibonacci {
    public static void main(String[] args) {
        int num, a = 0,b=0, c =1;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of times");
        num = in.nextInt();
        System.out.println("Fibonacci Series of the number is:");
        for (int i=0; i<num; i++) {
            a = b;
            b = c;
            c = a+b;
            System.out.println(a + "");
//if you want to print on the same line, use print()
        }
    }
}

Output:

Enter the number of times
10
Fibonacci Series of the number is:
0
1
1
2
3
5
8
13
21
34

Question #10) Write a Java Program to iterate ArrayList using for-loop, while-loop, and advance for-loop.

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

Then, we have used it loop. Whenever there is (next) element in the iterator,

It will display that element till we reach the end of the list. So it will iterate three times.

Similarly, we have done advanced for loop where we have created an object named obj for list named ArrayList. Then printed the object.

Thereafter, we put a condition for the for loop, where the iterator i is set to index 0, then it is incremented by 1 until the ArrayList limit or size is reached.

Finally, we have printed one element for each iteration of the for loop using the (index) method.

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

Question #11) Write a Java Program to demonstrate an explicit wait condition check.

Answer: There are two main types of await – implicit and explicit. (I am not considering fluent wait in this program)

Also Read This 👉   Get all eloquent query log using Laravel 7/6 example

Implicit wait is the wait which is executed irrespective of any condition. In the program below,

You can see that this is for Google Chrome and we have used some inbuilt methods to set the property, for window, URL navigation and web element detection.

WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Software download - Wikipedia"))));
element2.click();

In the above code, you can see that we have created an object wait for WebDriverWait and then we searched for element 2 named Web2element.

This condition is set in such a way that one must wait until the “Software download – Wikipedia” link to the web software is seen on the web page.

If this link is not found it will not be executed. If it does, it will perform a mouse click on that link.

package codes;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
 
public class explicitWaitConditionCheck {
 
           public static void main(String[] args) {
                    
// TODO Auto-generated method stub
                    System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe");
                   ChromeOptions options = new ChromeOptions();
                   options.addArguments("--disable-arguments");
                   WebDriver driver = new ChromeDriver();
                   driver.manage().window().maximize();
                   driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                   driver.navigate().to("https://www.google.com");
                   WebElement element = driver.findElement(By.name("q"));
                    element.sendKeys("download");
                    element.submit();
                    WebDriverWait wait = new WebDriverWait(driver, 20);
 
                     WebElement element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Software download - Wikipedia"))));
element2.click();
}

Question #12) Write a Java Program to demonstrate Scroll up/ Scroll down.

Answer: All the lines of codes are easily related as we have discussed in our previous example.

However, in this program, we have included our JavascriptExecutor js which will do the scrolling. If you look at the last line of code, we’ve passed window.scrollBy(arg1, arg2) .

If you want to scroll then pass some value in arg1 If you want to scroll down then pass some value in arg2.

java programming questions and answers

package codes;
 
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class ScrollDown {
 
          public static void main(String[] args) {
                   
// TODO Auto-generated method stub
                   System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe");
                   WebDriver driver = new ChromeDriver();
                   JavascriptExecutor js = (JavascriptExecutor) driver;
                   driver.manage().window().maximize();
                   driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                   driver.get("https://www.google.com");
                   WebElement element = driver.findElement(By.name("q"));
                   element.sendKeys("Softwaredownloadfree");
                   element.sendKeys(Keys.ENTER);
                    js.executeScript("window.scrollBy(0,1000)");
 
}
 
}

Question #13) Write a Java Program to open all links of gmail.com.

Answer: This is a typical example of the advanced for loop that we have seen in our previous programs.

Once you open a website using gmail get() or navigate().to() , you can search the tag name of a website using a tagname locator which will return all the tags.

We have proceeded to the for loop, where we have created a new WebElement link2 for a link (which already has located all the tags), then we have got all the links via getAttribute(“href”) and getText All texts are found through ().

java interview programs for freshers – java interview questions

package codes;
 
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class openAllLinks {
 
        public static void main(String[] args) {
        
// TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.drive", "C:\\webdriver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://www.gmail.com/");
        java.util.List<WebElement> link = driver.findElements(By.tagName("a"));
       System.out.println(link.size());
 
       for (WebElement link2: link) {
 
       
//print the links i.e. http://google.com or https://www.gmail.com
      System.out.println(link2.getAttribute("href"));
 
      
//print the links text
     System.out.println(link2.getText());
}
}
}

Output:

Starting ChromeDriver 2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed) on port 16163
Only local connections are allowed.
4
https://support.google.com/chrome/answer/6130773?hl=en-GB
Learn more
https://support.google.com/accounts?hl=en-GB
Help
https://accounts.google.com/TOS?loc=IN&hl=en-GB&privacy=true
Privacy
https://accounts.google.com/TOS?loc=IN&hl=en-GB
Terms

Question #14) Write a Selenium code to switch to the previous tab.

Answer: We have demonstrated the use of the Robot class. We see this as an important third party because if you know the shortcut keys we can achieve different navigation within a browser and its tabs.

For example, if you have three tabs open in Chrome and you want to go to the middle tab,

So you have to press Control + 2 from your keyboard. The same thing can be achieved through code as well.

Look at the following code carefully (just let us see the instantiation of Robot class). We have used Robot class object called Robot with two inbuilt methods keypad (keyPress(KeyEvenet.VK_*) and keyRelease(KeyEvenet.VK_*).

java programs asked in interview:- java interview questions

package codes;
 
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class PreviousTab {
          public static void main(String[] args) throws AWTException {
               
// TODO Auto-generated method stub
              System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe");
             WebDriver driver = new ChromeDriver();
             driver.manage().window().maximize();
             driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
             driver.get("https://www.google.com");
             WebElement element1 = driver.findElement(By.name("q"));
             element1.sendKeys("software download free");
             element1.sendKeys(Keys.ENTER);
             String a = Keys.chord(Keys.CONTROL,Keys.RETURN);
             driver.findElement(By.partialLinkText("Software download free - A Must Visit Software download Portal")).sendKeys(a);
             Robot robot = new Robot();
// instantiated robot class
             robot.keyPress(KeyEvent.VK_CONTROL);
// with robot class you can easily achieve anything if you know the shortcut keys
             robot.keyPress(KeyEvent.VK_2);
// here, we have just pressed ctrl+2
             robot.keyRelease(KeyEvent.VK_CONTROL);
// once we press and release ctrl+2, it will go to the second tab.
             robot.keyRelease(KeyEvent.VK_2);
//if you again want to go back to first tab press and release vk_1
             }
}

Question #15) Write a Java Program to find the duplicate characters in a string.

Answer: In this program, we have created a string variable string and started an integer count with zero.

Then, we’ve created a character array to convert our string variables to characters. With the free of loop, I am comparing between different characters at different index.

If two characters of consecutive index match, it will print that character and after each iteration the counter will be incremented by 1.

public class DuplicateCharacters {
          
          public static void main(String[] args) {
                   
// TODO Auto-generated method stub
                  String str = new String("Pakainfooo");
                  int count = 0;
                  char[] chars = str.toCharArray();
                  System.out.println("Duplicate characters are:");
                  for (int i=0; i<str.length();i++) {
                              for(int j=i+1; j<str.length();j++) {
                                         if (chars[i] == chars[j]) {
                                                    System.out.println(chars[j]);
                                                    count++;
                                                    break;
                                          }
                               }
                   }
           }
 
}

Output:

Duplicate characters are:
k
t

Question #16) Write a Java Program to find the second-highest number in an array.

Answer: In this program, we have initialized an array with 10 random elements from which I am going to find the second-highest number.

Here, we have two integers—the largest and the second largest. Both are set to the first index of the element. Then, we have printed out all the elements using the loop.

Now, the logic is that when the element at the 0th index is the largest, assign arr[0] to the largest and the second to the largest.

Again, if the element at index 0, is greater than the second list, secondLargest, then assign secondLargest to arr[0].

This will be repeated for each iteration and will eventually give you the second largest element after comparing or completing the iterations up to the array length. java interview questions

package codes;
public class SecondHighestNumberInArray {
public static void main(String[] args)
    {
        int arr[] = { 100,14, 46, 47, 94, 94, 52, 86, 36, 94, 89 };
        int largest = 0;
        int secondLargest = 0;
        System.out.println("The given array is:");
        for (int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i] + "\t");
        }
        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i] > largest)
            {
                secondLargest = largest;
                largest = arr[i];
            }
            else if (arr[i] > secondLargest)
            {
                secondLargest = arr[i];
            }
        }
        System.out.println("\nSecond largest number is:" + secondLargest);
        System.out.println("Largest Number is: " +largest);
    }
}

Output:

The given array is:
100 14 46 47 94 94 52 86 36 94 89
Second largest number is:94
Largest Number is: 100

Question #17) Write a Java Program to check Armstrong number.

Answer: First we need to understand what the Armstrong number is. The Armstrong number is the number that is the sum of the cube of the hundred digits for all its unit, tens and three-digit numbers.

153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 * 3 = 1 + 125 + 27 = 153

If you have a four digit number, lets say

1634 = 1 * 1 * 1 * 1 + 6 * 6 * 6 * 6 * 3 * 3 * 3 * 3 * 3 * 4 * 4 * 4 * 4 * 4 = 1 + 1296 + 81 + 256 = 1634

Now, in this program, we have a temporary and an integer declared. We have initialized c with the value 0.

Then, we need to assign the integer value we’re going to check for Armstrong (in our case, let’s say 153).

Then we have assigned our temp variable with the number I am going to check.

Next, we have used the conditional check, where the remainder is assigned to a and the number is divided by 10 and assigned to n.

Now, our c variable which was initially set to zero is assigned with c + (a * a * a) .

Suppose we have to evaluate a four digit number then c should be assigned with c + (a * a * a * a) .

Lastly, we have placed an if-else statement for the conditional check, where we compare the value contained in c against temp (which is the actual number stored at this point). If it matches, the number is Armstrong otherwise not.
java interview questions

java coding interview questions pdf


class Armstrong{
 public static void main(String[] args) {
   int c=0,a,temp;
   int n=153;
//It is the number to check Armstrong
   temp=n;
   while(n>0)
   {
	   a=n%10;
	   n=n/10;
	    c=c+(a*a*a);
    }
    if(temp==c)
    System.out.println("armstrong number");
    else
        System.out.println("Not armstrong number");
}

Output:

Also Read This 👉   Update multiple records using Laravel

armstrong number

Question #18) Write a Java Program to remove all white spaces from a string with using replace().

Answer: This is a simple program where we have our string variable userInput1.

Another string variable userInput2 is initialized with replace option which is an inbuilt method to remove n number of whitespaces. Ultimately, we have printed userInput2 with no whitespace.

class RemoveWhiteSpaces
{
    public static void main(String[] args)
    {
        String userInput1 = "Pakainfo Website is a QualityAna list";
  
        
// 1. Using replaceAll() Method
  
        String userInput2 = userInput1.replaceAll("\\s", "");
  
        System.out.println(userInput2);
  
           }
}
}

Output:

PakainfoWebsiteisaQualityAnalist

Question #19) Write a Java Program to remove all white spaces from a string without using replace().

Answer: This is another approach to remove all white spaces. Then, we have a string variable userInput1 which has some values. Then, we have converted that string into a character array using character array().

After that, we have a StringReferr object sb, which will be used to concatenate the value stored in the i[i] index after the join in the for loop and on an if condition.

If the position is set as such, the element at the i index of the character array must not be equal to space or tab. Finally, we have printed our StringBuffer object sb.

coding interview questions in java

class RemoveWhiteSpaces
{
    public static void main(String[] args)
    {
        String userInput1 = "Pakainfo Website is an Autom ation Engi ne er";
  
        char[] chars = userInput1.toCharArray();
  
        StringBuffer sb = new StringBuffer();
  
        for (int i = 0; i < chars.length; i++)
        {
            if( (chars[i] != ' ') && (chars[i] != '\t') )
            {
                sb.append(chars[i]);
            }
        }
        System.out.println(sb);
//Output : CoreJavajspservletsjdbcstrutshibernatespring
    }
}

Output:

PakainfoWebsiteisanAutomationEngineer

Question #20) Write a Java Program to read an excel.

Answer: These types of programs are commonly used in Selenium framework. We have added detailed comments for every step to understand the program more.

The logic starts from the sheet when we load the sheet in which the data is stored.

I am trying to import email and password. For this, I am retrieving the cell using getRow() and getCell() method. Let’s say we have email and password in the first and second cells.

Then I am setting the type of cell to string. I am then performing a simple web element locator operation (by.ed) where we have passed unique locator values ​​such as “e-mail” and “password” that will identify these elements.

Finally, I am sending keys using element.sendKeys where cell.getStringCellValue() is the keys. This will return you the value stored at cell number 1 and 2 respectively.

Program for coding interview questions in java

@Pakainfo
 public void ReadData() throws IOException
 {
     
// Import excel sheet from a webdriver directory which is inside c drive.
     
//DataSource is the name of the excel
     File src=new File("C:\\webdriver\\DataSource.xls");
      
     
//This step is for loading the file. We have used FileInputStream as
     
//I am reading the excel. In case you want to write into the file,
     
//you need to use FileOutputStream. The path of the file is passed as an argument to FileInputStream
     FileInputStream finput = new FileInputStream(src);
      
     
//This step is to load the workbook of the excel which is done by global HSSFWorkbook in which we have
     
//passed finput as an argument.
    workbook = new HSSFWorkbook(finput);
      
     
//This step is to load the sheet in which data is stored.
     sheet= workbook.getSheetAt(0);
      
     for(int i=1; i<=sheet.getLastRowNum(); i++)
     }
         
// Import data for Email.
         cell = sheet.getRow(i).getCell(1);
         cell.setCellType(Cell.CELL_TYPE_STRING);
         driver.findElement(By.id("email")).sendKeys(cell.getStringCellValue());
          
         
// Import data for the password.
         cell = sheet.getRow(i).getCell(2);
         cell.setCellType(Cell.CELL_TYPE_STRING);
         driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue());
                 
        }
  }
  

java multiple choice questions MCQ & java interview questions

Question 1:- Which of the following is a primitive type?

  • float
  • string
  • integer
  • byte

Answer:- 4

Question 2:- What is the range of char type?

  • 0 to 2^16 – 1
  • 0 to 2^16
  • 0 to 2^15-1
  • 0 to 2^15

Answer:- 3

Question 3:- The garbage collector runs immediately when the system is out of memory.

  • truth
  • false

Answer:- True

Question 4:- Out of these, Java’s keyword is.

  • NULL
  • Sizeof
  • Friend
  • Extends

Answer:- 4

Question 5:- What are access modifiers?

  • public
  • private
  • protected
  • default
  • all these

Answer:- 5

Question 6:- Who developed Java?

  • Microsoft has
  • Google
  • Sun Microsystems
  • Amazon has
  • none of these

Answer:- 3

Question 7:- Java interpreter converts which of the following into machine code?

  • user code
  • bit code
  • Byte Code (Virtual Machine Code)
  • machine code

Answer:- 3

Question 8:- Who among these are the inventors of Java?

  • Fleming
  • James Gosling
  • Balaguru Swami
  • Dennis Ritchie

Answer:- 2

Question 9:- Which of the following is an assignment operator?

  • 1.+=
  • 2.==
  • 3.%=
  • 4.=

Answer:- 3

Question 10:- What is the full name of JVM?

  • java variable machine
  • java virtual method
  • Java Virtual Machine
  • Java Versatile Machine

Answer:- 3

11 to 20 java mcq – java interview questions

Question 11:- Which is the default access specifier in Java?

  • private
  • public
  • protected
  • friendly

Answer:- 4

Question 12:- We cannot create a subclass of which of the following classes.

  • final
  • public
  • static
  • abstract

Answer 1

Question 13:- Which of the following errors are called all syntax errors?

  • Exception
  • Run-time
  • compile-time
  • logocal

Answer:- 3

Question 14:- Which of the following package is used to create and implement applet?

  • java.out
  • java.util
  • java.lang
  • java.applet

Answer:- 4

Question 15:- JDBC was developed under whom.

  • JPC
  • JCP
  • JBC
  • ODBC

Answer:- 2

Question 16:- What kind of language is Java?

  • weakly typed
  • moderate typed
  • strongly typed
  • None of these.

Answer:- 3

Question 17:- How many primitive data types are there in Java?

  • 9
  • 5
  • 7
  • 8

Answer:- 3

Question 18:- The suspend() method is used to terminate the thread.

  • Correct
  • Wrong

Answer:- Wrong

Question 19:- Can you create Java source code in Notepad creator?

  • Correct
  • Wrong

Answer:- Correct

21 to 32 java mcq – java interview questions

Question 20:- Java supports multidimensional array.

  • Correct
  • Wrong

Answer:- Correct

Question 21:- What happens to the object, class?

  • inheritance
  • invoke
  • incentive
  • instance

Answer:- 4

Question 22:- Whose collection is the package?

  • of tools
  • of keywords
  • of object
  • of classes and interfaces

Answer:- 4

Question 23:- Which servlets use doGet(), doPost(), doHead(), doDelete() and doTrace() methods?

  • HttpServlets
  • GenericServlets
  • both a and B
  • None of these

Answer 1

Question 24:- Where is the clone() method defined?

  • object class
  • arraylist class
  • abstract class
  • none of these

The clone() method is defined in the Object class.

Answer:- a

Question 25: – By whom is the life cycle of the thread controlled.

  • JDK
  • JRE
  • JVM
  • none of these

Answer:- a

Question 26:- The Java Virtual Machine is platform independent.

  • Correct
  • Wrong

Answer:- Wrong

Question 27:- The web server is used to load the init() method of the servlet.

  • Correct
  • Wrong

Answer:- Correct

Question 28:- What is the full name of JDBC?

  • java database community
  • java database connectivity
  • java database concept
  • java database communication

Answer:- 2

29:- What is the full name of JIT?

  • java in time
  • java in technology
  • just in time
  • None of these

Answer:- 3

Question 30:- Which keyword is used to define interface in Java?

  • intf
  • in
  • interface
  • None of these

Answer:- 3

Question 31:- Which of the following does not support oop?

  • global variables
  • abstraction
  • polymorphism
  • encapsulation

Answer 1

Question 32:- What is the full name of jar?

  • java archive
  • java application runner
  • java archive runner
  • none of these

Answer 1

in java interview questions article, I have given some important java MCQs here which can prove to be very useful. If you need MCQ of any other subject then tell us through comment and share this post of java mcq with your friends.

I hope you get an idea about java interview questions.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, and java interview questions question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.