How to write an array of strings to the output console in Java

You cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. If you want to print a one-dimensional array, please use the toString() method, if you want to print a two-dimensional or 3-dimensional array, etc., please use the deepToString() method. In Java, arrays do not overwrite toString(). When we try to write the array directly to the output console in Java, we will get the class_name + ‘@’ + hash_code of the array defined by Object.toString(). Please refer to the example below for a better understanding.

 

import java.io.*;

class GFG {
	public static void main(String[] args)
	{
		String gfg[] = { "Geeks", "for", "Geeks" };
		System.out.println(gfg);
	}
}

Output

[Ljava.lang.String;@3d075dc0

Therefore, to print Java arrays in a meaningful way, you don't need to look further, because your own Collection framework provides many array utility methods in the java.util.Arrays class. Here we have toString() method and deepToString() method to print array in Java. The following is how to write a string array to the output console.

Method 1: Using Arrays.toString()

This method is used when you have one dimensional array.

 

 
import java.io.*;
import java.util.Arrays;

class GFG {
	public static void main(String[] args)
	{
		String gfg[] = { "Geeks", "for", "Geeks" };
		System.out.println(Arrays.toString(gfg));
	}
}

Output

[Geeks, for, Geeks]

We use the Arrays.toString() method above. Just pass the array name as an argument to Arrays.toString() and all array elements will be written to console output.

Method 2: Using Arrays.deepToString()

This method is used when you have to two dimensional array.

import java.io.*;
import java.util.Arrays;

class GFG {
	public static void main(String[] args)
	{
		String gfg[][]
			= { { "GeeksforGeeks", "Article Writing" },
				{ "Google", "Search Engine" },
				{ "Facebook", "Social Media" } };
		System.out.println(Arrays.deepToString(gfg));
	}
}

Output

[[GeeksforGeeks, Article Writing], [Google, Search Engine], [Facebook, Social Media]]

In the above example we use the Arrays.deepToString() method. This method handles writing elements from a two-dimensional array to the output console.

Method 3: Using for loop

In this method we have access to each array element and store it in the output console.

import java.io.*;

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

Output

Geeks for Geeks 

In the above method, we use the for loop() method to access each element of the gfg array and write it to the output console.

Submit Your Programming Assignment Details