• Register

How to Print an Array in Java

An array is a data structure that is adopted to save data of the same type. Arrays save their elements in adjacent memory locations. Arrays are objects in Java. All orders of the class object can be invoked in an array. A fixed number of elements in an array can be stored.

Here is a simple primitive type of array:

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

Now let’s strive 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 occurring under the hood?

The System.out.println() method converts the objects and then we pass into a string String.valueOf(). 

If we look at the implementation of String.valueOf() method, we shall 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 designing our custom classes, it is a most useful practice to override the Object.toString() method. We can not print arrays in Java using a plain System.out.println() method.

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

 

100 points
2