0 votes
1 view
in Java by (3.4k points)

In Java, arrays don't override toString(), so if you try to print one directly, you get the className + @ + the hex of the hashCode of the array, as defined by Object.toString():

int[] intArray = new int[] {2, 3, 4, 5, 6}; System.out.println(intArray); // prints something like '[[email protected]'

But usually, we'd actually want something more like [2, 3, 4, 5, 6]. What's the simplest way of doing that? Here are some example inputs and outputs:

// array of primitives: int[] intArray = new int[] {2, 3, 4, 5, 6}; //output: [2, 3, 4, 5, 6] //

array of object references: String[] strArray = new String[] {"Abhi", "Kabhi", "Sbhi"}; //output: Abhi, Kabhi, Sbhi]

1 Answer

0 votes
by (46.1k points)

In JAVA 5 or above, you can use Array.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. As you can see in the example below that object[] version calls .toString() on each object in the array. The output in the examples is decorated as you asked.

Here are some examples:

1. For Simple Array:

Input:

String[] array = new String[] {"Abhi", "Kabhi", "Sabhi"};

System.out.println(Arrays.toString(array));

Output:

[Abhi, Kabhi, Sbhi]

2. For Nested Array:

Input:

String[][] deepArray = new String[][] {{"Abhi", "Kabhi"}, {"Nbhi", "Sbhi"}};

System.out.println(Arrays.toString(deepArray));

//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]

System.out.println(Arrays.deepToString(deepArray));

Output:

[[Abhi, Kabhi], [Nbhi, Sbhi]]

3. For int Array:

Input:

int[] intArray = { 8, 7, 6, 2, 4 };

System.out.println(Arrays.toString(intArray));

Output:

[8, 7, 6, 2, 4 ]

4. For double Array:

Input:

double[] doubleArray = { 8.0, 7.0, 6.0, 2.0, 4.0 };

System.out.println(Arrays.toString(doubleArray));

Output:

[8.0,7.0, 6.0, 2.0, 4.0 ]

5. You can also use loop:

Input:

public class Array

{

   public static void main(String[] args) ]

{

       int[] array = {2, 3, 4, 5, 6};

       for (int element: array)

{

System.out.println(element);

       }

   }

}

Output:  

2

3

4

5

6

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...