6

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.

1
  • Here the result is the address of the array inside the array not the actual values you want Commented Dec 10, 2017 at 13:30

4 Answers 4

12

You can use deepToString instead of toString:

System.out.println(Arrays.deepToString(newArray));
Sign up to request clarification or add additional context in comments.

2 Comments

@LalitVerma what happen when you use System.out.println(new int[]{1,2,3}); ?
@LalitVerma When you use Arrays.toString with an array of arrays it will print the arrays inside this array(memory address), and not the values of this arrays
3

Try

Arrays.deepToString(newArray)

Comments

3

With the result you desire, make sure the array you are declaring is one-dimensional. You declared a two dimensional array which you are not using correctly.
Change int[][] newArray to int[] newArray

1 Comment

I see what you mean. However, I should have been more clear, the result I have shown is just a snippet of the actual result. In actuality, there are multiple rows. I'll edit this now.
2

when you call toString(Object[] a) internally it will call Object.toString method.

(obj == null) ? "null" : obj.toString();

If you want to print all element then as mentioned you have to deepToString instead of toString method.Internally it will for a object type array will loop through the array and convert to string.

For an example every array element in your case is int array will call toString.

if (eClass.isArray()) {
                    if (eClass == int[].class)
                        buf.append(toString((int[]) element));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.