Reputation: 525
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);
}
}
Upvotes: 0
Views: 269
Reputation: 129547
Java is pass-by-value, so in showValue()
you're not handling the ab
you have declared in your main()
but rather dealing with a copy. Come to think of it, you're not even reassigning ab
anywhere, so how could it possibly change?
In any case, you can see the pass-by-value concept at work in something like this:
public static void main(String[] args) {
int n = 42;
foo(n);
System.out.println(n);
}
public static void foo(int n) {
n = 0;
}
42
In foo()
, we are reassigning a copy of n
, not changing the n
defined in main()
.
EDIT I see now that you're asking why the second print statement in showValue()
doesn't print 0
each time it is reached. To see why, let's step through the function call by hand. This is what happens when you call that showValue(ab)
in main()
:
ab = 98
.98
(1st print statement)98 != 0
, so: (if
-statement)
ab = ab/10 == 9
.9
(1st print statement)9 != 0
, so: (if
-statement)
ab = ab/10 == 0
.0
(1st print statement)0 == 0
, so don't enter if
-statement.0
(2nd print statement)ab
, which is 9
here. (2nd print statement)ab
, which is 98
here. (2nd print statement)Upvotes: 3