An array is a data structure used to store data of the same type. Arrays store their elements in contiguous memory locations.

In Java, arrays are objects. All methods of class object may be invoked in an array. We can store a fixed number of elements in an array.

Let’s declare a simple primitive type of array:

int[] intArray = {2,5,46,12,34};

Now let’s try to print it with the System.out.println() method:

System.out.println(intArray);
// output: [I@74a14482

Why did Java not print our array? What is happening under the hood?

The System.out.println() method converts the object we passed into a string by calling String.valueOf() . If we look at the String.valueOf() method’s implementation, we’ll see this:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

If the passed-in object is null it returns null, else it calls obj.toString() . Eventually, System.out.println() calls toString() to print the output.

If that object’s class does not override Object.toString()'s implementation, it will call the Object.toString() method.

Object.toString() returns getClass().getName()+**‘@’**+Integer.toHexString(hashCode()) . In simple terms, it returns: “class name @ object’s hash code”.

In our previous output [I@74a14482 , the [ states that this is an array, and I stands for int (the type of the array). 74a14482 is the unsigned hexadecimal representation of the hash code of the array.

Whenever we are creating our own custom classes, it is a best practice to override the Object.toString() method.

We can not print arrays in Java using a plain System.out.println() method. Instead, these are the following ways we can print an array:

  1. Loops: for loop and for-each loop
  2. Arrays.toString() method
  3. Arrays.deepToString() method
  4. Arrays.asList() method
  5. Java Iterator interface
  6. Java Stream API

Let’s see them one by one.

1. Loops: for loop and for-each loop

Here’s an example of a for loop:

int[] intArray = {2,5,46,12,34};

for(int i=0; i<intArray.length; i++){
    System.out.print(intArray[i]);
    // output: 25461234
}

All wrapper classes override Object.toString() and return a string representation of their value.

And here’s a for-each loop:

int[] intArray = {2,5,46,12,34};

for(int i: intArray){
    System.out.print(i);
    // output: 25461234
}

#java #developer

Java Array Methods – How to Print an Array in Java
2.00 GEEK