Traversing Arrays

Learn how to access each element stored in an array.

We'll cover the following...

Remember what we learned about iteration back in Unit 4. We’ll use the same concepts to traverse through an array.

Why do we need a loop?

Look at the code below.

Press + to interact
class CharArray
{
public static void main(String args[])
{
char[] string = {'J', 'a', 'v', 'a'}; // Making a char type array
System.out.println(string); // Printing the array
}
}

We have already covered the String type in detail. Now let’s look at a character array. Look at line 5. We make a char type array, named string, and store four values in it. In the next line, we directly print the string array. It gives the output: Java.

🧐 Note: A char type array stores a string in it, just like a String type variable.

However, if we have any other type of array, we can’t print it by simply passing its name in the System.out.print() function. Here’s the problem:

Press + to interact
class PrintingArray
{
public static void main(String args[])
{
int[] num = {1, 2, 3};
System.out.println(num); // Prints the address
}
}

Line 6 prints a strange value, something like [I@28d93b30. [ means it’s an array, I means the values in the array are ...