2386

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[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'

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

// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
// Output: [1, 2, 3, 4, 5]

// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
// Output: [John, Mary, Bob]
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Alex Spurling
  • 54,094
  • 23
  • 70
  • 76
  • 9
    What do you want the representation to be for objects other than strings? The result of calling toString? In quotes or not? – Jon Skeet Jan 03 '09 at 20:41
  • 3
    Yes objects would be represented by their toString() method and without quotes (just edited the example output). – Alex Spurling Jan 03 '09 at 20:42
  • 2
    In practice, closely related to http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4 – Raedwald Jan 24 '16 at 18:02
  • 2
    That weird output is not necessarily the memory location. It's the `hashCode()` in hexadecimal. See [`Object#toString()`](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--). – 4castle Nov 10 '16 at 21:22
  • 1
    To print single dimensional or multi-dimensional array in java8 check http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array/30931066#30931066 – akhil_mittal Nov 16 '16 at 01:28
  • Related: [*Convert array of strings into a string in Java*](https://stackoverflow.com/q/5283444/3357935) & [*How do I print my Java object without getting “SomeType@2f92e0f4”?*](https://stackoverflow.com/q/29140402/3357935) – Stevoisiak Sep 01 '17 at 13:21
  • Related: https://stackoverflow.com/questions/62191507/objects-deeptostringobject-o-method – John McClane Jun 14 '20 at 19:08

37 Answers37

3169

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

  • Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));
    

    Output:

    [John, Mary, Bob]
    
  • Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    // Gives undesired output:
    System.out.println(Arrays.toString(deepArray));
    // Gives the desired output:
    System.out.println(Arrays.deepToString(deepArray));
    

    Output:

    [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    [[John, Mary], [Alice, Bob]]
    
  • double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));
    

    Output:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    
  • int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));
    

    Output:

    [7, 9, 5, 1, 3 ]
    
Marc Bannout
  • 388
  • 4
  • 15
Esko
  • 29,022
  • 11
  • 55
  • 82
  • 4
    What if we have an array of strings, and want simple output; like: `String[] array = {"John", "Mahta", "Sara"}`, and we want this output without bracket and commas: `John Mahta Sara`? – Hengameh Aug 29 '15 at 02:34
  • 3
    @Hengameh: There are several other ways to do this, but my favorite is this one: http://www.javahotchocolate.com/notes/java.html#arrays-tostring . – Russ Bateman Aug 29 '15 at 06:16
  • 5
    FYI, `Arrays.deepToString()` accepts only an `Object []` (or an array of classes that extend `Object`, such as `Integer`, so it won't work on a primitive array of type `int []`. But `Arrays.toString()` works fine for primitive arrays. – Marcus Dec 11 '15 at 23:25
  • 7
    @Hengameh There's a method dedicated to that. `System.out.println(String.join(" ", new String[]{"John", "Mahta", "Sara"}))` will print `John Mahta Sara`. – The SE I loved is dead Mar 13 '17 at 14:15
  • 2
    @dorukayhan Actually you can omit explicitly instantiating the array here: `String.join(" ", "John", "Mahta", "Sara")`for the `.join(...)` method takes the array as a _vararg_ parameter. – Amadán Aug 18 '18 at 08:12
  • 11
    Don't forget "import java.util.Arrays;" – M.Hossein Rahimi Oct 21 '19 at 21:48
  • If you don't import, you can write `java.util.Arrays.toString(array)` – Omkar76 Aug 29 '20 at 06:47
  • Also, don't forget to override `Object#toString()` if the array contains an object type other than `String` or a primitive wrapper class. – hfontanez Dec 29 '20 at 14:24
428

Always check the standard libraries first.

import java.util.Arrays;

Then try:

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

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
Limbic System
  • 6,820
  • 7
  • 29
  • 37
  • 25
    @Hengameh Nowadays with Java 8: `String.join(" ", Arrays.asList(array))`. [doc](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) – Justin Mar 04 '16 at 23:14
115

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
Russ Bateman
  • 18,333
  • 14
  • 49
  • 65
112

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Eric Baker
  • 1,137
  • 1
  • 7
  • 2
55

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.deepToString methods, is simply the best.

Java 8 - Stream.collect(joining()), Stream.forEach

Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the Stream.collect operator, using a joining Collector, to mimic what the String.join is doing.

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);
eis
  • 51,991
  • 13
  • 150
  • 199
YoYo
  • 9,157
  • 8
  • 57
  • 74
  • if you use IntStream.of(ints).forEach(System.out::print); i don't think it will print in new line.. – Prashant Apr 28 '22 at 07:08
51

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

The output will be "Hey there amigo!".

laylaylom
  • 1,754
  • 16
  • 15
46

Prior to Java 8

We could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays.

Java 8

Now we have got the option of Stream and lambda to print the array.

Printing One dimensional Array:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

The output is:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
43

If you're using Java 1.4, you can instead do:

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

(This works in 1.5+ too, of course.)

Ross
  • 9,652
  • 8
  • 35
  • 35
30

Arrays.deepToString(arr) only prints on one line.

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

Rhyous
  • 6,510
  • 2
  • 44
  • 50
  • 3
    Maybe use System.getProperty("line.separator"); instead of \r\n so it is right for non-Windows as well. – Scooter Dec 21 '13 at 22:01
20
for(int n: someArray) {
    System.out.println(n+" ");
}
Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
somedude
  • 267
  • 2
  • 2
  • 8
    This way you end up with an empty space ;) – Matthias Sep 21 '14 at 09:23
  • 1
    @ matthiad .. this line will avoid ending up with empty space System.out.println(n+ (someArray.length == n) ? "" : " "); – Muhammad Suleman Jun 01 '15 at 12:29
  • 1
    @MuhammadSuleman That doesn't work, because this is a for-each loop. `n` is the actual value from the array, not the index. For a regular for loop, it would also be `(someArray.length - 1) == i`, because it breaks when `i` is equal to the array length. – Radiodef Aug 06 '18 at 22:02
18

Different Ways to Print Arrays in Java:

  1. Simple Way

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output: [One, Two, Three, Four]

  1. Using toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

  1. Printing Array of Arrays

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

Resource: Access An Array

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
Aftab
  • 2,863
  • 32
  • 41
12

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

Andrew_Dublin
  • 745
  • 6
  • 22
  • 4
    It prints "1, 2, 3, 4, 5, " as output, it prints comma after the last element too. – icza Mar 10 '14 at 11:32
  • 3
    You could replace the code within the loop with `System.out.print(intArray[i]); if(i != intArray.length - 1) System.out.print(", ");` – Nepoxx Jul 16 '14 at 17:39
  • 2
    You could also use `System.out.print(i + (i < intArray.length - 1 ? ", " : ""));` to combine those two lines. – Nick Suwyn Jan 11 '16 at 18:55
11

It should always work whichever JDK version you use:

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

It will work if the Array contains Objects. If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..

Example:

int[] a = new int[]{1,2,3,4,5};

Replace it with:

Integer[] a = new Integer[]{1,2,3,4,5};

Update :

Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.

So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as

public void printArray(int [] a){
        //write printing code
} 
Greesh Kumar
  • 1,847
  • 3
  • 27
  • 44
  • 2
    Converting an Array to a List simply for printing purposes does not seem like a very resourceful decision; and given that the same class has a `toString(..)`, it defeats me why someone would ever do this. – Debosmit Ray May 13 '16 at 11:35
9

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
9

In java 8 it is easy. there are two keywords

  1. stream: Arrays.stream(intArray).forEach
  2. method reference: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
suatCoskun
  • 812
  • 2
  • 10
  • 14
7

You could loop through the array, printing out each item, as you loop. For example:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

item 1
item 2
item 3
Dylan Black
  • 262
  • 3
  • 16
