大家帮忙看看,下面二个例子。
为什么调用方法后,s的值没有改变?
方法调用时,内存是怎样的?
这两个例子,在内存调用上有什么不同?
谢谢各位!
-------------------------------
public class Test11 {
public static void main(String [] args) {
String s="welcome";
ptt(s);
System.out.println("s2="+s);
}
public static void ptt(String s) {
s="comehere";
System.out.println("s1="+s);
}
}-------------------------------
public class TestMethod {
String s="welcome";
public static void main(String[] args) {
new TestMethod().pt();
}
public void pt(){
new Testm().ptt(s);
System.out.println("s2="+s);
}}
class Testm{
public void ptt(String s) {
s="comehere";
System.out.println("s1="+s);
}
}
-----------------------------
其运行结果均为
s1=comehere
s2=welcome
-----------------------------

解决方案 »

  1.   

    我觉的这样以不对啊?
    -----------------------
    public static void main(String[] args) {
    String s="welcome";
    System.out.println("s1="+s);
    s="comehere";
    System.out.println("s2="+s);
    }
    运行结果
    s1=welcome
    s2=comehere
    -----------------------
    上面s的指向不是改变了吗?
    那为什么调用方法时,之后s的指向不会改变呢?
      

  2.   

    我觉的这样以不对啊?
    -----------------------
    public static void main(String[] args) {
    String s="welcome";
    System.out.println("s1="+s);
    s="comehere";
    System.out.println("s2="+s);
    }
    运行结果
    s1=welcome
    s2=comehere
    -----------------------
    上面s的指向不是改变了吗?
    那为什么调用方法时,之后s的指向不会改变呢?
      

  3.   

    我觉的这样以不对啊?
    -----------------------
    public static void main(String[] args) {
    String s="welcome";
    System.out.println("s1="+s);
    s="comehere";
    System.out.println("s2="+s);
    }
    运行结果
    s1=welcome
    s2=comehere
    -----------------------
    上面s的指向不是改变了吗?
    那为什么调用方法时,之后s的指向不会改变呢?
      

  4.   

    你的S第2次被重新赋值了,也就是从welcome变成comehere
    LZ有什么不懂的?
      

  5.   

    public static void main(String[] args) {
    int p=3;
    ptt(p);
    System.out.println("p2="+p);
    }
    public static void ptt(int p) {
    p=2;
    System.out.println("p1="+p);
    }
    -------------------------------------------
    p1=2
    p2=3那么如里int类 
    也不变啊?
      

  6.   

    你调用方法时public void ptt(String s)这里的s只是个参数,你在方法里s="comehere";改变了s的值只是参数的值,不是全局String s="welcome"; 的值,
    改变参数值不影响全局的s的值
      

  7.   

    你要想在方法里改变成员变量要用到this关键字,this.s=comehere这样就改变了
      

  8.   

    调用方法时
    public static void ptt(int p)
    public static void ptt(String s)
    往里面传的是什么啊?
      

  9.   

    java 中只有值传递
    public static void ptt(int p) 中传的是一个int变量的值
    public static void ptt(String s) 中传的是字符串的地址的值
      

  10.   


    反正你记住他们传进来的是一个值而已,你改变他对成员变量不影响的
    要想改变成员变量的值就用this
      

  11.   

    也特别谢谢ysm010613的多次关注。
    要贴了,分不多请见谅!