How To Print An Array In Java In One Line

How To Print An Array In Java In One Line | In this post, we will discuss how to print an array in Java in one line. While displaying an array we can use a print() method instead of println() method inside the loop so that it can display all array elements in the same line. Java util package also provides some built-in methods to solve this problem.

Java Arrays class contains toString() and deepToString() method. The toString() method is helpful in displaying a one-dimensional array in a single line, whereas the deepToString() method is helpful in displaying a multi-dimensional array in a single line.

The toString() method of the Arrays class converts the array into a string. While conversion it adds “[” at the beginning and “]” at the end of the string. And every element is separated by a comma and space characters. For example if the array contains following elements:- 1, 2, 3 then the Arrays.toString(array) will return “[1, 2, 3]”.

Let us develop a program to demonstrate how to print an array in Java in one line using the toString() method.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = { 10, 20, 30, 40, 50 };
        System.out.println("Array: " + Arrays.toString(arr));
    }
}

Output:-

Array: [10, 20, 30, 40, 50]

If we have a multi-dimensional array then we can take the help of the deepToString() method. The deepToString() converts a multi-dimensional array to a string.

Let us demonstrate a program to see how to print a multi-dimensional array in Java in one line using deepToString() method

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = { { 10, 20 }, { 80, 90 }, { 18, 27 } };
        System.out.println("Array: " + Arrays.deepToString(arr));
    }
}

Output:-

Array: [[10, 20], [80, 90], [18, 27]]

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][][] arr = 
            {
                { 
                    { 10, 20 },
                    { 30, 40 } 
                },
                { 
                    { 80, 90 },
                    { 99, 18 }
                }, 
                { 
                    { 27, 36 },
                    { 45, 81 } 
                } 
            };
        System.out.println("Array: " + Arrays.deepToString(arr));
    }
}

Output:-

Array: [[[10, 20], [30, 40]], [[80, 90], [99, 18]], [[27, 36], [45, 81]]]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *