0% found this document useful (0 votes)
140 views

Commonly Asked Java Programming Interview Questions: Selfless (Freshersjob)

This document provides 15 code examples of common Java programming interview questions involving algorithms and data structures. The examples cover calculating the Fibonacci series, checking if a number is prime, checking if a string is a palindrome, finding the greatest common divisor of two numbers, performing a linear search on an array, and other fundamental programming concepts often explored during interviews.

Uploaded by

Snehal Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views

Commonly Asked Java Programming Interview Questions: Selfless (Freshersjob)

This document provides 15 code examples of common Java programming interview questions involving algorithms and data structures. The examples cover calculating the Fibonacci series, checking if a number is prime, checking if a string is a palindrome, finding the greatest common divisor of two numbers, performing a linear search on an array, and other fundamental programming concepts often explored during interviews.

Uploaded by

Snehal Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SELFLESS(FreShersjob)

Commonly Asked Java Programming Interview Questions

1. Fibonacci series

public class Fibonacci {

public static void main(String[] args) {

int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");

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


{
System.out.print(t1 + " + ");

int sum = t1 + t2;


t1 = t2;
t2 = sum;
}
}
}

2. Prime number

public class PrimeNumbers {

public static void main(String[] args) {

int num = 20, count;


for (int i = 1; i & lt; = num; i++) {
count = 0;
for (int j = 2; j & lt; = i / 2; j++) {
if (i % j == 0) {
count++;
break;
}
}

if (count == 0) {
System.out.println(i);
}

}
}
}

3. String Palindrome

class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");
str = sc.nextLine();

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + str.charAt(i);

if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");

}
}

4. Integer Palindrome

class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454; //It is the number variable to be checked for palindrome

temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}

5. Armstrong number

public class Armstrong {

public static void main(String[] args) {

int number = 371, originalNumber, remainder, result = 0;

originalNumber = number;

while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}

6. Factorial

public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

7. Reverse a String

public class ReverseString


{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);


String str = read.nextLine();
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}

System.out.println("Reversed string is:");


System.out.println(reverse);
}
}

8. GCD of two numbers

public class GCDExample1 {

public static void main(String[] args) {

//Lets take two numbers 55 and 121 and find their GCD
int num1 = 55, num2 = 121, gcd = 1;

for(int i = 1; i <= num1 && i <= num2; i++)


{
if(num1%i==0 && num2%i==0)
gcd = i;
}

System.out.printf("GCD of %d and %d is: %d", num1, num2, gcd);


}

9. Reverse words of sentence

public class Reverse {

public static void main(String[] args) {


String sentence = "Go work";
String reversed = reverse(sentence);
System.out.println("The reversed sentence is: " + reversed);
}

public static String reverse(String sentence)


{
if (sentence.isEmpty())
return sentence;

return reverse(sentence.substring(1)) + sentence.charAt(0);


}
}

10. Leap year

public class LeapYear {

public static void main(String[] args) {

int year = 1900;


boolean leap = false;

if(year % 4 == 0)
{
if( year % 100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year % 400 == 0)
leap = true;
else
leap = false;
}
else
leap = true;
}
else
leap = false;
if(leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}

11. String Anagram

import java.util.Arrays;

public class AnagramString {


static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}

public static void main(String[] args) {


isAnagram("Keep", "Peek");
isAnagram("Mother In Law", "Hitler Woman");
}
}

Output: Keep and Peek are anagrams


MotherInLaw and HitlerWoman are anagrams

12. To check whether input character is vowel or consonant.

import java.util.Scanner;
class JavaExample
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}

13. Linear Search


import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();

for (counter = 0; counter < num; counter++)


{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}
Output :

Enter number of elements:


6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3

14. Binary Search


import java.util.Scanner;
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();

//Creating array to store the all the numbers


array = new int[num];

System.out.println("Enter " + num + " integers");


//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;

while( first <= last )


{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) +
".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}
}
Output :Enter number of elements:

7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

15. Factorial using Recursion

import java.util.Scanner;
class FactorialDemo{
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is:
"+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
Output:

Enter the number:


5
Factorial of entered number is: 120

16. Floyd’s Triangle

import java.util.Scanner;

class FloydTriangle

public static void main(String args[])

int n, num = 1, c, d;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows of


Floyd'striangle to display");

n = in.nextInt();

System.out.println("Floyd's triangle:");

for (c = 1; c <= n; c++)

for (d = 1; d <= c; d++)

System.out.print(num+" ");

num++;
}

System.out.println(); // Moving to next row

Output :
Enter the number of rows of Floyd'striangle to display
6
Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

17. Find Frequency of Character

public class Frequency {

public static void main(String[] args) {


String str = "This website is awesome.";
char ch = 'e';
int frequency = 0;

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


if(ch == str.charAt(i)) {
++frequency;
}
}

System.out.println("Frequency of " + ch + " = " + frequency);


}
}

18. Print characters and their frequencies

public class Char_frequency {

static final int SIZE = 26;

// function to print the character and its


// frequency in order of its occurrence
static void printCharWithFreq(String str)
{
// size of the string 'str'
int n = str.length();

// 'freq[]' implemented as hash table


int[] freq = new int[SIZE];

// accumulate freqeuncy of each character


// in 'str'
for (int i = 0; i < n; i++)
freq[str.charAt(i) - 'a']++;

// traverse 'str' from left to right


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

// if frequency of character str.charAt(i)


// is not equal to 0
if (freq[str.charAt(i) - 'a'] != 0) {

// print the character along with its


// frequency
System.out.print(str.charAt(i));
System.out.print(freq[str.charAt(i) - 'a'] + "
");

// update frequency of str.charAt(i) to


// 0 so that the same character is not
// printed again
freq[str.charAt(i) - 'a'] = 0;
}
}
}

// Driver program to test above


public static void main(String args[])
{
String str = "geeksforgeeks";
printCharWithFreq(str);
}
}

Input : str = "elephant"


Output : e2 l1 p1 h1 a1 n1 t1

19. Remove/Delete all Vowels from String

import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
String strOrig, strNew;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");


strOrig = scan.nextLine();

System.out.print("Removing Vowels from The String ["


+strOrig+ "]\n");
strNew = strOrig.replaceAll("[aeiouAEIOU]", "");

System.out.print("All Vowels Removed


Successfully..!!\nNow the String is :\n");

System.out.print(strNew);
}
}
Output:
Enter a String : Deepak Patel
Removing Vowels from The String [Deepak Patel]
All Vowels Removed Successfully..!!
Now the String is :
Dpk Ptl

Regards,
Dharmesh
Jamali
Dhiraj
Krishna

You might also like