为什么java中输出字符数组名得到的是数组的内容

Java API关于println介绍

Java 关于println的源代码
/**
* Prints an array of characters and then terminate the line. This method
* behaves as though it invokes <code>{@link #print(char[])}</code> and
* then <code>{@link #println()}</code>.
*
* @param x an array of chars to print.
*/
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
在源代码中关于输出的是别的类型的数组时,例如int数组时
int[] arr1 = new int[] { 1, 2, 3 };
System.out.println(arr1);
Java源码所做的操作是
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
此时用到了String类中的valueOf()方法,而vlaueOf()方法也是对于char数组输出内容,对于其他引用类型输出为地址值。

本文探讨了Java中使用System.out.println()输出字符数组和非字符数组时的不同行为。通过源代码分析,揭示了println方法如何处理不同类型数组的输出。对于char数组,它直接打印数组内容;而对于其他类型的数组,如int数组,println首先调用String.valueOf()方法,导致输出对象的内存地址。这种差异源于Java API的设计和String类的valueOf()方法的实现。
1559

被折叠的 条评论
为什么被折叠?



