开发者

Am I understanding passing arguments to functions correctly?

Total noobie question here.

I'm just learning Java, and studying passing arguments to functions. I created this basic examp开发者_运维问答le, and it is doing what I expect, but I want to be sure I am understanding the "signal path" correctly:

    public void run() {

        int value = 4;
        println(" the value is "+ add(value));  
    }

    private int add(int n) {        
        int result = 4;
        result = n + result;

        return result;
            }
    }

Am I correct to say that:

1) the int value is being passed from add(value) to the private method and so then int n = 4

2) then the result = n + return. (8)

3) then the return result passes back to the public method and takes the place of add(value).

Is my thinking correct? Thanks! Joel


Yes, precisely.


1) the int value is being passed from add(value) to the private method and so then int n = 4

The int value is being passed to the method add(), and then int n will be 4.

2) then the result = n + return. (8)

Yes, that's true. An alternate syntax would be result += n; Which would do the exact same thing.

3) then the return result passes back to the public method and takes the place of add(value).

Yes, then the value is returned from add and that is the value that would be used.


Your thinking is correct.


Yes, this is what parameter passing and value returning is all about. Note that in Java, everything is passed by value.

This means the following:

 void f(int x) {
   x = 0;
 }

 void main() {
   int n = 10;
   f(n);
   // n is still 10
 }


On (2) that should be "result = n + result", not "n + return". But I think that's just a typo, you appear to understand what's going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