Explain Codes LogoExplain Codes Logo

Syntax for creating a two-dimensional array in Java

java
2d-arrays
array-initialization
java-best-practices
Nikita BarsukovbyNikita Barsukov·Jan 20, 2025
TLDR

To create a 2D array in Java, utilize the new keyword, specifying both dimensions. For a grid of 4 rows and 5 columns of int, write:

int[][] array = new int[4][5]; // Creates a '4x5' array. Nice and square. Just how arrays like it.

Elements can be accessed via row and column indexes, like array[0][2] for the third item in the first row. Note that arrays begin at 0.

How to get in shape: Uniform vs. Skewed Arrays

Java generously offers a choice between uniform or skewed 2D arrays. The former has equal columns per row while the latter can have varying column lengths.

Uniform array in full display:

int[][] uniformArray = new int[5][10]; // More like a uniform rectangle, really.

Skewed array showing its edges:

int[][] skewedArray = new int[5][]; for(int i = 0; i < skewedArray.length; i++) { skewedArray[i] = new int[i + 1]; // The lenient parent of arrays. Different for each child. }

Initialization Games: Loop vs Static

The Loop-de-loop way

int[][] matrix = new int[4][5]; // Let's play a game! for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { matrix[i][j] = i * j; // It's not Sudoku, but it's still fun! } }

This is how pros populate arrays that require calculated values.

The Static, old-fashioned way

int[][] staticArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // So static it gets goosebumps from rubbing on a balloon!

For when you want to initalize with set data like a boss.

Beware the Bear-Traps: Caveats & Best Practices

  1. Null and Void: Watch out for null when dealing with array of objects.
  2. The Looping Loop: Whenever possible, equip loops to avoid hardcoded indices. They are your trusty sidekick.
  3. Keep it Clean: Use modular methods for fluid and clean code, keeping array creation and initialization separate.

Expert Moves: Advanced Initialization

Differently sized columns

int[][] diffColSizes = { new int[3], new int[2], new int[4], }; // This array is proud of its different shapes. diffColSizes[0] = new int[] {1, 2, 3}; // Shapeshifting its content!

This gives you the flexbility to have varying column lengths because Java is nice like that.

Memory allocation

Creating a 2D array is like building a mini-universe. It requires space. Memory allocation depends on the dimensions. It's n * m * 4 bytes of memory (for int type). Pick array sizes wisely, to avoid memory explosion!

Keeping it Short and Readable

Shorthand notation is your friend. It helps clarify the essence of the array, making it readable and almost comprehensible at first glance!

int[][] readableArray = { { 10, 20, 30 }, { 40, 50, 60 }, { 70, 80, 90 } }; // Array turns poet.

Best Practices for Peaceful Coding

  • Loops are the go-to for dynamic data generation.
  • For static data, shorthand makes your code readable and neat.
  • Avoid hardcoding at all costs for the sake of code maintenance.

Problem-Solvers' Checklist

  • Keep an eye for out-of-bounds exceptions. Any access must range from 0 to length - 1.
  • Prevent null pointer exceptions, make sure you've initialized all dimensions of the array.