Input from text file to array - java

The input will be a text file with an arbitrary amount of integers from 0-9 with NO spaces. How do I populate an array with these integers so I can sort them later?
What I have so far is as follows:
BufferedReader numInput = null;
int[] theList;
try {
numInput = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
int i = 0;
while(numInput.ready()){
theList[i] = numInput.read();
i++;
Obviously theList isn't initialized, but I don't know what the length will be. Also I'm not too sure about how to do this in general. Thanks for any help I receive.
To clarify the input, it will look like:
1236654987432165498732165498756484654651321
I won't know the length, and I only want the single integer characters, not multiple. So 0-9, not 0-10 like I accidentally said earlier.

Going for Collection API i.e. ArrayList
ArrayList a=new Arraylist();
while(numInput.ready()){
a.add(numInput.read());
}

You could use a List<Integer> instead of a int[]. Using a List<Integer>, you can add items as desired, the List will grow along. If you are done, you can use the toArray(int[]) method to transform the List into an int[].

1 . Use guava to nicely read file's 1st line into 1 String
readFirstLine
2 . convert that String to char array - because all of your numbers are one digit lengh, so they are in fact chars
3 . convert chars to integers.
4 . add them to list.
public static void main(String[] args) {
String s = "1236654987432165498732165498756484654651321";
char[] charArray = s.toCharArray();
List<Integer> numbers = new ArrayList<Integer>(charArray.length);
for (char c : charArray) {
Integer integer = Integer.parseInt(String.valueOf(c));
numbers.add(integer);
}
System.out.println(numbers);
}
prints: [1, 2, 3, 6, 6, 5, 4, 9, 8, 7, 4, 3, 2, 1, 6, 5, 4, 9, 8, 7, 3, 2, 1, 6, 5, 4, 9, 8, 7, 5, 6, 4, 8, 4, 6, 5, 4, 6, 5, 1, 3, 2, 1]

Related

Alphanumeric otp generator returning same values every time [duplicate]

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]
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 ]
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));
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 ) );
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
*/
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);
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!".
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
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.)
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.
for(int n: someArray) {
System.out.println(n+" ");
}
Different Ways to Print Arrays in Java:
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]
Using toString()
String[] array = new String[] { "One", "Two", "Three", "Four" };
System.out.println(Arrays.toString(array));
Output: [One, Two, Three, Four]
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
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
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
}
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.
In java 8 it is easy. there are two keywords
stream: Arrays.stream(intArray).forEach
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));
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
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);
}
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]]
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
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
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>
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);
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));
// 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]
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] }
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);
}
}
}
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.
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]
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
In java 8 :
Arrays.stream(myArray).forEach(System.out::println);

Replacing more than one character in a String

I am printing an array, but I only want to display the numbers. I want to remove the brackets and commas from the String (leaving only the digits). So far, I have been able to remove the commas but I was looking for a way add more arguments to the replaceAll method.
How can I remove the brackets as well as the commas?
cubeToString = Arrays.deepToString(cube);
System.out.println(cubeToString);
String cleanLine = "";
cleanLine = cubeToString.replaceAll(", ", ""); //I want to put all braces in this statement too
System.out.println(cleanLine);
The output is:
[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5]]
[[0000][1111][2222][3333][4444][5555]]
You can use the special characters [ and ] to form a pattern, and then \\ to escape the [ and ] (from your input) like,
cleanLine = cubeToString.replaceAll("[\\[\\]\\s,]", "");
or replace everything not a digit. Like,
cleanLine = cubeToString.replaceAll("\\D", "");
What you are doing is effectively using Java like you use a scripting language.
In this case, it happens to work well because your arrays only contain numbers and you don't have to worry about escaping characters that may also appear inside your array elements.
But it's still not efficient or Java-like to be converting strings several times, one of them with regular expressions (replaceAll), to get to your end-result.
A nicer and more efficient approach is to directly build the string that you need without any comma's or square brackets:
public static void main(String[] args) throws Exception {
int[][] cube = { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 },
{ 5, 5, 5, 5 } };
StringBuilder builder = new StringBuilder();
for (int[] r : cube) {
for (int c : r) {
builder.append(c);
}
}
String cleanLine = builder.toString();
System.out.println(cleanLine);
}
Output:
000011112222333344445555

Filling an array with random numbers in a for-loop [duplicate]

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]
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 ]
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));
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 ) );
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
*/
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);
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!".
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
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.)
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.
for(int n: someArray) {
System.out.println(n+" ");
}
Different Ways to Print Arrays in Java:
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]
Using toString()
String[] array = new String[] { "One", "Two", "Three", "Four" };
System.out.println(Arrays.toString(array));
Output: [One, Two, Three, Four]
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
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
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
}
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.
In java 8 it is easy. there are two keywords
stream: Arrays.stream(intArray).forEach
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));
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
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);
}
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]]
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
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
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>
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);
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));
// 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]
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] }
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);
}
}
}
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.
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]
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
In java 8 :
Arrays.stream(myArray).forEach(System.out::println);

Input two integer separated by space to determine a 2D array dimension [duplicate]

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]
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 ]
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));
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 ) );
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
*/
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);
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!".
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
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.)
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.
for(int n: someArray) {
System.out.println(n+" ");
}
Different Ways to Print Arrays in Java:
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]
Using toString()
String[] array = new String[] { "One", "Two", "Three", "Four" };
System.out.println(Arrays.toString(array));
Output: [One, Two, Three, Four]
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
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
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
}
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.
In java 8 it is easy. there are two keywords
stream: Arrays.stream(intArray).forEach
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));
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
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);
}
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]]
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
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
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>
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);
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));
// 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]
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] }
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);
}
}
}
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.
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]
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
In java 8 :
Arrays.stream(myArray).forEach(System.out::println);

How do I convert a String to an String Array? [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
I'm reading from a file using Scanner, and the text contains the following.
[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]
This was originally an integer Array that I had to convert to a String to be able to write in the file. Now, I need to be able to read the file back into java, but I need to be able to add the individual numbers together, so I need to get this String back into an array. Any help? Here's what I have:
File f = new File("testfile.txt");
try{
FileWriter fw = new FileWriter(f);
fw.write(Arrays.toString(array1));
fw.close();
} catch(Exception ex){
//Exception Ignored
}
Scanner file = new Scanner(f);
System.out.println(file.nextLine());
This prints out the list of numbers, but in a string. I need to access the integers in an array in order to add them up. This is my first time posting, let me know if I messed anything up.
You can use String#substring to remove the square brackets, String#split to split the String into an array, String#trim to remove the whitespace, and Integer#parseInt to convert the Strings into int values.
In Java 8 you can use the Stream API for this:
int[] values = Arrays.stream(string.substring(1, string.length() - 1)
.split(","))
.mapToInt(string -> Integer.parseInt(string.trim()))
.toArray();
For summing it, you can use the IntStream#sum method instead of converting it to an array at the end.
You don't need to read the String back in an Array, just use Regex
public static void main(String[] args) throws Exception {
String data = "[8, 3, 8, 2, 3, 4, 41, 4, 5, 8]";
// The "\\d+" gets the digits out of the String
Matcher matcher = Pattern.compile("\\d+").matcher(data);
int sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
System.out.println(sum);
}
Results:
86
List<Integer> ints = new ArrayList<>();
String original = "[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]";
String[] splitted = original.replaceAll("[\\[\\] ]", "").split(",");
for(String s : splitted) {
ints.add(Integer.valueOf(s));
}

Categories