java中關於char[]陣列輸出問題
阿新 • • 發佈:2019-01-02
今日在論壇上看到一個帖子發現了一個問題,以前這個問題沒有注意到,今日特意記錄下來,進行分享,希望能夠為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[[email protected]
這樣的結果存在疑問,為什麼第二次的輸出結果不是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方法的過載問題導致的。