Find the Largest Element in a Matrix in Java

In this post, you will learn how to find the largest element in a given Matrix in Java. To find the largest element in a matrix (2D array) in Java, you can use a similar approach as finding the smallest element, but instead of looking for smaller elements, you’ll look for larger ones.

Here’s a Java program logic to find the largest element in a matrix:

package com.javacodepoint.array.multidimensional;

public class LargestElementInMatrix {
	
	public static int findLargestElement(int[][] matrix) {
		if (matrix == null || matrix.length == 0) {
			throw new IllegalArgumentException("Input matrix is null or empty.");
		}

		int largest = matrix[0][0]; // Initialize with the first element of the matrix

		// Iterate through the matrix and update the largest value 
		// if a larger element is found
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				if (matrix[i][j] > largest) {
					largest = matrix[i][j];
				}
			}
		}

		return largest;
	}

	public static void main(String[] args) {
		int[][] matrix = { { 14, 12, 6 }, { 8, -3, 10 }, { 5, 19, 7 } };

		int largestElement = findLargestElement(matrix);

		System.out.println("Matrix:");
		for (int[] row : matrix) {
			for (int value : row) {
				System.out.print(value + " ");
			}
			System.out.println();
		}

		System.out.println("The largest element in the matrix: " + largestElement);
	}
}

OUTPUT:

Matrix:
14 12 6
8 -3 10
5 19 7
The largest element in the matrix: 19

Explanation:

In this program, we have a findLargestElement method that takes a 2D matrix as input and returns the largest element in the matrix.

We initialize the largest variable with the value of the first element of the matrix (matrix[0][0]). Then, we iterate through the matrix using nested loops. For each element, we compare it with the current value of largest. If the element is larger than largest, we update largest to the value of the element.

After iterating through the entire matrix, largest will contain the largest element.

Learn also: Find the Smallest Element in a Matrix.

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *