Top 20 Java Programming Interview Questions And Answers

1) Write a Java program to find whether a number is an Armstrong number.

import java.util.Scanner;

public class ArmstrongNumber {

    public static void main(String[] args){

        int c=0,a,temp;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int num = sc.nextInt();
        temp = num;
        while(num>0){
            a=num%10;
            num=num/10;
            c=c+(a*a*a);
        }
        if(temp==c) {
            System.out.println(temp +  " is an Armstrong number");
        } else System.out.println(temp + " is not an armstrong number");
    }
}
OUTPUT:

Enter a number
153
153 is an Armstrong number

Process finished with exit code 0

2) Write a Java program to compare 2 strings.

import java.util.Scanner;

public class CompareTwoStrings {
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first string");
        String first = sc.next();
        System.out.println("Enter second string");
        String second = sc.next();
        compare(first,second);
    }
    public static void compare(String s1, String s2){

        if(s1.compareTo(s2)==0) {
            System.out.println("Strings are equal");
        } else {
            System.out.println("Strings are not equal");
        }
    }
}
OUTPUT:

Enter first string
automation
Enter second string
java
Strings are not equal

Process finished with exit code 0

3) Write a Java program to find largest number in an array.

public class FindLargestNumberInArray {

    static int array[] = {21,98,13,9,34};
    public static void main(String[] args){
        int maxNumber = findLargestNumber();
        System.out.println("Maximum number in the array: "+ maxNumber);
    }
    private static int findLargestNumber(){
        int max = array[0];
        for(int i =0;i<array.length;i++){
            if(array[i]>max)
                max = array[i];
        }
        return max;
    }
}
OUTPUT:

Maximum number in the array: 98

Process finished with exit code 0

4) Write a Java program to find whether number is prime.

import java.util.Scanner;
public class FindNumberIsPrime {
    public static void main(String[] args){
        boolean flag = false;
        System.out.println("Enter input number");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        for(int i=2;i<=num/2;i++){
            if(num%i==0){
                flag = true;
                break;
            }
        }
        if(!flag){
                System.out.println(num + " is a prime number");
            } else{
                System.out.println(num + " is not a prime number");
            }
    }
}
OUTPUT:

Enter input number
23
23 is a prime number

Process finished with exit code 0

5) Write a Java program to find whether number is even or odd.

import java.util.Scanner;

public class FindOddEvenNumbers {
    public static void main(String[] args){
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter a number: ");
        int inputNumber = sc.nextInt();
        findNumber(inputNumber);
    }
    public static void findNumber(int number){
        if(number%2!=0){
            System.out.println("Number is odd");
        }
        else {
            System.out.println("Number is even");
        }
    }
}
OUTPUT:

Enter a number: 
29
Number is odd

Process finished with exit code 0

6) Write a Java program to find whether number is Palindrome.

import java.util.Scanner;

public class PalindromeNumber {

    public static void main(String[] args){
        int r,sum=0,temp;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        temp=n;
        while (n > 0) {
            r = n%10;
            sum = (sum*10) + r;
            n=n/10;
        }
        if(temp==sum)
            System.out.println("Number is palindrome");
        else
            System.out.println("Number is not palindrome");
    }
}
OUTPUT:

Enter a number
545
Number is palindrome

Process finished with exit code 0

7) Write a Java program to reverse a number.

import java.util.Scanner;

public class ReverseNumber {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int num = sc.nextInt();
        reverseNumber(num);
    }
    public static void reverseNumber(int number){
        int reverse = 0;
        while(number!=0){
            int digit = number % 10;
            reverse = reverse * 10 + digit;
            number = number/10;
        }
       System.out.println("Reversed number " + reverse);
    }
}
OUTPUT:

Enter the number
654
Reversed number 456

Process finished with exit code 0

8) Write a Java program to reverse a string.

import java.util.Scanner;

public class ReverseString {

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string");
        String s1 = sc.next();
        String s2 = reverseString(s1);
        System.out.println("Reversed String is: "+s2);
    }

    public static String reverseString(String s){
        String rev="";
        char[] arr = s.toCharArray();
        for(int i=arr.length-1;i>=0;i--)
        rev = rev + arr[i];
        return rev;
    }
}
OUTPUT:

Enter input string
automation
Reversed String is: noitamotua

Process finished with exit code 0

9) Write a Java program to swap numbers without a variable.

public class SwapNumberWithoutVariable {

    public static void main(String[] args) {
        int x = 10;
        int y = 5;
        System.out.println("Before swapping: " + "x is " + x + " and " + "y is " + y);
        x = x + y;
        y = x - y;
        x = x - y;
        System.out.println("After swapping: " + " x is " + x + " and " + "y is "+ y);
    }
}
OUTPUT:

Before swapping: x is 10 and y is 5
After swapping:  x is 5 and y is 10

Process finished with exit code 0

10) Write a Java program to reverse a sentence word by word.

public class ReverseSentenceWordByWord {

    public static void main(String[] args){

        String sentence = "Java Interview Questions";
        String reversedSentence = reverseSentence(sentence);
        System.out.println(reversedSentence);

    }

    public static String reverseSentence(String sentence){

        String reverse = "";
        String[] words = sentence.split("\\s");
        for(int i=words.length-1;i>=0;i--){
            reverse = reverse + words[i] + " ";
        }
        return reverse;
    }
}
OUTPUT:

Original sentence is: Java Interview Questions
Reversed sentence is: Questions Interview Java 

Process finished with exit code 0

11) Write a Java program to find duplicate numbers in an Array.

import java.util.HashSet;

public class FindDuplicateElementsInArray {

