-2

I am watching a tutorial on 2d arrays and I can't seem to understand where the values for states.length and states[i].length are coming from. How does it know the outer loop deals with the size 3 array and the inner is the size 2 array?

public class Test3 {
public static void main(String[] args) {

    String [][] states = new String[3][2];

    states[0][0] = "California";
    states[0][1] = "Sacremento";

    states[1][0] = "Oregon";
    states[1][1] = "Salem";

    states[2][0] = "Washington";
    states[2][1] = "Olympia";

    for (int i = 0; i < states.length; i++) {

        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < states[i].length; j++) {

            sb.append(states[i][j]);
        }
        System.out.println(sb);
    }

}
}
Baby
  • 5,062
  • 3
  • 30
  • 52
user3788779
  • 43
  • 1
  • 1
  • 3
  • arr.length is a property of the array. see [this][1] post . [1]: http://stackoverflow.com/questions/5950155/how-is-length-implemented-in-java-arrays – cyc115 Jun 30 '14 at 01:49

3 Answers3

0

The states.length is the row length of your array while the states[i].length is the number of column of the specified row.

Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

Well, a two dimensional array is an array of arrays.

So String[3][2] is

[["string", "string"],
 ["string", "string"],
 ["string", "string"]]

states.length is the length of the outer array, which is 3.

states[i].length is the length of each individual array, which are all 2.

Kyranstar
  • 1,650
  • 2
  • 14
  • 35
0

You begin by creating a 2D array that looks like the following.

[[California, Sacramento]
[Oregon, Salem]
[Washington, Olympia]]

The first for loop will iterate over each row. In this case states.length is 3 because there are 3 rows.

The next for loop will iterate over the columns in each row. In other words, states[i] will give you a row. If i is 0, then states[0] is [California, Sacramento]

There are 2 entries in that row, so states[0].length is 2.

Brian
  • 611
  • 5
  • 3