简体   繁体   中英

Java Multidimensional String giving a strange output

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

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. (eg: [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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM