Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
Now Reading
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Matrix multiplication in Java is the process of multiplying two matrices together. As a result, a new matrix is created with the results. It involves three steps. First, it iterates through the rows and columns of the matrices. Second, it multiplies the corresponding elements. Finally, it gathers the results to generate the resulting matrix.
In this tutorial, we will deal with the various concepts related to matrix multiplication in Java, Java programs to multiply two matrices, multiplication using for loops, and Java programs to multiply two matrices of any size, among other concepts.
Matrix multiplication is an arithmetic operation performed on matrices to obtain a new matrix by multiplying corresponding elements and summing the results. In Java, we can perform matrix multiplication with the help of nested loops to iterate over the elements of the matrices and apply the multiplication rule.
In the above example, matrix1 is a 2x3 matrix, and matrix2 is a 3x2 matrix. After performing the matrix multiplication, the resulting matrix will be a 2x2 matrix. The program prints the elements of the resulting matrix as the output.
Code:
public class upGradTutorials {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}}; // 2x3 matrix
int[][] matrix2 = {{7, 8}, {9, 10}, {11, 12}}; // 3x2 matrix
int rowsMatrix1 = matrix1.length;
int columnsMatrix1 = matrix1[0].length;
int columnsMatrix2 = matrix2[0].length;
// Create a new matrix to store the multiplication result
int[][] resultMatrix = new int[rowsMatrix1][columnsMatrix2];
// Perform matrix multiplication
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
for (int k = 0; k < columnsMatrix1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Print the result matrix
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
We start by defining two matrices, matrix1, and matrix2, with their respective dimensions. We determine the number of rows and columns for each matrix using the length property of arrays. We create a new matrix, resultMatrix, with dimensions equal to the number of rows in matrix1 and the number of columns in matrix2.
We use nested loops to perform the matrix multiplication. The outer loops iterate over the rows of matrix1 and the columns of matrix2. The inner loop iterates over the columns of matrix1 (or the rows of matrix2). Inside the innermost loop, we multiply the corresponding elements of matrix1 and matrix2 and accumulate the result in the corresponding position of resultMatrix.
Finally, we print the elements of resultMatrix to display the resulting matrix.
Here is the syntax for performing matrix multiplication in Java:
int[][] matrix1 = {
{element, element, element},
{element, element, element},
{element, element, element}
};
int[][] matrix2 = {
{element, element, element},
{element, element, element},
{element, element, element}
};
if (matrix1[0].length != matrix2.length) {
System.out.println("Matrix multiplication is not possible.");
return;
}
int[][] resultMatrix = new int[matrix1.length][matrix2[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
int sum = 0;
for (int k = 0; k < matrix1[0].length; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
resultMatrix[i][j] = sum;
}
}
In this program, we have two 2x2 matrices, matrix1 and matrix2. Like the previous program, it checks if the matrices are compatible for multiplication. If they are not compatible, it displays a message and exits.
If the matrices are compatible, the program creates a new matrix resultMatrix to store the multiplication result. It uses nested loops to iterate over the rows and columns of the matrices. For each element of the resulting matrix, it calculates the sum of the products of corresponding elements from the input matrices.
The calculated sum is then assigned to the corresponding position in resultMatrix. Finally, it prints the elements of resultMatrix, representing the product of the two matrices. You can modify the values and dimensions of matrix1 and matrix2 to perform matrix multiplication for different matrices.
Code:
public class upGradTutorials {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2}, {3, 4}}; // 2x2 matrix
int[][] matrix2 = {{5, 6}, {7, 8}}; // 2x2 matrix
int rowsMatrix1 = matrix1.length;
int columnsMatrix1 = matrix1[0].length;
int rowsMatrix2 = matrix2.length;
int columnsMatrix2 = matrix2[0].length;
if (columnsMatrix1 != rowsMatrix2) {
System.out.println("Matrix multiplication is not possible.");
return;
}
int[][] resultMatrix = new int[rowsMatrix1][columnsMatrix2];
// Perform matrix multiplication
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
int sum = 0;
for (int k = 0; k < columnsMatrix1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
resultMatrix[i][j] = sum;
}
}
// Print the resulting matrix
System.out.println("Resulting matrix:");
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
In the above program, we have two matrices matrix1 and matrix2. We first check the compatibility of matrices for multiplication by comparing the number of columns in matrix1 with the number of rows in matrix2. If they are incompatible, it displays a message and exits the program.
If the matrices are compatible, we create a new matrix resultMatrix to store the multiplication result. We use three nested for loops to iterate over the rows and columns of the matrices.
For each element of the resulting matrix, we calculate the sum of the products of corresponding elements from matrix1 and matrix2. The calculated sum is then assigned to the corresponding position in resultMatrix. Finally, we print the elements of resultMatrix, which represents the product of the two matrices.
Code:
public class upGradTutorials {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6}
};
int[][] matrix2 = {
{7, 8},
{9, 10},
{11, 12}
};
int rowsMatrix1 = matrix1.length;
int columnsMatrix1 = matrix1[0].length;
int rowsMatrix2 = matrix2.length;
int columnsMatrix2 = matrix2[0].length;
if (columnsMatrix1 != rowsMatrix2) {
System.out.println("Matrix multiplication is not possible.");
return;
}
int[][] resultMatrix = new int[rowsMatrix1][columnsMatrix2];
// Perform matrix multiplication
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
int sum = 0;
for (int k = 0; k < columnsMatrix1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
resultMatrix[i][j] = sum;
}
}
// Print the resulting matrix
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
This program follows a similar structure as the previous one. However, instead of using a separate variable to store the sum of products, we directly accumulate the result in the resultMatrix. This avoids unnecessary assignments and improves the efficiency of the multiplication process.
The innermost loop iterates over the common dimension of the matrices (columnsMatrix1 in matrix1 and rowsMatrix2 in matrix2). The elements from matrix1 and matrix2 are multiplied, and the result is added to the corresponding position in resultMatrix.
Finally, the program prints the elements of resultMatrix, which represents the product of the two matrices
This approach is more efficient because it reduces the number of variable assignments and eliminates the need for an intermediate sum variable.
Code:
public class upGradTutorials {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] matrix2 = {
{10, 11},
{12, 13},
{14, 15}
};
int rowsMatrix1 = matrix1.length;
int columnsMatrix1 = matrix1[0].length;
int rowsMatrix2 = matrix2.length;
int columnsMatrix2 = matrix2[0].length;
if (columnsMatrix1 != rowsMatrix2) {
System.out.println("Matrix multiplication is not possible.");
return;
}
int[][] resultMatrix = new int[rowsMatrix1][columnsMatrix2];
// Perform matrix multiplication
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
for (int k = 0; k < columnsMatrix1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Print the resulting matrix
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
Matrix multiplication is a fundamental operation in Java. It has many applications in maths and computer science. It serves as a handy tool for performing calculations. It also helps in transformations on multiple dimensions of data.
If you wish to learn more about matrix multiplication in Java, enroll in a credible course in computer science. Online learning platforms like upGrad provide the best-in-class courses for aspiring computer science experts. Visit upGrad to learn more.
1. Can matrices of different sizes be multiplied?
No, matrices of different sizes cannot be multiplied. For it to multiply, the number of columns in the first matrix must be the same as the number of rows in the second matrix.
2. How can I handle exceptions during matrix multiplication?
You can handle exceptions in Java by using try-catch blocks. For example, if the matrices have incompatible sizes for multiplication, you can catch an exception and handle it appropriately, such as displaying an error message or taking alternative actions.
3. Are there any optimization techniques for matrix multiplication in Java?
Yes, there are various optimization techniques for matrix multiplication, such as Strassen's algorithm or parallelization using multi-threading. These techniques can improve the efficiency of matrix multiplication for large matrices.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...