Java array | What Is The Simplest Way To Print A Java Array?

Here we will find The Simplest Way To Print A Java Array. As we can use a loop which could be for or while loop to print all the elements of an array in java which will have the complexity of linear O(n) where n is the size of the array.

Java array

Array In Java

The array is a mutable non-primitive data type that can store homogenous data at continuous memory locations. Let’s understand how data is stored as elements in an array.

We store the data of one data type in a single array where each element is assigned one index number from zero to n-1 (n is the length of the array) and using those indexes we access the element. And we can directly access the element of our choice as per the given array index.

Ways Printing A Array

There are three ways to print an array we can choose any of them Let’s discuss all the possible ways to print an array and you decided which is simplest.

Using Arrays.toString()

We can use this only to print one-dimensional arrays By just considering the array as a string To understand better follow the example.

import java.util.Arrays;
  
class ABC {
    public static void main(String[] args)
    {
        String array1[] = { "Prakhar", "Yadav", "Writing" };
        System.out.println(Arrays.toString(array1));
    }
}

Using Arrays.deepToString()

Although we can use it for printing two-dimensional arrays by the same method of converting the array to a string with some modifications. For understanding, it follow the example given below.

import java.util.Arrays;
  
class ABC {
    public static void main(String[] args)
    {
        String Array1[][]
            = { { "Prakhar", "Article Writing" },
                { "Google", "Search Engine" },
                { "Facebook", "Social Media" } };
        System.out.println(Arrays.deepToString(array1));
    }
}

Here array1 is two-dimensional.

Using For Loop

As discussed we already we can also print an array with for loop by this we can print single or multi-dimensional arrays by simply iterating each element one by one.

Let us understand with an example.

class ABC {
    public static void main(String[] args)
    {
        String array1[] = new String[3];
        gfg[0] = "Prakhar";
        gfg[1] = "Yadav";
        gfg[2] = "writing";
        for (int i = 0; i <= 2; i++) {
            System.out.print(array1[i] + " ");
        }
    }
}

Learn More about Java array | What Is The Simplest Way To Print A Java Array? at: Print an array

Also Visit Java Tutorials To solve More Problems related to java and visit Python’s list: What is the difference Between methods Append and Extend? For solving other problems related to Python and other programing doubts.

Leave a Comment

%d bloggers like this: