Top Java Programs asked in Interviews to Beginners and Experienced

Interviews in data sciences where you go as a fresher or as an experienced person, you will be asked about the coding of programs or how to frame programs for given outputs. This article consists of twenty questions mostly asked Java programming in job interviews. You can learn, practice and prepare Java Programs for interviews, exams, or skill enhancement through this article. We will start with an introduction to Java for a better and clear understanding of the Programs.

What is Java? 

Sun Microsystems made Java, a programming language and computing platform, available for the first time in 1995. It has grown to power a big part of the digital world from its small beginnings. It provides a solid foundation on which many services and apps are built. Java is still used in the future to create high-tech products and digital services.

Java Programs for Freshers and Experienced to Practice 

The following are some examples of basic Java programs, so practice the list and prepare yourself for work and interviews. This includes string programs, sorting, string, use of scanner class, etc.

Write a program to swap two numbers in Java.
Two ways to do this -with third variable and without third variable.


public static void swapNumberswithtemp(int a, int b) { //using 3rd variable

int temp = a;

a = b;

b = temp;

}

public static void swapNumberswithouttemp(int a, int b) {//without using 3rd variable

b = b + a;

a = b – a;

b = b – a;

}

public static void main(String[] args) {

int a = 10;

int b = 20;

swapNumbers(a, b);

System.out.printf(“%d %d”, a, b);

Write a program to print all the elements of Fibonacci series

.
A Fibonacci series is given by Fib(n)=Fib(n-1)+Fib(n-2)


public static int fibonacci(int number){

    if(number == 1 || number == 2){ //base case

        return 1;

    }

    return fibonacci(number-1) + fibonacci(number -2); 

}  

public static void main(String args[]) {

    int number = new Scanner(System.in).nextInt();

    for(int i=1; i<=number; i++){

        System.out.print(fibonacci2(i) +” “);

    }    

 }

Check if the given number is palindrome or not.

Java Programs

A palindrome is a number which is when reversed give the same number. We find the reverse and check whether it is equal to the given number or not.


public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    String str = in.nextLine();

    int length = str.length();         

    boolean isPalindrome = true;          

    for(int i = 0; i < length; i++)

    {

        if(str.charAt(i) != str.charAt(length-1-i)) {

            System.out.println(“Snot a palindrome.”);

            isPalindrome = false;

            break;

        }

    }          

    if(isPalindrome) {

        System.out.println(“palindrome.”);

    }

 }

Write a program to find whether a number is an Armstrong number or not.


Armstrong number – Sum of the cubes of its digit is equal to the number itself. E.g – 153


public static void main(String[] args) 

{

    int num = Integer.parseInt(args[0]);

    int temp = num;

    int count = 0;

    int sum = 0;

    while(num > 0)   

    {

        num = num / 10;

        count++;

    }

    num = temp;

    while (num > 0)

    {

        int rem = num % 10;

        int val = 1;

        for(int i = 1; i <= count; i++)

        {   

            val = val * rem;

        }

        num = num / 10;

        sum = sum + val;

    }   

    if(temp == sum)

        {

            System.out.println(“Armstrong number”);

        }

        else

        {

            System.out.println(“Not an armstrong number”);

        }   

}

Find the GCD of two numbers in logn time.


The greatest common divisor of two integers, a and b, is shown by the symbol gcd (a, b). We must list all the factors of the numbers and identify the biggest common factor in order to determine the gcd of the numbers. As a result, we can say that among the three numbers, 4 has the biggest common factor.


public static int gcd(int a, int b) {

while (((a > 0) && (b > 0))) {

  if ((a > b)) {

    a = (a % b);

  } else {

    b = (b % a);

  }

}

if ((a == 0)) {

  return b;

} else {

  return a;

}

}  

public static void main(String[] args) {

int a = new Scanner(System.in);

int b = new Scanner(System.in);

System.out.println(GCD.gcd(a, b));

}

Write a program to find the sum of n natural numbers


The formula for the product of n natural numbers is [n(n+1)]/2. Natural numbers are those that begin at 1 and go all the way to infinity. Except for the number 0, natural numbers only contain whole integers.


summation of i from 1 to n=n*(n+1)/2

public static void main(String arg[]){

              int n,sum=0;

              Scanner sc=new Scanner(System.in);

                sum = (n*(n+1))/2;

               System.out.println(sum);                  

            }

Write a program to find the lcm of two numbers.


