Java: pass by value or reference?

http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#37472

" When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor."

everything is pass by value, but if it is an object, the fields of the object could be modified, but the object itself cannot be modified, this is the traditional idea of "pass by reference".

e.g.
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "old";
        System.out.println(s);
        fun(s);
        System.out.println(s);
    }
   
    public static void fun(String s){
        s = "new";
        return;
   
    }

}

output:
old
old
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章