Why will this code not print out a string?
String s = "My name is Jack";
String[] arr = s.split("");
char[] a = Arrays.toString(arr).toCharArray();
System.out.println(a);
System.out.println(new String(a));
You didn't make a char[]
array, but rather a String[]
array. Use String#toCharArray()
instead:
String s = "My name is Jack";
char[] letters = s.toCharArray();
System.out.println(Arrays.toString(letters));
System.out.println(new String(letters));
It does print out a String, at least on the second println (the first println yields exactly the same output, but it does it without constructing the String).
However, the chars of the string you are printing is obtained via:
char[] a = Arrays.toString(arr).toCharArray();
Arrays.toString
gives you a string surrounded by []
, separated with commas. So "hello"
would look like:
[h, e, l, l, o]
You then get the chars of this string, and try to reconstitute it into a string (which is redundant anyway, just print Arrays.toString(arr)
).
To print the joined string, use String.join
:
String.join("", arr)