0% found this document useful (0 votes)
27 views20 pages

Java Coding Interview Questions for Freshers

The document provides solutions to commonly asked coding interview questions in Java for freshers, covering topics such as calculating factorials using recursion and iteration, changing character cases without built-in methods, and implementing binary search. It also includes programs for counting character occurrences, finding missing numbers in arrays, and generating combinations of strings. Each section contains code examples and expected outputs to illustrate the solutions effectively.

Uploaded by

arjunsai7
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)
27 views20 pages

Java Coding Interview Questions for Freshers

The document provides solutions to commonly asked coding interview questions in Java for freshers, covering topics such as calculating factorials using recursion and iteration, changing character cases without built-in methods, and implementing binary search. It also includes programs for counting character occurrences, finding missing numbers in arrays, and generating combinations of strings. Each section contains code examples and expected outputs to illustrate the solutions effectively.

Uploaded by

arjunsai7
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

Commonly Asked Coding Interview Questions In Java For

Freshers

1. How to find factorial of a number in Java using recursion and iteration.

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{

public static void main(String args[]) {

//finding factorial of a number in Java using recursion - Example


[Link]("factorial of 5 using recursion in Java is: " + factorial(5));

//finding factorial of a number in Java using Iteration - Example


[Link]("factorial of 6 using iteration in Java is: " + fact(6));
}

/*
* 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
*/

public static int fact(int number){


int result = 1;
while(number != 0){
result = result*number;
number--;
}

return result;
}
}

Output:

Factorial of 5 using recursion in Java is: 120


Factorial of 6 using iteration in Java is: 720
2. Change UpperCase to LowerCase and Lowercase to Uppercase Of all the characters In the string
without using built-in-Java

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.

We need to know about the UNICODE before we proceed.


Unicode is a character representation system that uses integers to represent characters. Unicode is the 16-bit representation of
each character, unlike ASCII, which is a 7-bit representation.

For lowercase letters that is for a,b,c,d…..x,y,z


the Unicode values lie in the range of 97,98,99,…….121,122

For uppercase letters that are A, B, C, D …… X, Y, Z


the Unicode values lie in the range of 65,66,67……89,90

Logic is that we check the Unicode of the character if the Unicode


lies between 97 to 122 then subtract 32 from that so that it will automatically be converted from lowercase to
uppercase Unicode integer representation of character while if the Unicode lies between 65 to 90 then add

32 from that number so that it will automatically be converted from uppercase to lowercase Unicode integer
representation of a character.

Please find the code below :

public class ChangeCase


{
static int i;
static void changecase(String s)
{
for(i=0;i<[Link]();i++) { int ch=[Link](i); if(ch>64&&ch<91) { ch=ch+32; [Link]( (char) ch); } else
if(ch>96&&ch<123)
{
ch=ch-32;
[Link]( (char) ch);
}
if(ch==32)
[Link](" ");
}
}

public static void main (String args[])


{

[Link]("Original String is : ");


[Link]("Alive is awesome ");
[Link]("Alive is awesome ");

}
}
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 [Link];
public class BinarySerarchMain {

public static int binarySearch(int[] sortedArray, int elementToBeSearched) {


int first = 0;
int last = [Link] - 1;

while (first < last) {

int mid = (first + last) / 2; // Compute mid point.

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
}
}

return -1; // Failed to find element


}

public static void main(String[] args)


{

int[] sortedArray={2,6,67,96,107,119,128,453};
int indexOfElementToBeSearched=binarySearch(sortedArray,67);
[Link]("Index of 74 in array is: " +indexOfElementToBeSearched);

int indexOfElementToBeSearchedNotFound=binarySearch(sortedArray,7);
[Link]("Index of 7 in array is: " +indexOfElementToBeSearchedNotFound);
}

When you run the above program, you will get the below output:

Index of 67 in array is: 2 Index of 7 in array is: -1


4. Java Program To Count Occurrences Of Each Character In String.

Solution :-

import [Link];
public class EachCharCountInString
{
private static void characterCount(String inputString)
{
//Creating a HashMap containing char as a key and occurrences as a value

HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

//Converting given string to char array

char[] strArray = [Link]();

//checking each char of strArray

for (char c : strArray)


{
if([Link](c))
{
//If char 'c' is present in charCountMap, incrementing it's count by 1

[Link](c, [Link](c)+1);
}
else
{
{
//If char 'c' is not present in charCountMap,
//putting 'c' into charCountMap with 1 as it's value

[Link](c, 1);
}
}

//Printing inputString and charCountMap

[Link](inputString+" : "+charCountMap);
}

public static void main(String[] args)


{
characterCount("Java J2EE Java JSP J2EE");

characterCount("All Is Well");

characterCount("Done And Gone");


}
}

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}

