0

how after the execution of if block in the whole program, the statement "System.out.println("after method showValue\t:"+ab);" is still able to fetch previous values ? i thought this statement will print 0 everytime but its not happening ?

public class Me{

public static void main(String[] args) {
    int ab=98;
    System.out.println(" value of ab in main at start\t:"+ab);
    Mno ref=new Mno();
    ref.showValue(ab);
    System.out.println("value of ab in Main After completion\t:"+ab);
}
}

class Mno{
    void showValue(int ab){
    System.out.println("Before method showvalue\t:"+ab);
    if (ab!=0){
        showValue(ab/10);}
    System.out.println("after method showValue\t:"+ab);

}

}

4

1 回答 1

3

Java 是按值传递的,所以showValue()你不是在处理ab你在你的声明中声明的,main()而是在处理一个副本。想一想,你甚至没有ab在任何地方重新分配,所以它怎么可能改变?

在任何情况下,您都可以通过以下方式看到传递值的概念:

public static void main(String[] args) {
    int n = 42;
    foo(n);
    System.out.println(n);
}

public static void foo(int n) {
    n = 0;
}
42

foo()中,我们正在重新分配 的副本n,而不是更改在 中的n定义main()


编辑我现在看到您在问为什么每次到达时showValue()都不会打印第二个打印语句。0要了解原因,让我们手动逐步完成函数调用。这就是当您调用它时会发生showValue(ab)的情况main()

  • 调用带有参数的函数ab = 98
  • 打印98(第一次打印声明)
  • 98 != 0,所以:(if-语句)
    • 再次使用参数调用函数ab = ab/10 == 9
    • 打印9(第一次打印声明)
    • 9 != 0,所以:(if-语句)
      • 再次使用参数调用函数ab = ab/10 == 0
      • 打印0(第一次打印声明)
      • 0 == 0,所以不要输入if-语句。
      • 打印0(第二次打印声明)
    • 打印ab,在9这里。(第二次印刷声明)
  • 打印ab,在98这里。(第二次印刷声明)
于 2013-09-14T14:41:42.937 回答