Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: Hello2DArrays

Coding Exercises: 2D Arrays

Make sure to write test code (not necessarily full unit tests) to print the contents of your arrays and demonstrate/verify they have the values you think they have.

Array initialization

  1. Declare and initialize a 5x5 array of doubles with 2 on the diagonal (i.e. where i == j) and 0 everywhere else.
    2.0  0.0  0.0  0.0  0.0
    0.0  2.0  0.0  0.0  0.0
    0.0  0.0  2.0  0.0  0.0
    0.0  0.0  0.0  2.0  0.0
    0.0  0.0  0.0  0.0  2.0
  1. Declare and initialize a 2D array of Strings (any size).

  2. Declare and initialize a 6x5 array of integers with the following values. You must use a loop.

    1 1 1 1 1
    2 2 2 2 2 
    3 3 3 3 3 
    4 4 4 4 4 
    5 5 5 5 5 
    6 6 6 6 6 
  1. Declare and initialize a 5x5 array of doubles with the following values. You must use a loop.
    11.0  12.0  13.0  14.0  15.0
    21.0  22.0  23.0  24.0  25.0
    31.0  32.0  33.0  34.0  35.0
    41.0  42.0  43.0  44.0  45.0
    51.0  52.0  53.0  54.0  55.0

Computations on 2D arrays

  1. Write a function that takes a 2D array of integers as input and returns the smallest.

  2. Write a function that calculates the sum of a 2D array of floats.

  3. Write a function that takes a 2D array of Strings as input, and counts the number of strings that start with the letter “A”.

2D arrays of objects

  1. Write a class Rectangle. Include the following:
  1. Write a function that takes a 2D array of Rectangle objects as input and returns the average perimeter.

  2. Write a function that takes a 2D array of Rectangle objects as input and returns the object with the greatest area.


Next: