arrays

2D Array Java Example

Photo of Mary ZhengMary ZhengMarch 5th, 2014Last Updated: July 6th, 2022
0 432 6 minutes read

In this post, we feature a comprehensive 2D Array Java Example. Java support one dimensional, two dimensional and generally multidimensional arrays.

1. Introduction

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.

Java gives us the opportunity of using arrays with many dimensions. The syntax to declare a multidimensional array is as:

{Datatype}[1D][2D][..][ND]

You can watch the following video and learn how to use arrays in Java:

Java Array Example How to use Arrays in Java – Video

The most common multidimensional arrays that are used in java apps are one (1D), two (2D) and three (3D) dimensional.2D array represents a tabular data in row and column style. The first bracket is for the rows and the second bracket is for the column. E.g.int[3][2] declares a 2D integer array with 3 rows and 2 columns.

2d array java
[rowIdx][colIdx]column 0column 1
row 0item[0][0]item[0][1]
row 1item[1][0]item[1][1]
row 2item[2][0]item[2][1]

In this example we are going to demonstrate:

  • Declare a 2-D array
  • Declare and create a 2-D array
  • Declare, create, and initialize a 2-D array
  • Declare, create, and assign the value to a 2-D array’s element
  • Print a 2-D array
  • ShowArrayIndexOutBoundException

2. Technologies Used

The example code in this article was built and run using:

  • Java 11
  • Maven 3.3.9
  • Junit 4.12
  • Eclipse Oxygen

3. Maven Project

In this step, I will create a Maven project which includes 2D array examples.

3.1 Dependencies

I will include Junit in the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>jcg.zheng.demo</groupId><artifactId>java-2dArray-demo</artifactId><version>0.0.1-SNAPSHOT</version><build><sourceDirectory>src</sourceDirectory><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version><configuration><release>11</release></configuration></plugin></plugins></build><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies></project>

3.2 Card

In this example, I will create aCard class to be used to create a 2D array withCard type.

Card.java

package jcg.zheng.demo.data;public class Card {public Card(String suit, String rank) {super();this.suit = suit;this.rank = rank;}private String suit;private String rank;public String getSuit() {return suit;}public void setSuit(String suit) {this.suit = suit;}public String getRank() {return rank;}public void setRank(String rank) {this.rank = rank;}@Overridepublic String toString() {return "[" + rank + " of " + suit + "]";}}

4. JUnit Test

4.1. 2D Integer Array

In this step, I will create a java class namedTwoDIntArrayTest with the following methods:

  • declare_array – defines a 2-D array with an integer type.
  • declare_and_create_array – defines a 2-D integer array with 4 rows. The columns arenullobjects.
  • declare_and_create_array_with_column – defines a 2-D integer array with 4 rows and 2 columns. The columns are 1-D array with default value as 0.
  • declare_create_and_initialize_array – defines a 2-D integer array with initial values.
  • declare_create_assign_array– defines a 2-D integer array and allocates with a row size and assigns the columns for each row.
  • print2DIntArray – prints out a 2-D integer array’s elements.
  • array_has_boundary – shows the array has a fixed size, it will throw an exception when accessing an array out of its boundary.

TwoDIntArrayTest.java

package jcg.zheng.demo.array;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertNotNull;import static org.junit.Assert.assertNull;import org.junit.Test;public class TwoDIntArrayTest {private static final int COLUMN_COUNT = 4;private static final int ROW_COUNT = 2;@Testpublic void declare_array() {int[][] anArray;System.out.println("done");}@Testpublic void declare_and_create_array() {int[][] anArray = new int[ROW_COUNT][];for (int i = 0; i < ROW_COUNT; i++) {assertNull(anArray[i]);}}@Testpublic void declare_and_create_array_with_column() {int[][] anArray = new int[ROW_COUNT][COLUMN_COUNT];for (int i = 0; i < ROW_COUNT; i++) {assertNotNull(anArray[i]);for (int j = 0; j < COLUMN_COUNT; j++) {assertEquals(0, anArray[i][j]);}}}@Testpublic void declare_create_and_initialize_array() {int[][] tableInt = new int[][] { { 1, 2, 3 }, { 6, 7, 8 }, { 5, 6, 7 } };print2DIntArray(tableInt);}@Testpublic void declare_create_assign_array() {int[][] tableInt = new int[ROW_COUNT][];for (int i = 0; i < ROW_COUNT; i++) {int[] row = new int[COLUMN_COUNT];tableInt[i] = row;for (int j = 0; j < COLUMN_COUNT; j++) {assertEquals(0, tableInt[i][j]);}}}private void print2DIntArray(int[][] tableInt) {for (int i = 0; i < tableInt.length; i++) {for (int j = 0; j < tableInt[i].length; j++) {System.out.printf("tableInt[%d][%d] = %d\n", i, j, tableInt[i][j]);}System.out.println();}}@Test(expected = ArrayIndexOutOfBoundsException.class)public void array_has_boundary() {int[] test = new int[ROW_COUNT];test[test.length] = 4;}}

As you can see, this manner is very similar to the declaration of one-dimensional array. Executemvn test -Dtest=TwoDIntArrayTest and capture the output here.

Output

------------------------------------------------------- T E S T S-------------------------------------------------------Running jcg.zheng.demo.array.TwoDIntArrayTestdonetableInt[0][0] = 1tableInt[0][1] = 2tableInt[0][2] = 3tableInt[1][0] = 6tableInt[1][1] = 7tableInt[1][2] = 8tableInt[2][0] = 5tableInt[2][1] = 6tableInt[2][2] = 7Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.172 secResults :Tests run: 6, Failures: 0, Errors: 0, Skipped: 0[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time:  10.678 s[INFO] Finished at: 2019-11-01T11:30:11-05:00[INFO] ------------------------------------------------------------------------C:\MaryZheng\Workspaces\jdk12\java-2dArray-demo>

4.2 2D Object Array

Instead of declaring only primitive types in an array, we can use objects too. In this example, I will createTwoDObjectarrayTest class to cover the definition ofCard 2D array. Every cell of this 2-dimensional array represents an instance ofCard class.

  • declare_and_create_2D_array_default_null – defines a 2DCard array with 4 rows and 2 columns and verifies the default elements arenull objects.
  • declare_create_initialize_string_2d_array – defines, creates, and initializes a 2DString array.
  • print2DArray – prints a 2D array elements with twofor loops
  • deal_poker_card_game – illustrates a 2DCard array with a poker game. It draws 5 cards for 4 players and prints out players’ hand.

TwoDObjectArrayTest.java

package jcg.zheng.demo.array;import static org.junit.Assert.assertEquals;import org.junit.Test;import jcg.zheng.demo.data.Card;public class TwoDObjectArrayTest {private static final int COLUMN_COUNT = 4;private static final int ROW_COUNT = 2;@Testpublic void declare_and_create_2D_array_default_null() {Card[][] array_2d = new Card[ROW_COUNT][COLUMN_COUNT];for (int i = 0; i < ROW_COUNT; i++) {for (int j = 0; j < COLUMN_COUNT; j++) {assertEquals(null, array_2d[i][j]);}}}@Testpublic void declare_create_initialize_String_2d_array() {String[][] array_2d = new String[][] { { "apple", "orange" }, { "kiwi", "strawberry" },{ "cranberry", "grape" } };print2DArray(array_2d);}private void print2DArray(Object[][] array_2d) {for (int i = 0; i < array_2d.length; i++) {for (int j = 0; j < array_2d[i].length; j++) {System.out.printf("[%d][%d]=%s ", i, j, array_2d[i][j]);}System.out.println();}}@Testpublic void deal_poker_card_game() {// 4 players play one game of pokerint PLAYER_COUNT = 4;int HAND_CARD_COUNT = 5;Card[][] cards = new Card[HAND_CARD_COUNT][PLAYER_COUNT];// draw first card for 4 playerscards[0][0] = new Card("Spade", "1");cards[0][1] = new Card("Heart", "J");cards[0][2] = new Card("Diamond", "3");cards[0][3] = new Card("Club", "K");// draw second card for 4 playerscards[1][0] = new Card("Heart", "1");cards[1][1] = new Card("Spade", "10");cards[1][2] = new Card("Club", "5");cards[1][3] = new Card("Diamond", "8");// draw third card for playerscards[2][0] = new Card("Spade", "11");cards[2][1] = new Card("Heart", "A");cards[2][2] = new Card("Diamond", "8");cards[2][3] = new Card("Club", "K");// draw fourth card for playerscards[3][0] = new Card("Heart", "9");cards[3][1] = new Card("Spade", "2");cards[3][2] = new Card("Club", "Q");cards[3][3] = new Card("Diamond", "7");// draw fifth card for playerscards[4][0] = new Card("Heart", "5");cards[4][1] = new Card("Spade", "K");cards[4][2] = new Card("Club", "10");cards[4][3] = new Card("Diamond", "4");print2DArray(cards);// print out each player's handfor (int playerIdx = 0; playerIdx < PLAYER_COUNT; playerIdx++) {System.out.printf("\nPlayer " + (playerIdx + 1) + " hand :");for (int cardIndex = 0; cardIndex < HAND_CARD_COUNT; cardIndex++) {System.out.print(cards[cardIndex][playerIdx] + " ");}}}}

For a better understanding, you can see the output of the execution of the above code.

Output

------------------------------------------------------- T E S T S-------------------------------------------------------Running jcg.zheng.demo.array.TwoDObjectArrayTest[0][0]=[1 of Spade] [0][1]=[J of Heart] [0][2]=[3 of Diamond] [0][3]=[K of Club][1][0]=[1 of Heart] [1][1]=[10 of Spade] [1][2]=[5 of Club] [1][3]=[8 of Diamond][2][0]=[11 of Spade] [2][1]=[A of Heart] [2][2]=[8 of Diamond] [2][3]=[K of Club][3][0]=[9 of Heart] [3][1]=[2 of Spade] [3][2]=[Q of Club] [3][3]=[7 of Diamond][4][0]=[5 of Heart] [4][1]=[K of Spade] [4][2]=[10 of Club] [4][3]=[4 of Diamond]Player 1 hand :[1 of Spade] [1 of Heart] [11 of Spade] [9 of Heart] [5 of Heart]Player 2 hand :[J of Heart] [10 of Spade] [A of Heart] [2 of Spade] [K of Spade]Player 3 hand :[3 of Diamond] [5 of Club] [8 of Diamond] [Q of Club] [10 of Club]Player 4 hand :[K of Club] [8 of Diamond] [K of Club] [7 of Diamond] [4 of Diamond] [0][0]=apple [0][1]=orange[1][0]=kiwi [1][1]=strawberry[2][0]=cranberry [2][1]=grapeTests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.401 secResults :Tests run: 3, Failures: 0, Errors: 0, Skipped: 0[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time:  10.294 s[INFO] Finished at: 2019-11-01T11:33:18-05:00[INFO] ------------------------------------------------------------------------C:\MaryZheng\Workspaces\jdk12\java-2dArray-demo>

5. Summary

In this example, I showed how to declare, create, and initialize a 2D array with both integer andCard. Please remember thatArray has fixed-size elements and will throw anArrayIndexOutBoundException if accessing an index which is outside of the boundary.

Please clickhere for how to add and remove an element and clickhere for how to copy an array.

6. Download the Source File

This example consists of a Maven project which includes a tutorial about 2D array for declaration, creation, initialization, assigning, accessing, and retrieving.

Download
Download the source code of this example:2D Array Java Example

Last updated on Nov. 5th, 2019

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Mary ZhengMary ZhengMarch 5th, 2014Last Updated: July 6th, 2022
0 432 6 minutes read
Photo of Mary Zheng

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.

    Related Articles

    Bipartite Graph

    Java String Array Example

    January 15th, 2014
    Subscribe
    Notify of
    guest
    I agree to theTerms andPrivacy Policy
    The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

    I agree to theTerms andPrivacy Policy
    The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.