2006
04.06

挺无聊的题目真的难倒不少人,咳

public class Hello {
    public static void main(String[] args) {
        String s = "123";
        System.out.println(s);
        m1(s);
        System.out.println(s);

        int i = 123;
        System.out.println(i);
        m2(i);
        System.out.println(i);
    }

    private static void m1(String s) {
        s = "321";
    }

    private static void m2(int i) {
        i = 321;
    }
}

运行结果是什么?

  1. 学习

  2. m1是不是应该为 s = “321″? ;)

  3. 哦,是啊,我写错。改了

  4. 这个要不会java就白学了,成绩虽然不好,但还知道第一个是321,第二个是123的
    感觉在搞mp3…哈哈哈。。mpg123/mpg321

  5. SunQ, 这个可能是看学得够不够细致的问题。很遗憾,你的答案正是多数人的错误答案。都说了,挺无聊的问题。

  6. 都是123吧
    值传递的问题。。

  7. 都是123, 所谓按应用传递其实也是传值,只不过传的是地址而已,m1里S的值,也就是其本身所指地址的改变和main里的S毫无关系。只有通过传递的地址来操作对象的成员才会起到所谓传引用的作用。
    C#里有ref这样的参数来按引用的引用来传递参数,这样就能完成SunQ所说的效果了
    最近在看JAVA,不知道JAVA里有没有类似ref的方法?

  8. 123
    321
    123
    123

  9. 123
    123
    123
    123

  10. 123
    123
    123
    123

    in Java, all arguments are passed by value.

    so do C.

  11. 全部都是123

  12. 123
    123
    123
    123
    如果m1(String s)改為…
    private static void m1(String s) {
    this.s = “321″;
    }
    則輸出為
    123
    321
    123
    123

  13. this.s = \”321\”;

  14. this.s = ’321′;

  15. 為什麼引號都不能正常顯示….

  16. 剛剛測一下發現我說錯了
    不能在static裡用this
    Sorry….

  17. public class test {
      public static void main(String[] args) {
        mFunction mf = new mFunction();
        System.out.println(mf.s);
        mf.m1(mf.s);
        System.out.println(mf.s);

        System.out.println(mf.i);
        mf.m2(mf.i);
        System.out.println(mf.i);
      }
    }
    class mFunction {
      String s = “123″;
      int i = 123;
    public void m1(String s) {
        this.s = “321″;
      }

      public void m2(int i) {
        i = 321;
      }
    }