Coding Interview Questions in Java for Freshers _ PrepInsta
Coding Interview Questions in Java for Freshers _ PrepInsta
Freshers
Solution:-
In this section, we will see a complete code example of a Java program to calculate the factorial of a number in both
recursive and iterative ways.
If you look closely you will find that the recursive solution of calculating factorial is much easier to write and pretty intuitive to
read as it represents formula number*(number -1).
/**
* 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{
/*
* Java program example to find factorial of a number using recursion
* @return factorial of 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 number
*/
return result;
}
}
Output:
Solution:-
To adjust the case of a string, Java has built-in methods like toLowerCase() and toUpperCase(). However, what if we need to
change the case of any character in the string? Using basic logic, we can accomplish that goal.
32 from that number so that it will automatically be converted from uppercase to lowercase Unicode integer
representation of a character.
}
}
3. Search a number in a sorted array in o(logn) time?
Solution:-
You need to use binary search to search an element in an array in o(logn) time.
Code for binary search is :
package org.arpit.java2blog.thread;
public class BinarySerarchMain {
if (elementToBeSearched < sortedArray[mid]) { last = mid; // repeat search in first half. } else if
(elementToBeSearched > sortedArray[mid]) {
first = mid + 1; // Repeat sortedArray in last half.
} else {
return mid; // Found it. return position
}
}
int[] sortedArray={2,6,67,96,107,119,128,453};
int indexOfElementToBeSearched=binarySearch(sortedArray,67);
System.out.println("Index of 74 in array is: " +indexOfElementToBeSearched);
int indexOfElementToBeSearchedNotFound=binarySearch(sortedArray,7);
System.out.println("Index of 7 in array is: " +indexOfElementToBeSearchedNotFound);
}
When you run the above program, you will get the below output:
Solution :-
import java.util.HashMap;
public class EachCharCountInString
{
private static void characterCount(String inputString)
{
//Creating a HashMap containing char as a key and occurrences as a value
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
{
//If char 'c' is not present in charCountMap,
//putting 'c' into charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
System.out.println(inputString+" : "+charCountMap);
}
characterCount("All Is Well");
Output :
Java J2EE Java JSP J2EE : { =4, P=1, a=4, 2=2, S=1, E=4, v=2, J=5}
All Is Well : { =2, A=1, s=1, e=1, W=1, I=1, l=4}
Done And Gone : { =2, A=1, D=1, d=1, e=2, G=1, n=3, o=2}
Solution:-
import java.util.Arrays;
import java.util.BitSet;
/**
* Java program to find missing elements in a Integer array containing
Arrays.toString(iArray), missing);
}
/**
* A general method to find missing values from an integer array in Java.
* This method will work even if array has more than one missing element.
*/
private static void printMissingNumber(int[] numbers, int count) {
int missingCount = count - numbers.length;
BitSet bitSet = new BitSet(count);
/**
* Java method to find missing number in array of size n containing
Output
6. Write a Java program that prints the numbers from 1 to 50. But for multiples of three print
“Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are
multiples of both three and five print “FizzBuzz”
Solution:-
import java.util.Arrays;
/**
* Java program to sort an array using Insertion sort algorithm.
* Insertion sort works great with already sorted, small arrays but
* not suitable for large array with random order.
*
* @author Javin Paul
*/
public class InsertionSort {
/*
* Java implementation of insertion sort algorithm to sort
* an integer array.
*/
public static void insertionSort(int[] array) {
// insertion sort starts from second element
for (int i = 1; i < array.length; i++) { int numberToInsert = array[i]; int compareIndex = i; while (compareIndex > 0
&& array[compareIndex - 1] > numberToInsert) {
array[compareIndex] = array[compareIndex - 1]; // shifting element
compareIndex--; // moving backwards, towards index 0
}
/*
* Method to Sort String array using insertion sort in Java.
* This can also sort any object array which implements
* Comparable interface.
*/
/
public static void insertionSort(Comparable[] objArray) {
// insertion sort starts from second element
for (int i = 1; i < objArray.length; i++) { Comparable objectToSort = objArray[i]; int j = i; while (j > 0 &&
objArray[j - 1].compareTo(objectToSort) > 1) {
objArray[j] = objArray[j - 1];
j--;
}
objArray[j] = objectToSort;
}
}
Output:
Random Integer array before Sorting : [74, 87, 27, 6, 25, 94, 53, 91, 15]
Sorted array uisng insretion sort : [6, 15, 25, 27, 53, 74, 87, 91, 94]
Before Sorting : [71, 5, 60, 19, 4, 78, 42]
After Sorting : [4, 5, 19, 42, 60, 71, 78]
String array before sorting : [London, Paris, Tokyo, NewYork, Chicago]
String array after sorting : [Chicago, London, NewYork, Paris, Tokyo]
Solution:-
Solution:-
package com.arpit.java2blog;
import java.util.Scanner;
When you run above program, you will get below output:
9. Java Program To Find Continuous Sub Array In Array Whose Sum Is Equal To Number.
Solution:-
import java.util.Arrays;
int start = 0;
for (int i = 1; i < inputArray.length; i++) { //Adding inputArray[i] to the current 'sum' sum = sum + inputArray[i];
//If sum is greater than inputNumber then following loop is executed until //sum becomes either smaller than or equal
to inputNumber while(sum > inputNumber && start <= i-1)
{
//Removing starting elements from the 'sum'
//Incrementing start by 1
start++;
}
if(sum == inputNumber)
{
System.out.println("Continuous sub array of "+Arrays.toString(inputArray)+" whose sum is "+inputNumber+" is ");
System.out.println();
}
}
}
Output :
Solution:-
import java.util.Scanner;
/**
* Java program to print Floyd's triangle up-to a given row
*
* @author Javin Paul
*/
public class FloydTriangle {
/**
* Prints Floyd's triangle of a given row
*
* @param rows
*/
public static void printFloydTriangle(int rows) {
int number = 1;
System.out.printf("Floyd's triangle of %d rows is : %n", rows);
System.out.println();
}
}
Output :
Enter the number of rows of Floyd's triangle, you want to display
5
Floyd's triangle of 5 rows is :
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Solution:-
import java.util.Scanner;
/**
* Java Program to check if a number is Prime or Not. This program accepts a
* number from command prompt and check if it is prime or not.
*
* @author http://java67.blogspot.com
*/
public class PrimeTester {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println("Enter number to check if prime or not ");
while (number != 0) {
number = scnr.nextInt();
System.out.printf("Does %d is prime? %s %s %s %n", number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* @return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return "not valid";
}
if (num == 0 || num == 1) {
return "not prime";
}
if (num == 2 || num == 3) {
return "prime number";
}
if ((num * num - 1) % 24 == 0) {
return "prime";
} else {
return "not prime";
}
}
}
Output :
Enter number to check if prime or not
2? Does 2 is prime? true prime number true
3? Does 3 is prime? true prime number true
4? Does 4 is prime? false not prime false
5? Does 5 is prime? true prime true
6? Does 6 is prime? false not prime false
7? Does 7 is prime? true prime true
17? Does 17 is prime? true prime true
21? Does 21 is prime? false not prime false
131? Does 131 is prime? true prime true
139? Does 139 is prime? true prime true
Solution:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
return list;
}
elementlist=bubbleSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println( );
System.out.println("Values after Bubble Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
}
Solution:-
You need to check the remainder value when you divide a number by 2.
package com.arpit.java2blog;
public class OddEvenCheckMain {
if ( number % 2 == 0 )
{
// If remainder is 0, it is even number
System.out.println("Number is even");
}
else
{
// If remainder is 1, it is odd number
System.out.println("Number is odd.");
}
}
}
When you run above program, you will get below output:
Number is odd.
Solution:-
In this method, we iterate both the given arrays and compare each element of one array with elements of the
other arrays.
If the elements are found to be equal, we will add that element to HashSet.
This method also works for those arrays which contain duplicate elements.
class CommonElements
{
public static void main(String[] args)
{
String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};
String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};
Solution:-
class CommonElements
{
public static void main(String[] args)
{
Integer[] i1 = {1, 2, 3, 4, 5, 4};
set1.retainAll(set2);
Solution:-
import java.util.Scanner;
/*
* Java Program to multiply two matrices
*/
public class MatricsMultiplicationProgram {
System.out
.println("Welcome to Java program to calcualte multiplicate of two matrices");
Scanner scnr = new Scanner(System.in);
scnr.close();
/*
* Java class to represent a Matrix. It uses a two dimensional array to
* represent a Matrix.
*/
class Matrix {
private int rows;
private int columns;
private int[][] data;
/**
* fills matrix from data entered by user in console
*
* @param rows
* @param columns
*/
public void read() {
Scanner s = new Scanner(System.in);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data[i][j] = s.nextInt();
}
}
/**
*
* @param a
* @param b
* @return
*/
public Matrix multiply(Matrix other) {
if (this.columns != other.rows) {
throw new IllegalArgumentException(
"column of this matrix is not equal to row "
+ "of second matrix, cannot multiply");
}
int[][] product = new int[this.rows][other.columns];
int sum = 0;
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < other.columns; j++) {
for (int k = 0; k < other.rows; k++) {
sum = sum + data[i][k] * other.data[k][j];
}
product[i][j] = sum;
}
}
return new Matrix(product);
}
/**
*
* @param matrix
*/
public void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
Output:
Welcome to Java program to calculate multiplicate of two matrices
Please enter details of the first matrix
Please Enter number of rows: 2
Please Enter number of columns: 2