Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting elements of an array with Arrays.toString()

Tags:

java

arrays

I have used the code below to create and populate an array, however, when it comes to printing the array I do not get the result I expect while using the Arrays.toString() function.

Rather than printing

newArray: [2, 4, 6]
newArray: [8, 10, 12]
etc..

it prints

newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
newArray: [[I@15db9742, [I@6d06d69c, [I@7852e922, [I@4e25154f]
etc..

The code:

public static void main(String[] args) {
    int[][] newArray = new int[4][3];
    int number = 2;
    for (int rowCounter = 0; rowCounter < newArray.length; rowCounter++) {
        for (int colCounter = 0; colCounter < newArray[rowCounter].length; colCounter++) {
            newArray[rowCounter][colCounter] = number;
            number += 2;
        }
        System.out.println("newArray: " + Arrays.toString(newArray));
    }
}

Any help with this would be much appreciated.

like image 448
Kieran M Avatar asked Dec 10 '17 13:12

Kieran M


People also ask

What is arrays toString ()?

toString(int[]) method returns a string representation of the contents of the specified int array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).

How do I print certain elements of an array?

You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.

How do I print multiple arrays?

To print a multi-dimensional array, you instead need to call the Arrays. deepToString() method and pass the multi-dimensional array as an argument.


2 Answers

You can use deepToString instead of toString:

System.out.println(Arrays.deepToString(newArray));
like image 113
YCF_L Avatar answered Oct 27 '22 01:10

YCF_L


Try

Arrays.deepToString(newArray)
like image 29
Nisal Edu Avatar answered Oct 27 '22 00:10

Nisal Edu