The IT industry is actively expanding, and almost every company is looking for candidates to fill open positions. Java is perhaps one of the most widely used programming languages today. Understanding the Java programs for interview is critical for anyone looking to break into the IT industry. Because of its popularity, it is one of the most sought-after programming languages in the IT industry.
Java is a general-purpose language that supports both object-oriented and procedural programming styles. It has been around since 1995 and is one of the first object-oriented programming languages to be created.
However, the language is used to develop a wide variety of applications and is important for businesses, government agencies, schools, and anyone who wants to create an app.
As a fresher, you might wonder what kind of Java programs interview questions you will be asked to write in an interview. While the specific programs will vary depending on the company and position you are interviewing for, here are some commonly asked general categories.
How To Prepare For a Java Programs Interview
A Java interview can be a daunting experience. However, if you are well-prepared, you can ace the interview and land the job. To prepare for a Java interview, you should first learn the basics of the language.
Next, you should practice answering common interview questions.
Finally, you should familiarise yourself with the company’s culture and expectations. Following these steps can increase your chances of landing the job you want.
Here are the top 8 Java programs asked about in interviews:
Top 8 Java Programs Asked In Interview for Freshers With Solution
Prepare yourself for the interview process with these commonly asked questions from past interviews:
1. The Fibonacci series
This is a very commonly asked Java programs interview question. Starting with 0 and 1, the Fibonacci series is a series of elements in which the previous two elements are added to get the next element.
Any number of integers from the Fibonacci series can be displayed using this programme. Each number in the Fibonacci sequence equals the sum of the two numbers before it.
For the above method, here is a Java programme:
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
int counter = 0;
// Iterate till counter is N
while (counter < N) {
// Print the number
System.out.print(num1 + ” “);
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
counter = counter + 1;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}
Also Read: Common C++ Questions to Know for Tech Interviews
2. Checking for prime number
You will be expected to write a programme to determine whether a given number is prime or composite. A prime number is greater than 1 and can only be divided by 1 or itself.
For instance, Prime numbers include 2, 3, 5, 7, 11, 13, and 17. We’ll take a number variable and verify whether it’s prime or not in this Java programme. Let’s look at a Java prime number programme:
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+” is not prime number”);
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+” is not prime number”);
flag=1;
break;
}
}
if(flag==0)Â { System.out.println(n+” is prime number”); }
}//end of else
}
}
After you run the above code, you’d receive the number 3 as Output (prime number).
3. String palindrome
It is a program that determines whether or not a given string is a palindrome. A palindrome is a string, which, when read forward and backward, means the same. Although to check whether or not a string is a palindrome, a string needs to be compared with its reverse.
So let us consider two strings, “12121” and “apple”, now the task is to find out if its reverse string is the same as it is.
package org.arpit.java2blog;
import java.util.Scanner;
public class StringFullLoopPalindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter string : “);
String str = scanner.nextLine();
String reverseStr = “”;
for(int i = str.length() – 1; i >= 0; i–){
reverseStr = reverseStr + str.charAt(i);
}
if(str.equals(reverseStr)){
System.out.println(“String is palindrome”);
} else {
System.out.println(“String is not palindrome”);
}
}
}
When you run the above program, you will get below output:
Enter string : 12121
String is palindrome
Enter a string: Apple
String is not a palindrome
4. Bubble sortÂ
You may be asked to write a code snippet to implement bubble sort. Bubble Sort is the most basic sorting algorithm, and it works by repeatedly swapping adjacent elements if they are out of order. However, because of its average and worst-case time complexity, this algorithm is unsuitable for large data sets.
In each iteration, each element of the array moves to the end of the array, similar to how air bubbles rise to the water’s surface. That’s why it’s referred to as a bubble sort.
The code below is the solution to a common Java interview question about bubble sort:
// Bubble sort in Java
import java.util.Arrays;
class Main {
// perform the bubble sort
static void bubbleSort(int array[]) {
int size = array.length;
// loop to access each array element
for (int i = 0; i < size – 1; i++)
// loop to compare array elements
for (int j = 0; j < size – i – 1; j++)
// compare two adjacent elements
// change > to < to sort in descending order
if (array[j] > array[j + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
public static void main(String args[]) {
int[] data = { -2, 45, 0, 11, -9 };
// call method using class name
Main.bubbleSort(data);
System.out.println(“Sorted Array in Ascending Order:”);
System.out.println(Arrays.toString(data));
}
}
5. Armstrong number
An Armstrong number is simply the sum of the cubes of its digits. This is a Java programme to verify whether or not a given number is an Armstrong number.
As an input, you need to enter the integer to be checked. Then, you can use modulos and division operations, loops and if-else statements to get the output.
Here is the Java source code for checking if a given number is an Armstrong number. The output of the programme is also shown below.
import java.util.Scanner;
public class ArmStrong
{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print(“Enter any integer you want to check:”);
n = s.nextInt();
a = n;
c = n;
while(a > 0)
{
a = a / 10;
count++;
}
while(n > 0)
{
b = n % 10;
sum = (int) (sum+Math.pow(b, count));
n = n / 10;
}
if(sum == c)
{
System.out.println(“Given number is Armstrong”);
}
else
{
System.out.println(“Given number is not Armstrong”);
}
}
}
Output:
$ javac ArmStrong.java
$ java ArmStrong
Enter any integer to be checked: 153
The given number is Armstrong.
Also Read: 10 Tricky Java Programming Questions to Ace Your Interview
6. Merge Sort
Merge Sort is one of the most effective sorting algorithms, operating on the divide-and-conquer principle. It is built on the notion of breaking down a list into several sub-lists, each of which contains a single element. Then merge those sublists in a way that produces a sorted list.
Here’s the code example to Merge Sort:
public class MergeSort {
public static void main(String[] args) {
int[] arr = { 70, 50, 30, 10, 20, 40, 60 };
int[] merged = mergeSort(arr, 0, arr.length – 1);
for (int val : merged) {
System.out.print(val + ” “);
}
}
public static int[] mergeTwoSortedArrays(int[] one, int[] two) {
int[] sorted = new int[one.length + two.length];
int i = 0;
int j = 0;
int k = 0;
while (i < one.length && j < two.length) {
if (one[i] < two[j]) {
sorted[k] = one[i];
k++;
i++;
} else {
sorted[k] = two[j];
k++;
j++;
}
}
if (i == one.length) {
while (j < two.length) {
sorted[k] = two[j];
k++;
j++;
}
}
if (j == two.length) {
while (i < one.length) {
sorted[k] = one[i];
k++;
i++;
}
}
return sorted;
}
public static int[] mergeSort(int[] arr, int lo, int hi) {
if (lo == hi) {
int[] br = new int[1];
br[0] = arr[lo];
return br;
}
int mid = (lo + hi) / 2;
int[] fh = mergeSort(arr, lo, mid);
int[] sh = mergeSort(arr, mid + 1, hi);
int[] merged = mergeTwoSortedArrays(fh, sh);
return merged;
}
}
7. Factorial
Factorial is one of the simplest and most popular Java programs and is commonly asked in Java interviews and other programming languages such as C or C++. For example, the interviewer may examine converting a recursive solution to an iterative one or vice versa.
The factorial of a number is calculated using the formula number*(number -1) until zero. Because the value of factorial zero is 1, it serves as the base case in the recursive version of the factorial method.
Also, let’s look at a complete code example of a Java programme that calculates a number’s factorial in both recursive and iterative ways.
However, if you look closely, you will notice that the recursive solution to calculating factorial is much easier to write and read because it represents the formula number* (number -1).
Here’s an example of a Java programme for calculating a number’s factorial:
/**
* Simple Java program to find the factorial of a number using recursion and iteration.
* Iteration will use for loop while recursion will call method itself
*/
public class FactorialInJava{
public static void main(String args[]) {
//finding factorial of a number in Java using recursion – Example
System.out.println(“factorial of 5 using recursion in Java is: ” + factorial(5));
//finding factorial of a number in Java using Iteration – Example
System.out.println(“factorial of 6 using iteration in Java is: ” + fact(6));
}
/*
* Java program example to find factorial of a number using recursion
* @return factorial of a number
*/
public static int factorial(int number){
//base case
if(number == 0){
return 1;
}
return number*factorial(number -1); //is this tail-recursion?
}
/*
* Java program example to calculate factorial using while loop or iteration
* @return factorial of a number
*/
public static int fact(int number){
int result = 1;
while(number != 0){
result = result*number;
number–;
}
return result;
}
}
When you run the above program and you will get the below output:
- The factorial of 5 using recursion in Java is 120.
- Also, the factorial of 6 using iteration in Java is 720.
8. Reversing strings
Strings are character sequences in Java. They are one of Java’s most popular data structures. While programming, you may be required to reverse a string in Java.
Consider a crossword puzzle: the answer to the clue is nothing but a string, and the letters that make up the answer are characters.
There are different ways to reverse a string in Java, and we’ll look at the most common method – By using toCharArray()
The toCharArray() function is one way to reverse a string in Java.
public static String reverse(String str) {
String rev = “”;
char[] finalarray = str.toCharArray();
for (int i = finalarray.length – 1; i >= 0; i–)
rev += finalarray[i];
return rev;
}
//Sample Input- “Scaler Academy”
//Sample Output-“ymedacA relacS”
Also Read: Critical Tips To Ace Cognizant Genc Next Coding Questions For Freshers
Final Thoughts
So, we’ve covered the top 8 Java Programs interview questions for Freshers in this article. You can also find various questions from other sources. The key to success in the Java interview is to answer as many questions as possible. The more programs you can code, the better your chances of getting through the interview.
Being certified also gives you an advantage during the interview. So, if you haven’t already validated your Java expertise, we recommend checking out CodeQuotient’s SuperCoders Internship Program. You can thoroughly master all the concepts in this program while earning a placement! Apply today for a successful career in the tech industry.