public class Itv { static String ss = "kkkkkk"; static String ss1 = new String("kkkkkk"); public void change(String str, char ch[]){ str = "kkkkkk"; System.out.println(str == ss);//true System.out.println(str == ss1);//false System.out.println("------------------"); str = new String("kkkkkk"); System.out.println(str == ss);//false //這句其實是廢話 System.out.println(str == ss1);//false ch[0] = 'J'; } public static void main(String[] args) { String str = new String("good"); String fry = "good"; System.out.println(str == fry);//false System.out.println("############"); char[] ch = {'t','e','s','t'}; Itv itv = new Itv(); itv.change(str,ch); System.out.println("-----------------------------------------"); itv.change(fry,ch); System.out.println(str+"---"+ Arrays.toString(ch));//good---[J, e, s, t] System.out.println(fry+"---"+ Arrays.toString(ch));//good---[J, e, s, t] } }
根據輸出結果得出結論: 傳遞的的確是引用,在常量池中有了“kkkkkk”就直接指向此字串的地址,如果沒有就在常量池中開闢空間然後把地址給str
如有不對,請大佬指正