How to Print an Array in Java

Thanoshan MV
4 min readJul 19, 2020

--

Array is a data structure to store data of same type. Array stores its elements in contiguous memory location. We can store fixed amount of elements in an array.

Photo by Tim Swaan on Unsplash

In Java, arrays are objects. All methods of class Object may be invoked in an array.

Let’s declare a simple primitive type array:

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

Let’s try to print it with System.out.println() method:

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

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

System.out.println() method converts the object we passed into string by calling String.valueOf() . If we look into String.valueOf() method’s implementation:

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() implementation, it will call Object.toString() method.

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

Our previous output [I@74a14482 , [ states that this is an array and I for int (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 Object.toString() method.

We can not print arrays in Java using plain System.out.println() method. These are the following ways we can print an array in Java.

  1. Loops: for loop and for-each loop are the most used.
  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

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 returns a string representation of their value.

for-each loop:

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

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

2. Arrays.toString() method

Arrays.toString() is a static method of Arrays class which belongs to java.util package. It returns a string representation of the contents of the specified array.

Array elements are converted to strings using String.valueOf() method. It returns null if that element is null .

int[] intArray = {2,5,46,12,34};
System.out.println(Arrays.toString(intArray));
// output: [2, 5, 46, 12, 34]

For reference type array, we have to make sure that reference type class overrides Object.toString() method.

For example:

public class Test {
public static void main(String[] args) {
Student[] students = {new Student("John"), new Student("Doe")};

System.out.println(Arrays.toString(students));
// output: [Student{name='John'}, Student{name='Doe'}]
}
}

class Student {
private String name;

public Student(String name){
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + '}';
}

}

This method is not appropriate for multidimensional arrays. This method converts multidimensional arrays to string using Object.toString() which describes their identities rather than their contents.

For example:

// creating multi dimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.toString(multiDimensionalArr));
// output: [[I@74a14482, [I@1540e19d]

With the help of Arrays.deepToString(), we can convert multidimensional arrays to string representation.

3. Arrays.deepToString() method

Arrays.deepToString() converts multidimensional arrays to string. It returns a string representation of the “deep contents” of the specified array.

If an element is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString() .

Here is an example of primitive type multidimensional array:

// creating multi dimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.deepToString(multiDimensionalArr));
// output: [[2, 3], [5, 9]]

If an element is an array of a reference type, it is converted to a string as by invoking Arrays.deepToString() recursively.

Teacher[][] teachers = {{ new Teacher("John"), new Teacher("Doe") }, {new Teacher("Mary")} };System.out.println(Arrays.deepToString(teachers));
// output:
[[Teacher{name='John'}, Teacher{name='Doe'}],[Teacher{name='Mary'}]]

We have to override Object.toString() in our Teacher class.

If you are curious on how it does recursion, here is the source code of Arrays.deepToString() method.

NOTE: Reference type one-dimensional array can also be converted to string by this method. For example:

Integer[] oneDimensionalArr = {1,4,7};

System.out.println(Arrays.deepToString(oneDimensionalArr));
// output: [1, 4, 7]

4. Arrays.asList() method

This method returns a fixed-size list backed by the specified array.

Integer[] intArray = {2,5,46,12,34};
System.out.println(Arrays.asList(intArray));
// output: [2, 5, 46, 12, 34]

We have changed the type to Integer from int. Because List is a collection that holds list of objects. When we are converting an array to list, that array should be of reference type.

Java calls Arrays.asList(intArray).toString() .

This technique internally utilizes the toString() method of the type of the elements within the List.

Another example with our custom Teacher class:

Teacher[] teacher = { new Teacher("John"), new Teacher("Mary") };System.out.println(Arrays.asList(teacher));
// output: [Teacher{name='John'}, Teacher{name='Mary'}]

5. Java Iterator Interface

Similar to for-each loop, we can use Iterator interface to loop through array elements and print them.

Iterator object can be created by invoking iterator() method on a Collection. That object will be used to iterate over that Collection’s elements.

Integer[] intArray = {2,5,46,12,34};// creating a List of Integer
List<Integer> list = Arrays.asList(intArray);
// creating an iterator of Integer List
Iterator<Integer> it = list.iterator();
// if List has elements to be iterated
while(it.hasNext()) {
System.out.print(it.next());
// output: 25461234
}

6. Java Stream API

The Stream API is used to process collections of objects. A stream is a sequence of objects. Streams don’t change the original data structure, they only provide the result as per the requested operations.

With the help of forEach() terminal operation, we can iterate through every element of the stream.

Integer[] intArray = {2,5,46,12,34};
Arrays.stream(intArray).forEach(System.out::print);
// output: 25461234

Now we know how to print an array in Java.

Thank you for reading.

Happy Coding!

--

--

Thanoshan MV
Thanoshan MV

Written by Thanoshan MV

Hi! I'm a Software Engineer with a passion for research in AI, software engineering, and open-source development. Web - https://thanoshanmv.github.io/

No responses yet