    public static void main(String[] args){

    Integer[] inputArray = {2,3,4,5,1,2,3};

        HashSet<Integer> set = new HashSet<>();
        for(int number: inputArray){
            if(!set.add(number))
            {
                System.out.println("Duplicate element in the array is "+ number);
            }
        }

    }


}
OUTPUT:

Duplicate element in the array is 2
Duplicate element in the array is 3

Process finished with exit code 0

12) Write a Java program to find frequency of characters in String.

import java.util.HashMap;
import java.util.Map;

public class FindFrequencyOfCharactersInString {

    public static void main(String[] args){

        Map<Character,Integer> map = new HashMap<>();
        map = findFrequency("Java J2EE Java JSP J2EE");

        for(Map.Entry<Character,Integer> entry: map.entrySet()){
            System.out.println("Frequency of character " + entry.getKey() + " is "+ entry.getValue());
        }
    }

    public static Map<Character,Integer> findFrequency(String input){

        char[] arr = input.toLowerCase().replaceAll("\\s+","").toCharArray();
        Map<Character,Integer> frequency = new HashMap<>();
        for(char c: arr){
            if(frequency.containsKey(c)){
                frequency.put(c,frequency.get(c) + 1);
            }
            else{
                frequency.put(c,1);
            }
        }
        return frequency;
    }

}
OUTPUT:

Frequency of character p is 1
Frequency of character a is 4
Frequency of character 2 is 2
Frequency of character s is 1
Frequency of character e is 4
Frequency of character v is 2
Frequency of character j is 5

Process finished with exit code 0

13) Write a Java program to perform binary search of an element.

// Java implementation of recursive Binary Search
class BinarySearch {
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
            // If the element is present at the middle itself
            if (arr[mid] == x)
                return mid;
            // If element is smaller than mid, then it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
            // Else the element can only be present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
        // If element is not present in array
        return -1;
    }
    public static void main(String args[])
    {
        BinarySearch bs = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = bs.binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " + result);
    }
}
OUTPUT:

Element found at index 3

Process finished with exit code 0

14) Write a Java program to perform linear search of an element.

public class LinearSearch {
    static int search(int arr[], int n, int x){
        for(int i = 0;i<n;i++){
            if(arr[i] == x)
                return i;
        }
        return -1;
    }
    public static void main(String[] args){
        int[] arr = {5,1,9,4,3,8};
        int n = arr.length;
        int x = 4;
        int index = search(arr,n,x);
        if(index == -1){
            System.out.println("Element is not present in the array");
        }
        else
            System.out.println("Element found at position " + index);
    }
}
OUTPUT:

Element found at position 3

Process finished with exit code 0

15) Write a Java program to sort numbers using Bubble sort.

class BubbleSort
{
    void bubbleSort(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }
    void printArray(int arr[]) {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
    public static void main(String args[]) {
        BubbleSort bs = new BubbleSort();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        bs.bubbleSort(arr);
        System.out.println("Sorted array");
        bs.printArray(arr);
    }
}
OUTPUT:

Sorted array
11 12 22 25 34 64 90 

Process finished with exit code 0

16) Write a Java program to print Floyd triangle.

import java.util.Scanner;

public class FloydTriangle {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        printFloydTriangle(rows);
    }
    public static void printFloydTriangle(int n){
        int number = 1;
        for(int i=0;i<n;i++){
            for(int j=0;j<=i;j++){
                System.out.print(number +" ");
                number++;
            }
            System.out.println();
        }
    }
}
OUTPUT:

Enter the number of rows
5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

Process finished with exit code 0

17) Write a Java program to generate a random number.

import java.util.Random;

public class GenerateRandomNumber {
    public static void main(String[] args){
        Random rand = new Random();
        int r1 = rand.nextInt(1000);
        System.out.println("Random numbers: "+ r1);
    }
}
OUTPUT:

Random numbers: 876

Process finished with exit code 0

18) Write a Java program to open a Notepad application.

import java.io.IOException;

public class OpenNotepad {

    public static void main(String[] args){
        Runtime rs = Runtime.getRuntime();
        try{
            rs.exec("notepad");
        }
        catch (IOException e){
            System.out.println(e);
        }
    }
}

19) Write a Java program to get date and time in specific format.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

public class GetDateAndTime {

        private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

        public static void main(String[] args) {

            Date date = new Date();
            System.out.println(sdf.format(date));

            Calendar cal = Calendar.getInstance();
            System.out.println(sdf.format(cal.getTime()));

            LocalDateTime now = LocalDateTime.now();
            System.out.println(dtf.format(now));

            LocalDate localDate = LocalDate.now();
            System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));

    }
}
OUTPUT:

2020/03/14 20:37:13
2020/03/14 20:37:13
2020/03/14 20:37:13
2020/03/14

Process finished with exit code 0

20) Write a Java program to find your IP address.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;

public class FindIPAddress {
    public static void main(String[] args) throws Exception{
        // Returns the instance of InetAddress containing local host name and address
        InetAddress localhost = InetAddress.getLocalHost();
        System.out.println("System IP Address : " + (localhost.getHostAddress()).trim());
        // Find public IP address
        String systemipaddress = "";
        try
        {
            URL url_name = new URL("https://bot.whatismyipaddress.com");
            BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
            // reads system IPAddress
            systemipaddress = sc.readLine().trim();
        }
        catch (Exception e)
        {
            systemipaddress = "Cannot Execute Properly";
        }
        System.out.println("Public IP Address: " + systemipaddress +"\n");
    }
}
OUTPUT: 

System IP Address : 192.168.0.0
Public IP Address: 11.99.77.111


Process finished with exit code 0

 

Share

Bijan Patel

Founder & Creator of QAScript | 12+ years of IT Experience | Full Stack Automation Engineer | Blogger | Trainer

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!