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.
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).
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.
To print a multi-dimensional array, you instead need to call the Arrays. deepToString() method and pass the multi-dimensional array as an argument.
You can use deepToString
instead of toString
:
System.out.println(Arrays.deepToString(newArray));
Try
Arrays.deepToString(newArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With