5. Java Program to find missing numbers

Solution:-

import [Link];
import [Link];
/**
* Java program to find missing elements in a Integer array containing

* numbers from 1 to 100.


*
* @author Javin Paul
*/
public class MissingNumberInArray {

public static void main(String args[]) {

// one missing number


printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);

// two missing number


printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);

// three missing number


printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);

// four missing number


printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);

// Only one missing number in array


int[] iArray new int[]{1 2 3 5};
int[] iArray = new int[]{1, 2, 3, 5};
int missing = getMissingNumber(iArray, 5);
[Link]("Missing number in array %s is %d %n",

[Link](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 - [Link];
BitSet bitSet = new BitSet(count);

for (int number : numbers) {


[Link](number - 1);
}

[Link]("Missing numbers in integer array %s, with total number %d is %n",


[Link](numbers), count);
int lastMissingIndex = 0;

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


lastMissingIndex = [Link](lastMissingIndex);
[Link](++lastMissingIndex);
}

/**
* Java method to find missing number in array of size n containing

* numbers from 1 to n only.


* can be used to find missing elements on integer array of

* numbers from 1 to 100 or 1 - 1000


*/
private static int getMissingNumber(int[] numbers, int totalCount) {
int expectedSum = totalCount * ((totalCount + 1) / 2);
int actualSum = 0;
for (int i : numbers) {
actualSum += i;
}

return expectedSum - actualSum;


}

Output

Missing numbers in integer array [1, 2, 3, 4, 6], with total number 6 is


5
Missing numbers in integer array [1, 2, 3, 4, 6, 7, 9, 8, 10], with total number 10 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 9, 8], with total number 10 is
5
7
10
Missing numbers in integer array [1, 2, 3, 4, 9, 8], with total number 10 is
5
6
7
10
Missing number in array [1, 2, 3, 5] is 4

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 [Link];
/**
* 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 {

public static void main(String args[]) {

// getting unsorted integer array for sorting


int[] randomOrder = getRandomArray(9);
[Link]("Random Integer array before Sorting : "
+ [Link](randomOrder));

// sorting array using insertion sort in Java


insertionSort(randomOrder);
[Link]("Sorted array uisng insretion sort : "
+ [Link](randomOrder));

// one more example of sorting array using insertion sort


randomOrder = getRandomArray(7);
[Link]("Before Sorting : " + [Link](randomOrder));
insertionSort(randomOrder);
[Link]("After Sorting : " + [Link](randomOrder));

// Sorting String array using Insertion Sort in Java


String[] cities = {"London", "Paris", "Tokyo", "NewYork", "Chicago"};
[Link]("String array before sorting : " + [Link](cities));
insertionSort(cities);
[Link]("String array after sorting : " + [Link](cities));
}

public static int[] getRandomArray(int length) {


int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = (int) ([Link]() * 100);
}
return numbers;
}

/*
* 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 < [Link]; 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
}

// compareIndex now denotes proper place for number to be sorted


array[compareIndex] = numberToInsert;
}
}

/*
* 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 < [Link]; 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]

7. Find all possible combinations of String.

Solution:-

public class Combinations {


private StringBuilder output = new StringBuilder();
private final String inputstring;
public Combinations( final String str ){
inputstring = str;
[Link]("The input string is : " + inputstring);
}

public static void main (String args[])


{
Combinations combobj= new Combinations("wxyz");
[Link]("");
[Link]("");
[Link]("All possible combinations are : ");
[Link]("");
[Link]("");
[Link]();
}

public void combine() { combine( 0 ); }


private void combine(int start ){
for( int i = start; i < [Link](); ++i ){
[Link]( [Link](i) );
[Link]( output );
if ( i < [Link]() )
combine( i + 1);
[Link]( [Link]() - 1 );
}
}
}

8. Write a program to find the factorial of a number.

Solution:-
package [Link].java2blog;
import [Link];

public class Factorial{


public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Enter the number to calculate Factorial: ");
int n = [Link]();
int f =1;
for(int i=n; i>0; i--){
f = f*i;
}
[Link]("Factorial of "+n+" is "+f);
}
}

When you run above program, you will get below output:

Enter the number to calculate Factorial:


5
Factorial of 5 is 120

9. Java Program To Find Continuous Sub Array In Array Whose Sum Is Equal To Number.

Solution:-

import [Link];

public class SubArrayWhoseSumIsNumber


{
static void findSubArray(int[] inputArray int inputNumber)
static void findSubArray(int[] inputArray, int inputNumber)
{
//Initializing sum with the first element of the inputArray

int sum = inputArray[0];

//Initializing starting point with 0

int start = 0;

//Iterating through inputArray starting from second element

for (int i = 1; i < [Link]; 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'

sum = sum - inputArray[start];

//Incrementing start by 1

start++;
}

//If 'sum' is equal to 'inputNumber' then printing the sub array

if(sum == inputNumber)
{
[Link]("Continuous sub array of "+[Link](inputArray)+" whose sum is "+inputNumber+" is ");

for (int j = start; j <= i; j++)


{
[Link](inputArray[j]+" ");
}

[Link]();
}
}
}

public static void main(String[] args)


{
findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);

findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);

findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);


}
}

Output :

Continuous sub array of [42, 15, 12, 8, 6, 32] whose sum is 26 is


12 8 6
Continuous sub array of [12, 5, 31, 13, 21, 8] whose sum is 49 is
5 31 13
Continuous sub array of [15, 51, 7, 81, 5, 11, 25] whose sum is 41 is
5 11 25

10. Java Program to draw Floyd’s Triangle

Solution:-

import [Link];
/**
* Java program to print Floyd's triangle up-to a given row
*
* @author Javin Paul
*/
public class FloydTriangle {

public static void main(String args[]) {


Scanner cmd = new Scanner([Link]);

[Link]("Enter the number of rows of Floyd's triangle, you want to display");


int rows = [Link]();
printFloydTriangle(rows);

/**
* Prints Floyd's triangle of a given row
*
* @param rows
*/
public static void printFloydTriangle(int rows) {
int number = 1;
[Link]("Floyd's triangle of %d rows is : %n", rows);

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


for (int j = 1; j <= i; j++) {
[Link](number + " ");
number++;
}

[Link]();
}
}

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

Enter the number of rows of Floyd's triangle, you want to display


10
Floyd's triangle of 10 rows is :
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

11. Prime Number Checker in Java

Solution:-
import [Link];
/**
* 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 [Link]
*/
public class PrimeTester {
public static void main(String args[]) {
Scanner scnr = new Scanner([Link]);
int number = Integer.MAX_VALUE;
[Link]("Enter number to check if prime or not ");
while (number != 0) {
number = [Link]();
[Link]("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) [Link](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) [Link](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

12. Bubble sort in java.

Solution:-
import [Link];
import [Link];
import [Link];
import [Link];

public class BubbleSort {

public static int[] bubbleSort(int[] list) {


for (int i = ([Link] - 1); i >= 0; i--) {
for (int j = 1; j <= i; j++) { if (list[j - 1] > list[j]) {
// swap elements at j-1 and j
int temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}

return list;
}

public static void main(String args[]) throws Exception


{
String list="";
int i=0,n=0;

BubbleSort s= new BubbleSort();


ArrayList arrlist=new ArrayList();
[Link](" ");
[Link](" ");
[Link]("Please enter the list of elements,one element per line");
[Link](" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader([Link]));
while(!(list=[Link]()).equalsIgnoreCase("stop")){
int intelement=[Link](list);
[Link](intelement);

int elementlist[] = new int[[Link]()];


Iterator iter = [Link]();
for (int j=0;[Link]();j++) {
elementlist[j] = [Link]();
}

elementlist=bubbleSort(elementlist);
[Link](" ");
[Link](" ");
[Link](" ");
[Link]( );
[Link]("Values after Bubble Sort : ");
for (int j=0;j<[Link];j++) {
[Link](elementlist[j]+" ");
}
}
}

13. Check if a number is odd or even.

Solution:-

It is a very basic question.

You need to check the remainder value when you divide a number by 2.

If it is 1 then it is odd else it is even.

package [Link].java2blog;
public class OddEvenCheckMain {

public static void main(String[] args) {


int number=27;

if ( number % 2 == 0 )
{
// If remainder is 0, it is even number
[Link]("Number is even");
}
else
{
// If remainder is 1, it is odd number
[Link]("Number is odd.");
}
}
}

When you run above program, you will get below output:

Number is odd.

14. Write a java program to find the intersection of two arrays.

(Using Iterative Method)

Solution:-

Using Iterative Method

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"};

HashSet set = new HashSet();

for (int i = 0; i < [Link]; i++)


{
for (int j = 0; j < [Link]; j++)
{
if(s1[i].equals(s2[j]))
{
[Link](s1[i]);
}
}
}

[Link](set); //OUTPUT : [THREE, FOUR, FIVE]


}
}

15. Write a java program to find the intersection of two arrays.

(Using retainAll() Method)

Solution:-

class CommonElements
{
public static void main(String[] args)
{
Integer[] i1 = {1, 2, 3, 4, 5, 4};

Integer[] i2 = {3, 4, 5, 6, 7, 4};


HashSet set1 = new HashSet<>([Link](i1));

HashSet set2 = new HashSet<>([Link](i2));

[Link](set2);

[Link](set1); //Output : [3, 4, 5]


}
}

16. Java Program to multiply two matrices in Java

Solution:-
import [Link];
/*
* Java Program to multiply two matrices
*/
public class MatricsMultiplicationProgram {

public static void main(String[] args) {

[Link]
.println("Welcome to Java program to calcualte multiplicate of two matrices");
Scanner scnr = new Scanner([Link]);

[Link]("Please enter details of first matrix");


[Link]("Please Enter number of rows: ");
int row1 = [Link]();
[Link]("Please Enter number of columns: ");
int column1 = [Link]();
[Link]();
[Link]("Enter first matrix elements");
Matrix first = new Matrix(row1, column1);
[Link]();

[Link]("Please enter details of second matrix");


[Link]("Please Enter number of rows: ");
int row2 = [Link]();
[Link]("Please Enter number of columns: ");
int column2 = [Link]();
[Link]();
[Link]();
[Link]("Enter second matrix elements");

Matrix second = new Matrix(row2, column2);


[Link]();

Matrix product = [Link](second);

[Link]("first matrix: ");


[Link]();
[Link]("second matrix: ");
[Link]();
[Link]("product of two matrices is:");
[Link]();

[Link]();

/*
* 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;

public Matrix(int row, int column) {


[Link] = row;
[Link] = column;
data = new int[rows][columns];
}

public Matrix(int[][] data) {


[Link] = data;
[Link] = [Link];
[Link] = data[0].length;
}

public int getRows() {


return rows;
}

public int getColumns() {


return columns;
}

/**
* fills matrix from data entered by user in console
*
* @param rows
* @param columns
*/
public void read() {
Scanner s = new Scanner([Link]);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data[i][j] = [Link]();
}
}

/**
*
* @param a
* @param b
* @return
*/
public Matrix multiply(Matrix other) {
if ([Link] != [Link]) {
throw new IllegalArgumentException(
"column of this matrix is not equal to row "
+ "of second matrix, cannot multiply");
}
int[][] product = new int[[Link]][[Link]];
int sum = 0;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link]; j++) {
for (int k = 0; k < [Link]; k++) {
sum = sum + data[i][k] * [Link][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++) {
[Link](data[i][j] + " ");
}
[Link]();
}
}

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

Enter first matrix elements


1
2
3
4
Please enter details of the second matrix
Please Enter number of rows: 2
Please Enter number of columns: 2

Enter second matrix elements


1
2
2
2
first matrix:
1 2
3 4
second matrix:
1 2
2 2
product of two matrices is:
5 11
22 36
22 36

Common questions

Powered by AI

The program uses nested loops, where the outer loop controls the number of rows and the inner loop manages numbers printed per row, incrementing a counter after each number. This systematic increment and structured loop ensure correct sequential number placement across rows .

The ChangeCase program checks each character's Unicode integer value to determine if it is uppercase (between 65 and 90) or lowercase (between 97 and 122). If uppercase, it adds 32 to convert it to lowercase, and if lowercase, it subtracts 32 to convert it to uppercase. Spaces (value 32) are printed as is .

The program initializes a BitSet with a size equal to the total count of expected numbers. It sets bits corresponding to numbers present in the array, then checks for clear bits which represent missing numbers. This is effective for multiple missing elements as the BitSet efficiently marks presence and absence in a compact form .

The iterative method compares elements of two arrays. For each match, the element is added to a HashSet, inherently handling duplicates by allowing each matching element only once in the set. This ensures the intersection contains unique elements common to both arrays .

The program ensures the number of columns in the first matrix matches the number of rows in the second to allow multiplication, where the element product-sum defines each entry in the resulting matrix. This structural requirement guarantees each array position results from a feasible pair multiplication .

The program uses a HashMap to store characters as keys and their occurrences as values. As it iterates over the character array of the input string, it checks if the character is already in the map; if so, it increments the count, otherwise it adds the character with a count of 1 .

The FizzBuzz program iterates numbers from 1 to 50. For each number, it checks divisibility by 3 and 5. If a number is divisible by both, it prints 'FizzBuzz'; if by only 3, 'Fizz'; if by only 5, 'Buzz'; otherwise, it prints the number itself .

The midpoint is crucial as it is used to divide the array into two halves, reducing the search space. If the element to be searched is less than the midpoint element, the search continues in the first half by adjusting the end index to mid; if greater, it continues in the second half by adjusting the start index to mid+1 .

Insertion sort iterates through the array, extracting each element (numberToInsert) and placing it by comparing with previous elements. If it is smaller than the preceding elements, it shifts those elements forward until the correct position is found. This repetitive comparison and shifting ensure elements are sorted incrementally .

The PrimeTester program checks if a number is prime by using an efficient approach that limits checks up to the square root of the number and skips even numbers after checking divisibility by 2. This reduction in checks minimizes the computational cost, improving efficiency .

You might also like