Module 06: Arrays and Collections - Exercises

Practice exercises to master arrays, collections framework, and data structures in Java

Practice Exercises

Exercise 1: Basic Array Operations

Create and manipulate arrays with various operations.

Requirements:

  • Create an array of integers with values [5, 2, 8, 1, 9, 3]
  • Find the maximum and minimum values in the array
  • Calculate the sum and average of all elements
  • Print all elements in reverse order
  • Create a method to check if a number exists in the array
Sample Code:
public class ArrayOperations {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 3};
        
        // Find max and min
        int max = findMax(numbers);
        int min = findMin(numbers);
        
        // Calculate sum and average
        int sum = calculateSum(numbers);
        double average = (double) sum / numbers.length;
        
        System.out.println("Max: " + max + ", Min: " + min);
        System.out.println("Sum: " + sum + ", Average: " + average);
    }
    
    public static int findMax(int[] arr) {
        // Implement max finding logic
    }
}

Exercise 2: Two-Dimensional Arrays

Work with 2D arrays and matrix operations.

Requirements:

  • Create a 3x3 matrix (2D array) with integer values
  • Print the matrix in a formatted way
  • Calculate the sum of each row and each column
  • Find the sum of the main diagonal (top-left to bottom-right)
  • Transpose the matrix (swap rows and columns)
Sample Code:
public class MatrixOperations {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        printMatrix(matrix);
        printRowSums(matrix);
        printColumnSums(matrix);
        System.out.println("Main diagonal sum: " + getMainDiagonalSum(matrix));
        
        int[][] transposed = transposeMatrix(matrix);
        System.out.println("Transposed matrix:");
        printMatrix(transposed);
    }
    
    public static void printMatrix(int[][] matrix) {
        // Implement matrix printing logic
    }
}

Exercise 3: ArrayList Operations

Practice using ArrayList and its methods.

Requirements:

  • Create an ArrayList of Strings with names
  • Add, remove, and modify elements
  • Sort the list alphabetically
  • Search for a specific name
  • Create a method to remove duplicates
  • Convert ArrayList to array and vice versa
Sample Code:
import java.util.ArrayList;
import java.util.Collections;

public class ArrayListPractice {
    public static void main(String[] args) {
        ArrayList names = new ArrayList<>();
        
        // Add names
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        
        // Sort alphabetically
        Collections.sort(names);
        
        // Search for a name
        if (names.contains("Bob")) {
            System.out.println("Bob is in the list");
        }
        
        // Remove duplicates
        removeDuplicates(names);
        
        // Convert to array
        String[] namesArray = names.toArray(new String[0]);
    }
    
    public static void removeDuplicates(ArrayList list) {
        // Implement duplicate removal logic
    }
}

Exercise 4: HashMap and HashSet

Practice using Map and Set collections.

Requirements:

  • Create a HashMap to store student grades (name -> grade)
  • Add, update, and remove student records
  • Find the student with the highest grade
  • Create a HashSet to store unique course names
  • Check if a course exists and add new courses
  • Create a method to find students above a certain grade
Sample Code:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CollectionPractice {
    public static void main(String[] args) {
        // HashMap for student grades
        HashMap grades = new HashMap<>();
        grades.put("Alice", 95);
        grades.put("Bob", 87);
        grades.put("Charlie", 92);
        
        // Find highest grade
        String topStudent = findTopStudent(grades);
        System.out.println("Top student: " + topStudent);
        
        // HashSet for courses
        HashSet courses = new HashSet<>();
        courses.add("Java Programming");
        courses.add("Data Structures");
        courses.add("Algorithms");
        
        // Check if course exists
        if (courses.contains("Java Programming")) {
            System.out.println("Java Programming is available");
        }
    }
    
    public static String findTopStudent(HashMap grades) {
        // Implement logic to find student with highest grade
    }
}

Exercise 5: Generics and Type Safety

Practice using generics for type-safe collections.

Requirements:

  • Create a generic class Box<T> that can hold any type
  • Create a generic method to find the maximum element in an array
  • Create a generic method to swap two elements in an array
  • Use bounded generics to create a method that works with numbers only
  • Create a generic method to reverse an array
Sample Code:
public class GenericPractice {
    // Generic class
    public static class Box {
        private T content;
        
        public Box(T content) {
            this.content = content;
        }
        
        public T getContent() {
            return content;
        }
        
        public void setContent(T content) {
            this.content = content;
        }
    }
    
    // Generic method to find max
    public static > T findMax(T[] array) {
        if (array.length == 0) return null;
        
        T max = array[0];
        for (T element : array) {
            if (element.compareTo(max) > 0) {
                max = element;
            }
        }
        return max;
    }
    
    // Generic method to swap elements
    public static  void swap(T[] array, int i, int j) {
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}