Member-only story

Java Interview Programs With Solutions

Gain Java Knowledge
4 min readOct 26, 2024

--

If you’re interviewing for a Java programming role, then your coding skills will probably be tested. Whether you’re a beginner in Java or an expert programmer, this article provides some common Java interview questions and answers to help you prepare.

  1. How do you reverse a string in java ?

There is no reverse() utility method in the String class. However, you can create a character array from the string and then iterate it from the end to the start. You can StringBuilder class reverse() to return the reversed string.

public class ReverseString {
public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
}
}

2. How do you check whether a string is a palindrome in Java?

A palindrome string is the same string backwards or forwards. To check for a palindrome, you can reverse the input string and check if the result is equal to the input.

public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversed);
System.out.println(isPalindrome);
}
}

3. Write a Java program to print a Fibonacci sequence.

A Fibonacci sequence is one in which each number is the sum of the two previous numbers.

public class Fibonacci {
public static void main(String[] args) {
int n = 10, first = 0, second = 1;
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}

4. How can you find the factorial of an integer in Java?

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number:

public class Factorial {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}…

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet

Write a response