Java In-Class Exercises: Arrays and 2D
Arrays
Simple Exercises
• Initialize and Print an Array
- Create an integer array of size 5.
- Initialize it with the first five natural numbers.
- Print all elements using a for loop.
• Sum of Elements in an Array
- Given an integer array, write a method that calculates and returns the sum of all
elements.
• Find Maximum and Minimum
- Given an array of integers, find and print the maximum and minimum values.
• Reverse an Array
- Write a method that reverses the elements of an integer array in-place.
Intermediate Exercises
• 2D Array Initialization and Traversal
- Create a 3x3 2D integer array.
- Initialize it with values 1 to 9.
- Print the 2D array in matrix form.
• Sum of Rows and Columns in a 2D Array
- Given a 2D integer array, write methods to compute:
- Sum of each row.
- Sum of each column.
• Find Diagonal Sum of 2D Array
- Write a method that computes the sum of the main diagonal elements of a square 2D
array.
• Transpose of a Matrix
- Write a method to transpose a given 2D square matrix in-place.
Stretching / Advanced Exercises
• Jagged Arrays
- Create a jagged (ragged) 2D array where each row has a different length (e.g., row 0
has 2 elements, row 1 has 3 elements, etc.).
- Initialize and print all elements.
• Array of Object References
- Define a simple class Student with attributes name (String) and id (int).
- Create an array of 3 Student objects.
- Initialize each element with a Student instance.
- Write a method to print all students' details.
• 2D Array of Object References
- Create a 2D array of Student objects with size 2x2.
- Initialize each element with a new Student object.
- Write a method to print the 2D array of students in matrix form.
• Search for an Element in 2D Array
- Write a method that takes a 2D integer array and an integer key and returns true if the
key exists in the array, otherwise false.
• Merge Two Sorted Arrays
- Given two sorted integer arrays, write a method to merge them into one sorted array.