The lowest number that may be divided by both numbers is the LCM (Least Common Multiple) of two numbers. LCM of 15 and 20 is 60, for instance, while LCM of 5 and 7 is 35. Finding the union of all the elements contained in both numbers is a straightforward way to solve the problem.


private static int getGCD(int num1, int num2) {

while (num2 > 0) {

    int temp = num2;

    num2 = num1 % num2;

    num1 = temp;

}

return num1;

}

private static int getLCM(int num1, int num2) {

return num1 * (num2 / getGCD(num1, num2));

}

Calculate the sum of digits of a given number.


By adding a number’s digits without considering for place values, we may determine the amount of digits that make up the sum. Therefore, using the number 567 as a starting point, we may compute the digit total as 5 + 6 + 7 = 


public static void main(String args[]){

 long number=-9999,input=-9999;

    try{    

       number=Long.parseLong(System.console().readLine());

       input=number;    

    }catch(NumberFormatException nfe){

       System.exit(1);    

      }

    long remainder=0,total=0;

    while(number > 0){

        remainder=number % 10;

        total+=remainder;

        number=number/10;

     }

    System.out.println(total);

}

Write a program to reverse a string.


Reversing the characters in a string is possible using the built-in function reverse() of the StringBuilder or StringBuffer class. By using this technique, the characters are substituted in the opposite order. In Java, the static method with the necessary logic to reverse a string is called reverse.


public static void main(String args[]) {

    String word = “HelloWorld”;

    String reverse = new StringBuffer(word).reverse().toString();

    word = “thisisstring”;

    reverse = new StringBuilder(word).reverse().toString();

    System.out.printf(reverse);

}     

public static String reverse(String source){

    if(source == null || source.isEmpty()){

        return source;

    }       

    String reverse = “”;

    for(int i = source.length() -1; i>=0; i–){

        reverse = reverse + source.charAt(i);

    }      

    return reverse;

   }

Can you find the second highest number in given array?


Running two loops is an easy way to discover the second biggest member in an array. The first loop will locate the array’s greatest member. The second loop will then search the array for the biggest member that is smaller than first largest.


public static void main(String[] args)

{

    int arr[] = { 1,4,2,3,5};

    int largest = 0;

    int secondLargest = 0;

    for (int i = 0; i < arr.length; i++)

    {

        System.out.print(arr[i] + “\t”);

    }

    for (int i = 0; i  largest)

        {

            secondLargest = largest;

            largest = arr[i];

        }

        else if (arr[i] > secondLargest)

        {

            secondLargest = arr[i];

        }

    }

    System.out.println(secondLargest);

  }

Find the first repeating element In the array.


The HashSet data structure is the usual method for locating duplicate entries in an array. If you recall, duplicates are not permitted with the Set abstract data type. This attribute may be used to filter out duplicate items.


void firstrep(int a[], int n) 

{

    Set set = new HashSet();

    int firstrepeating = -1;

    for (int i = 0; i < n; i++){            

        if (set.contains(a[i])) {

            majority = i;

        } else {

            set.add(a[i]);

        }

    }        

    System.out.println(a[firstrepeating]);

}

public static void main(String[] args) 

{

    int arr[] = {1, 2, 5, 4, 5, 5, 1, 2};

    int n = arr.length;

    firstrep(arr,n);

}

Write a program to find two elements in the array whose sum is near to zero.


Given below is the solution where we using two pointer approach.


public static void main (String[] args) 

{

  int arr[] = {3, 2, -1, 9, -8, 6};

  int size = arr.length;

  int l, r, min_sum, sum, min_l_num, min_r_num;      

  min_l_num = 0;

  min_r_num = 1;

  min_sum = arr[0] + arr[1];      

  for(l = 0; l < size – 1; l++)   {

    for(r = l+1; r  Math.abs(sum))

      {

        min_sum = sum;

        min_l_num = l;

        min_r_num = r;

      }

    }

  }

  System.out.println(arr[min_l_num],arr[min_r_num]);

}

You Must Like: Cracking the Code: 36 Python Interview Questions You Need to Know

What is Singleton and write a program to describe it.


Singleton class in Java has only one instance in the whole program. We can easily implement a singleton class with thread safe property. We can see the implementation below –


public class Javasingleton

{

private static  volatile Javasingleton  singleinstance;

private Javasingleton(){}

public static   Javasingleton  getInstance()

{

    if (singleinstance ==null )

    {

        synchronized(Javasingleton.class)

        {

            if (singleinstance ==null )

            {

                singleinstance=new Javasingleton();

            }

        }

    }

    return singleinstance ;

}

}

Write a code to print all the first n prime numbers where n will be given as input.


According to the formal definition, a number “n” is prime if it can only be divided by 1 and n. To put it another way, a number is prime if it cannot be divided by any integer between 2 and n-1.


public static void main(String[] args) {

    int N = 200;

    int k;

    Scanner sc = new Scanner(System.in);

    k = sc.nextInt();

    int i = 0;

    for (int num = 2; num <= N; num++) {

        if (isPrimeNumber(num) && i!=k) {

            System.out.println(num);

            i++;

        }

    }

}

public static boolean isPrimeNumber(int num) {

    for (int i = 2; i 0)

      {

        RevNumber=(RevNumber*10)+(n%10);

        n=n/10;

      }

      return  (int) RevNumber;   

    }

Can you write the Bubble Sort Algorithm?


The idea is to bubble out the greater numbers to the right.


public void sort(int[] numbers) {

validateInput(numbers);

int length = numbers.length;

boolean swap = true;

while (swap) {

  swap = false;

  for (int i = 0; i < length – 1; i++) {

    for (int j = 0; j  numbers[j + 1]) {

        swap(numbers, j, j + 1);

        swap = true;

      }

    }

  }

}

}

  }

Implement the merge Sort algorithm.


This is a Divide and conquer algorithm.


public static void main(String[] args) {

    int[] list = {4,5,2,1,3};

    mergeSort(list, 0, list.length – 1);

}

public static void mergeSort(int[] a, int first, int last)

  {

    if(last – first == 0) 

    {

    }

    else if (last – first == 1) 

    {

        if(a[first] > a[last])

        {

            int temp = a[first];

            a[first] = a[last];

            a[last] = temp;

        }

    }

    else    

    {

        int mid = (first + last) / 2;

        mergeSort(a, first, mid);

        mergeSort(a, mid + 1, last);

        merge(a, first, mid, last);

    }

  }

private static void merge(int[] a, int first, int mid, int last)

  {

    int[] temp = new int[last – first + 1];

    int i = first; int j = mid + 1;

    for(int k = first; k  mid || j > last)

        {

            if(i > mid && j <= last)

            {

                System.out.println(“a[j]: ” + a[j]);

                temp[k – first] = a[j];

                j++;

            }

            else if(i  last)

            {

                System.out.println(“a[i]: ” + a[i]);

                temp[k – first] = a[i];

                i++;

            }

            else

            {

                break;

            }

        }

        else

        {

            if(a[i] < a[j])

            {

                temp[k – first] = a[i];

                i++;

            }

            else

            {

                temp[k – first] = a[j];

                j++;

            }

        }

    }

    for(int count = 0; count < temp.length; count++)

    {

        a[first + count] = temp[count];

    }

      }

Write a program to get the sum of even numbers and odd number in an array.

first create an array with elements. To obtain the sum, define and initialise three variables with the values I evenSum, and oddSum. Next, use the “for loop” command to take each individual element out of the array.


public static void main(String[] args) 

{

    int n, sumeven= 0, sumodd = 0;

    Scanner s = new Scanner(System.in);

    n = s.nextInt();

    int[] a = new int[n];

    for(int i = 0; i < n; i++)

    {

        a[i] = s.nextInt();

    }

    for(int i = 0; i  0)

{

bin[i++] = n%2;

   n = n/2;

}

for(int j = i-1;j >= 0;j–)

{

   System.out.print(bin[j]);

}

}

Write a program to add two binary numbers.


Begin adding from the right side, and when more than one is returned, store the carry for the next numbers.


public static void main(String[] args)

{     

long b1, b2;

int i = 0, carry = 0;

int[] sum = new int[10];

Scanner scanner = new Scanner(System.in);

b1 = scanner.nextLong();

b2 = scanner.nextLong();

while (b1 != 0 || b2 != 0) 

{

    sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);

    carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);

    b1 = b1 / 10;

    b2 = b2 / 10;

}

if (carry != 0) {

    sum[i++] = carry;

}

–i;

while (i >= 0) {

    System.out.print(sum[i–]);

}

System.out.print(“\n”);  

}

Conclusion –

So these are the Most commonly asked Java programs in interviews. We hope you find it helpful and reliable source of information.

Press ESC to close