简体   繁体   English

我是否正确理解向函数传递参数?

[英]Am I understanding passing arguments to functions correctly?

Total noobie question here. 总诺比问题在这里。

I'm just learning Java, and studying passing arguments to functions. 我只是在学习Java,并研究将函数传递给函数。 I created this basic example, 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 1) int valueadd(value)传递给private方法,因此int n = 4

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

3) then the return result passes back to the public method and takes the place of add(value) . 3)然后return result传回公共方法并取代add(value)

Is my thinking correct? 我的想法是否正确? Thanks! 谢谢! Joel 乔尔

是的,确切地说。

1) the int value is being passed from add(value) to the private method and so then int n = 4 1)int值从add(value)传递给private方法,因此int n = 4

The int value is being passed to the method add(), and then int n will be 4. int值将传递方法add(),然后int n将为4。

2) then the result = n + return. 2)然后结果= n +返回。 (8) (8)

Yes, that's true. 是的,这是真的。 An alternate syntax would be result += n; 替代语法是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). 3)然后返回结果传回公共方法并取代add(value)。

Yes, then the value is returned from add and that is the value that would be used. 是的,然后从add返回值,这是将使用的值。

你的想法是正确的。

Yes, this is what parameter passing and value returning is all about. 是的,这是参数传递和值返回的全部内容。 Note that in Java, everything is passed by value . 请注意,在Java中, 所有内容都按值传递

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". 在(2)上应该是“result = n + result”,而不是“n + return”。 But I think that's just a typo, you appear to understand what's going on. 但我认为这只是一个错字,你似乎明白发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM