2

So I'm just playing around with a 2-D String array here and wanted to see how my output varies if I just print out only the row dimension of my actual array. Following is my code with the strange output.

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

        String[][] words = { { "Hello", "Mr.", "Spencer!" }, { "How", "Are", "You", "Doing", "Today?" },
                { "I", "recommend", "an", "outdoor", "activity", "for", "this", "evening." }

        };
for (int m = 0; m < words.length; m++) {
            for (int n = 0; n < words[m].length; n++) {
                System.out.println(words[m]);
            }
        }

    }

Output:

[Ljava.lang.String;@7852e922
[Ljava.lang.String;@7852e922
[Ljava.lang.String;@7852e922
[Ljava.lang.String;@4e25154f
[Ljava.lang.String;@4e25154f
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Greedy Coder
  • 89
  • 2
  • 9
  • Java is printing out string array references. – yters Mar 16 '17 at 23:32
  • 1
    Possible duplicate of [How do I print my Java object without getting "SomeType@2f92e0f4"?](http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – Joe Mar 17 '17 at 12:32

2 Answers2

4

What you are seeing here, as pointed out by @yters, are references to the array.

Keep in mind that inside each array, you have another array now (because it is a two-dimensional array). So the result in your case of words[0] would be ["Hello","Mr.","Spencer!"].

When you perform a print statement in Java, you are relying on the objects toString() method to give you the correct information. In this case, the object you are doing this for is of type String[], thus an Array. When running toString() on an Array, you will get the object reference printed out, which is the result you are getting. (e.g: [Ljava.lang.String;@135fbaa4 ).

What you could do to print the array is write code like this:

    for (int m = 0; m < words.length; m++) {
        System.out.println(Arrays.toString(words[m]));
    }

By using the Arrays util class, you can print each array inside your two dimensional array like that.

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
  • He already had the two loops done so using `words[m][n]` was ok too ;) – AxelH Mar 17 '17 at 12:28
  • 1
    @AxelH yeah but the OP said this: `if I just print out only the row dimension`. So in my interpretation, he wanted to have the complete array for each index of m, without iterating over the index n as well. He also did not use N so I assumed as well that he did not really understand what he was doing. But of course, your point is valid, just a difference of interpretation of the question I suppose :-) – Dylan Meeus Mar 17 '17 at 12:31
0

Or you can change the line System.out.println(words[m]); to System.out.println(words[m][n]);

Mustafa Çil
  • 766
  • 8
  • 15