Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show values of different array types

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?

like image 609
Fabian König Avatar asked Mar 17 '23 19:03

Fabian König


2 Answers

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

like image 100
nsommer Avatar answered Mar 28 '23 01:03

nsommer


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 then println().

like image 26
Maroun Avatar answered Mar 28 '23 02:03

Maroun