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

Coding Interview Questions in Java for Freshers _ PrepInsta

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Coding Interview Questions in Java for Freshers _ PrepInsta

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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


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 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<s.length();i++) { int ch=s.charAt(i); if(ch>64&&ch<91) { ch=ch+32; System.out.print( (char) ch); } else
if(ch>96&&ch<123)
{
ch=ch-32;
System.out.print( (char) ch);
}
if(ch==32)
System.out.print(" ");
}
}

public static void main (String args[])


{

System.out.println("Original String is : ");


System.out.println("Alive is awesome ");
ChangeCase.changecase("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 org.arpit.java2blog.thread;
public class BinarySerarchMain {

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


int first = 0;
int last = sortedArray.length - 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);
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:

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

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

//Converting given string to char array

char[] strArray = inputString.toCharArray();

//checking each char of strArray

for (char c : strArray)


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

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

//Printing inputString and charCountMap

System.out.println(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 java.util.Arrays;
import java.util.BitSet;
/**
* 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);
System.out.printf("Missing number in array %s is %d %n",

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);

for (int number : numbers) {


bitSet.set(number - 1);
}

System.out.printf("Missing numbers in integer array %s, with total number %d is %n",


Arrays.toString(numbers), count);
int lastMissingIndex = 0;

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


lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
System.out.println(++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 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 {

public static void main(String args[]) {

// getting unsorted integer array for sorting


int[] randomOrder = getRandomArray(9);
System.out.println("Random Integer array before Sorting : "
+ Arrays.toString(randomOrder));

// sorting array using insertion sort in Java


insertionSort(randomOrder);
System.out.println("Sorted array uisng insretion sort : "
+ Arrays.toString(randomOrder));

// one more example of sorting array using insertion sort


randomOrder = getRandomArray(7);
System.out.println("Before Sorting : " + Arrays.toString(randomOrder));
insertionSort(randomOrder);
System.out.println("After Sorting : " + Arrays.toString(randomOrder));

// Sorting String array using Insertion Sort in Java


String[] cities = {"London", "Paris", "Tokyo", "NewYork", "Chicago"};
System.out.println("String array before sorting : " + Arrays.toString(cities));
insertionSort(cities);
System.out.println("String array after sorting : " + Arrays.toString(cities));
}

public static int[] getRandomArray(int length) {


int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = (int) (Math.random() * 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 < 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
}

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

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;
System.out.println("The input string is : " + inputstring);
}

public static void main (String args[])


{
Combinations combobj= new Combinations("wxyz");
System.out.println("");
System.out.println("");
System.out.println("All possible combinations are : ");
System.out.println("");
System.out.println("");
combobj.combine();
}

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


private void combine(int start ){
for( int i = start; i < inputstring.length(); ++i ){
output.append( inputstring.charAt(i) );
System.out.println( output );
if ( i < inputstring.length() )
combine( i + 1);
output.setLength( output.length() - 1 );
}
}
}

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

Solution:-
package com.arpit.java2blog;
import java.util.Scanner;

public class Factorial{


public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number to calculate Factorial: ");
int n = in.nextInt();
int f =1;
for(int i=n; i>0; i--){
f = f*i;
}
System.out.println("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 java.util.Arrays;

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

sum = sum - inputArray[start];

//Incrementing start by 1

start++;
}

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

if(sum == inputNumber)
{
System.out.println("Continuous sub array of "+Arrays.toString(inputArray)+" whose sum is "+inputNumber+" is ");

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


{
System.out.print(inputArray[j]+" ");
}

System.out.println();
}
}
}

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 java.util.Scanner;
/**
* 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(System.in);

System.out.println("Enter the number of rows of Floyd's triangle, you want to display");


int rows = cmd.nextInt();
printFloydTriangle(rows);

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

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


for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}

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

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

12. Bubble sort in java.

Solution:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class BubbleSort {

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


for (int i = (list.length - 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();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);

int elementlist[] = new int[arrlist.size()];


Iterator iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}

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]+" ");
}
}
}

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 com.arpit.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
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.

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 < s1.length; i++)


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

System.out.println(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<>(Arrays.asList(i1));

HashSet set2 = new HashSet<>(Arrays.asList(i2));

set1.retainAll(set2);

System.out.println(set1); //Output : [3, 4, 5]


}
}

16. Java Program to multiply two matrices in Java

Solution:-
import java.util.Scanner;
/*
* Java Program to multiply two matrices
*/
public class MatricsMultiplicationProgram {

public static void main(String[] args) {

System.out
.println("Welcome to Java program to calcualte multiplicate of two matrices");
Scanner scnr = new Scanner(System.in);

System.out.println("Please enter details of first matrix");


System.out.print("Please Enter number of rows: ");
int row1 = scnr.nextInt();
System.out.print("Please Enter number of columns: ");
int column1 = scnr.nextInt();
System.out.println();
System.out.println("Enter first matrix elements");
Matrix first = new Matrix(row1, column1);
first.read();

System.out.println("Please enter details of second matrix");


System.out.print("Please Enter number of rows: ");
int row2 = scnr.nextInt();
System.out.print("Please Enter number of columns: ");
int column2 = scnr.nextInt();
System.out.println();
System.out.println();
System.out.println("Enter second matrix elements");

Matrix second = new Matrix(row2, column2);


second.read();

Matrix product = first.multiply(second);

System.out.println("first matrix: ");


first.print();
System.out.println("second matrix: ");
second.print();
System.out.println("product of two matrices is:");
product.print();

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;

public Matrix(int row, int column) {


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

public Matrix(int[][] data) {


this.data = data;
this.rows = data.length;
this.columns = 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(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

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

You might also like