7
  • It is very simple way to print array without using any loop in JAVA.

    -> For, Single or simple array:

     int[] array = new int[]{1, 2, 3, 4, 5, 6};
     System.out.println(Arrays.toString(array));
    

    The Output :

          [1, 2, 3, 4, 5, 6]
    

    -> So, this 2D array can't be printed with Arrays.toString()

     int[][] array = new int[][]{{1, 2, 3, 4, 5, 6, 7}, {8, 9, 10, 11, 12,13,14}};
     System.out.println(Arrays.deepToString(array));
    

    The Output:

       [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]]
    
Pang
  • 9,564
  • 146
  • 81
  • 122
6

There Are Following way to print Array

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }
Muskovets
  • 449
  • 8
  • 16
Ravi Patel
  • 129
  • 1
  • 3
5

There's one additional way if your array is of type char[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

abc
Roam
  • 4,831
  • 9
  • 43
  • 72
4

A simplified shortcut I've tried is this:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

1
2
3

No loops required in this approach and it is best for small arrays only

Mohamed Idris
  • 442
  • 4
  • 10
4

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
Haim Raman
  • 11,508
  • 6
  • 44
  • 70
  • Adding a dependency because of something trivial that be done in two lines of code is a screaming antipattern. – jurez May 11 '20 at 11:27
  • commons-lang3 is a very poplar dependency, and note that this answer was were most people didn't used java 8 – Haim Raman May 11 '20 at 18:58
  • Still the best solution as also referred in https://stackoverflow.com/questions/38425623/java-join-array-of-primitives-with-separator commons-lang is of course really popular and should be used instead of implement yourself. Such utility methods have to be tested and should also be accessible for other projects. As long as primitive arrays can not simple handled, a library like common-lang with overloaded methods is for me the best and efficient way to solve this problem. – Marc H. Nov 20 '20 at 16:39
4

For-each loop can also be used to print elements of array:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);
Ma_124
  • 45
  • 1
  • 11
hasham.98
  • 73
  • 3
  • @firephil System.out.println(a[i]); is used with ordinary for loop, where index "i" is created and value at every index is printed. I have used "for each" loop. Give it a try, hope you will get my point. – hasham.98 Dec 25 '16 at 21:22
3

To add to all the answers, printing the object as a JSON string is also an option.

Using Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • This is what I do. With this, you can print arbitrarily complex structures as long as they're encodable to JSON. I always make sure to use "pretty". Does your second example do that? I'd think you'd need to tickle a "pretty" option to get that. – CryptoFool Feb 10 '19 at 02:43
3
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

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

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

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

output: [John, Mary, Bob]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
fjnk
  • 62
  • 3
3

Here a possible printing function:

  public static void printArray (int [] array){
        System.out.print("{ ");
        for (int i = 0; i < array.length; i++){
            System.out.print("[" + array[i] + "] ");
        }
        System.out.print("}");
    }

For example, if main is like this

public static void main (String [] args){
    int [] array = {1, 2, 3, 4};
    printArray(array);
}

the output will be { [1] [2] [3] [4] }

2
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
2

This is marked as a duplicate for printing a byte[]. Note: for a byte array there are additional methods which may be appropriate.

You can print it as a String if it contains ISO-8859-1 chars.

String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

or if it contains a UTF-8 string

String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

or if you want print it as hexadecimal.

String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

or if you want print it as base64.

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

or if you want to print an array of signed byte values

String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

or if you want to print an array of unsigned byte values

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

if you are running jdk 8.

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

output:

[7,3,5,1,3]
duyuanchao
  • 3,863
  • 1
  • 25
  • 16
  • This is better than the accepted answer in that it gives more control over the delimiter, prefix and suffix. However, I would remove superfluous `toString()` in the final `System.out.println()` and used it in `joiner.add(element.toString())` instead of adding the empty string. This solution works for arrays of non-primitive types as well, uniformly. – John McClane Dec 14 '18 at 14:42
  • My bad, `element.toString()` inside `joiner.add()` is for non-primitive types only. You still need to use `Integer.toString(element)` - like constructs for primitive types. Personally, I used foreach loop `for (int element : array) joiner.add(Integer.toString(element));` instead of streams, but that's the matter of taste. – John McClane Dec 14 '18 at 15:02
