tags:

views:

90

answers:

6

Total noobie question here.

I'm just learning Java, and studying passing arguments to functions. 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

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

+3  A: 

Yes, precisely.

Adeel Ansari
What I needed to know I'm on the right track. :-D Thanks!
Joel
+1  A: 

Hi Joel. Your thinking is correct.

Rouan van Dalen
+2  A: 

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.

zipcodeman
A: 

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
 }
polygenelubricants
"everything is passed by value": That is a very confusing thing to say, as with all Object parameters, the method will be working on the same instance that the caller had. You can say "the reference to the object is passed by value", but in effect (i.e. with regards to how it plays out for the programmer), only primitive types are passed by value.
Thilo
Did you read the article? Java passes everything by value, and there's nothing confusing about that statement. Object mutability is a totally separate issue.
polygenelubricants
A: 

yes man ur correct :)

Neo
A: 

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.

Jay