Q: How to make twodimensional array in Java?

+13 votes

Can you please give me an example of the usage of twodimensional (2-dimensional) array in Java? Not like the original one - for example String[ ]; but String [ ] [ ]. Thanks

asked in Java category by user paulcabalit

1 Answer

+1 vote
Best answer

Hi, this is my array with 2 dimensions in Java. I even drew you a picture so you can imagine the 2 dimensional array better :-) The drawing is from the code obviously.

I also used StringBuilder to append the capitals to the countries and print them in the console.

Here's my code:

public class TwoDimensionalArray {
    public static void main(String[] args) {
        String[][] countriesCapitals = new String[3][2];
        countriesCapitals[0][0] = "USA";
        countriesCapitals[0][1] = "Washington";
        countriesCapitals[1][0] = "Russia";
        countriesCapitals[1][1] = "Moscow";
        countriesCapitals[2][0] = "China";
        countriesCapitals[2][1] = "Beijing";

        for (int i = 0; i < countriesCapitals.length; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append("The capital of ")
                    .append(" is ")


2 dimensional array in java

... and the Output:

The capital of USA is Washington.
The capital of Russia is Moscow.
The capital of China is Beijing.

answered by user Jolie Ann
selected by user golearnweb