java中关于char[]数组输出问题

来源:互联网 发布:算法设计与分析屈婉玲 编辑:程序博客网 时间:2024/05/22 03:17

今日在论坛上看到一个帖子发现了一个问题,以前这个问题没有注意到,今日特意记录下来,进行分享,希望能够为java学习带来一些帮助。

public class First {public static void main(String[] args) {char[] ch = {'a','b','c'};System.out.println(ch);System.out.println("ch"+ch);}}

输出结果为:

abc
ch[C@15db9742

这样的结果存在疑问,为什么第二次的输出结果不是chabc


分析:

System.out.println(ch);//调用的println方法的参数是char[]数组,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();        }    }


System.out.println("ch"+ch);//调用的println方法的参数是char[]数组,println方法的源代码:

/**     * Prints a String and then terminate the line.  This method behaves as     * though it invokes <code>{@link #print(String)}</code> and then     * <code>{@link #println()}</code>.     *     * @param x  The <code>String</code> to be printed.     */    public void println(String x) {        synchronized (this) {            print(x);            newLine();        }    }


这两次调用的println方法是不同的,
第一次调用的方法的参数是char[]数组类型
第二次调用的方法的参数是String类型的,因为“ch”+ch把数组转化成了字符串String类型的了
这是println方法的重载问题导致的。


原创粉丝点击