2

If you are using Java 11

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String[] array = { "John", "Mahta", "Sara" };
       System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
     }
}

Output :

John Mahta Sara
Anis KCHAOU
  • 830
  • 1
  • 11
  • 11
1

In java 8 :

Arrays.stream(myArray).forEach(System.out::println);
Muskovets
  • 449
  • 8
  • 16
Mehdi
  • 1,340
  • 15
  • 23
  • Those who created a vote to remove my answer .. can you expose your point of view so everyone can learn ? The question asked for the simplest way in java, so it's a one liner, java current version is >14 and my solution is for at least java 8 ( so it is applicable ). – Mehdi Aug 05 '20 at 15:03
1

If using Commons.Lang library, we could do:

ArrayUtils.toString(array)

int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
ArrayUtils.toString(intArray);
ArrayUtils.toString(strArray);

Output:

{1,2,3,4,5}
{John,Mary,Bob}
Pradip Karki
  • 662
  • 1
  • 8
  • 21
1

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

 // #3
 Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

Also, starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below)

string[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

` The output will be "Hey there amigo!"

0

By using the java.util.Arrays:

String mRole = "M_XXX_ABC";        
System.out.println(Arrays.asList(mRole.split("_")).toString());

output: [M, XXX, ABC]

jkwli
  • 51
  • 1
  • 7
0

Use the Arrays class. It has multiple utility methods and its toString() is overriden to display array elements in a human readable way. Arrays.toString(arr)

0

For Android developers ending up here, this is for Kotlin:

println(myArray.joinToString())

OR

println(myArray.joinToString(separator = "|"))
Mahozad
  • 18,032
  • 13
  • 118
  • 133
-1

There are several ways to print an array elements.First of all, I'll explain that, what is an array?..Array is a simple data structure for storing data..When you define an array , Allocate set of ancillary memory blocks in RAM.Those memory blocks are taken one unit ..

Ok, I'll create an array like this,

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           System.out.print(number);
      }
}

Now look at the output,

enter image description here

You can see an unknown string printed..As I mentioned before, the memory address whose array(number array) declared is printed.If you want to display elements in the array, you can use "for loop " , like this..

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           int i;

           for(i=0;i<number.length;i++){
                 System.out.print(number[i]+"  ");
           }
      }
}

Now look at the output,

enter image description here

Ok,Successfully printed elements of one dimension array..Now I am going to consider two dimension array..I'll declare two dimension array as "number2" and print the elements using "Arrays.deepToString()" keyword.Before using that You will have to import 'java.util.Arrays' library.

 import java.util.Arrays;

 class demo{
      public static void main(String a[]){

           int[][] number2={{1,2},{3,4},{5,6}};`

           System.out.print(Arrays.deepToString(number2));
      }
}

consider the output,

enter image description here

At the same time , Using two for loops ,2D elements can be printed..Thank you !

Gayan Sampath
  • 163
  • 2
  • 5
  • int array[] = {1, 2, 3, 4, 5}; for (int i:array) System.out.println(i); – Manjitha Teshara Aug 04 '18 at 16:22
  • try this i think this is shortest way to print array – Manjitha Teshara Aug 04 '18 at 16:23
  • "the memory address whose array(number array) declared is printed" That's not true at all, its system hash code of object, and this can be based on many things, including memory address, but this could change later and hash code would not change. And currently its mostly a random number. https://gotofinal.dev/java/2017/10/08/java-default-hashcode.html – GotoFinal Jan 14 '20 at 12:14
-1

toString is a way to convert an array to string.

Also, you can use:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");
}

This for loop will enable you to print each value of your array in order.

Chen Jin
  • 39
  • 8