Java Arrays Loop
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:
Example
String[] cars = ; for (int i = 0; i
Loop Through an Array with For-Each
There is also a «for-each» loop, which is used exclusively to loop through elements in arrays:
Syntax
for (type variable : arrayname)
The following example outputs all elements in the cars array, using a «for-each» loop:
Example
String[] cars = ; for (String i : cars)
The example above can be read like this: for each String element (called i — as in index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.
// The following example (an array literal):
String[] cars = ;
// Can also be created with the new keyword:
String[] cars = new String[] ;
It is up to you if you want to use the new keyword. In general, we use an array literal when we know what values to insert into the array, while the new keyword is often used when we know the size of the array (the number of elements), but we don’t know the values in advance, like in the example below.
The following example will declare an array of 5 integers (without values):
Example
To initialize the elements, start adding some values to them:
Example
// Declare an array of 5 integers
int[] myNumbers = new int[5];
// Assign values to array elements
myNumbers[0] = 10; // First element
myNumbers[1] = 20; // Second element
myNumbers[2] = 30; // Third element
//..etc
// Output values
System.out.println(«First element: » + myNumbers[0]);
System.out.println(«Second element: » + myNumbers[1]);
System.out.println(«Third element: » + myNumbers[2]);
//..etc
Java Array Methods – How to Print an Array in Java
Thanoshan MV
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:
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)
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:
- Loops: for loop and for-each loop
- Arrays.toString() method
- Arrays.deepToString() method
- Arrays.asList() method
- Java Iterator interface
- Java Stream API
1. Loops: for loop and for-each loop
Here’s an example of a for loop:
int[] intArray = ; for(int i=0; i
All wrapper classes override Object.toString() and return a string representation of their value.
int[] intArray = ; for(int i: intArray)< System.out.print(i); // output: 25461234 >
2. Arrays.toString() method
Arrays.toString() is a static method of the array class which belongs to the java.util package. It returns a string representation of the contents of the specified array. We can print one-dimensional arrays using this method.
Array elements are converted to strings using the String.valueOf() method, like this:
int[] intArray = ; System.out.println(Arrays.toString(intArray)); // output: [2, 5, 46, 12, 34]
For a reference type of array, we have to make sure that the reference type class overrides the Object.toString() method.
public class Test < public static void main(String[] args) < Student[] students = ; System.out.println(Arrays.toString(students)); // output: [Student, Student] > > 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'; > >
This method is not appropriate for multidimensional arrays. It converts multidimensional arrays to strings using Object.toString() which describes their identities rather than their contents.
// creating multidimensional array int[][] multiDimensionalArr = < , >; System.out.println(Arrays.toString(multiDimensionalArr)); // output: [[I@74a14482, [I@1540e19d]
With the help of Arrays.deepToString() , we can print multidimensional arrays.
3. Arrays.deepToString() method
Arrays.deepToString() returns a string representation of the “deep contents” of the specified array.
If an element is an array of primitive type, it is converted to a string by invoking the appropriate overloading of Arrays.toString() .
Here is an example of the primitive type of multidimensional array:
// creating multidimensional array int[][] multiDimensionalArr = < , >; System.out.println(Arrays.deepToString(multiDimensionalArr)); // output: [[2, 3], [5, 9]]
If an element is an array of reference type, it is converted to a string by invoking Arrays.deepToString() recursively.
Teacher[][] teachers = , >; System.out.println(Arrays.deepToString(teachers)); // output: [[Teacher, Teacher],[Teacher]]
We have to override Object.toString() in our Teacher class.
If you are curious as to how it does recursion, here is the source code for the Arrays.deepToString() method.
NOTE: Reference type one-dimensional arrays can also be printed using this method. For example:
Integer[] oneDimensionalArr = ; 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 = ; 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 a list of objects. When we are converting an array to a list it should be an array of reference type.
Java calls Arrays.asList(intArray).toString() . This technique internally uses 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, Teacher]
NOTE: We can not print multi-dimensional arrays using this method. For example:
Teacher[][] teachers = , < new Teacher("Mary") >>; System.out.println(Arrays.asList(teachers)); // output: [[Lcom.thano.article.printarray.Teacher;@1540e19d, [Lcom.thano.article.printarray.Teacher;@677327b6]
5. Java Iterator Interface
Similar to a for-each loop, we can use the Iterator interface to loop through array elements and print them.
Iterator object can be created by invoking the iterator() method on a Collection. That object will be used to iterate over that Collection’s elements.
Here is an example of how we can print an array using the Iterator interface:
Integer[] intArray = ; // creating a List of Integer List list = Arrays.asList(intArray); // creating an iterator of Integer List Iterator 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 the forEach() terminal operation we can iterate through every element of the stream.
Integer[] intArray = ; Arrays.stream(intArray).forEach(System.out::print); // output: 25461234
Now we know how to print an array in Java.
You can read my other articles on Medium.
Happy Coding!