I was studying the Java tutorials here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
However a doubt appeared:
Why do I need the new String()
? Is there any potential problem of using directly System.out.println(copyTo)
? I thought that under the hood the println already had the toString method that converts to strings.
class ArrayCopyOfDemo {
public static void main(String[] args) {
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd'};
char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
System.out.println(new String(copyTo));
}
}