I have a question about the output of Arrays in Java. So, when I have this code:
char[] chars = new char[] {'a', 'b', 'c'};
System.out.println(chars);
Then the output is: abc
.
I know that an Array is an Object in Java. So I think the toString()
method will be called here?
But if I have this code:
int[] ints = new int[] {3, 4, 5};
System.out.println(ints);
Then the output is: [I@1540e19d
.
Why is the first code working and not the second one?
I know that I can call the static method toString()
in class Arrays
, but this not the answer I'm looking for.
Can you help me, why the Java developers using different techniques to show the values of Arrays?
Look at the method signatures of the println
method:
println(char [] x) exists: The method converts each character into a byte value according to the system's character encoding and prints them all.
But there does not exist any method, that takes an integer array.
Instead, the generic println(Object x) method is called
Because println
method overloaded and can accept char[]
, see its source - println(char x[])
:
757 public void println(char x[]) {
758 synchronized (this) {
759 print(x);
760 newLine();
761 }
762 }
print
calls write(char buf[])
which iterates on the sequence and print it.
Also refer to the docs and see PrintStream#println(char[] x)
:
Prints an array of characters and then terminate the line. This method behaves as though it invokes
print(char[])
and thenprintln()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With