Monday, May 21, 2012

Returning from a Function: Job Well Done




This is closely connected to my previous post Functions: Running when you call the name. In that post, we used a function to print something directly to a web page using javascript. In this post we'll use a powerful ability of functions: passing values to a function and returning values from a function.

Functions still have the same primary purpose, they help you organize your code and keep things simplified and compact. But now we are also exploring the ability to return values from the functions. Basically, when your function finishes, it says, "Did. That." and sends information back to where you called the function.

Let's look at an example function that is very simple:


Let's break it down line by line.



Is two function calls in one. The inner function call (add(5)) is executed first and is passed the value 5. The outer function call "System.out.println()" is executed second, and is passed the result of add(5).

Next we have our function declaration.


"public" is the visibility of this function (Don't worry about this much for now, it defines what programs can call the function). "int" is the return type of the function. The main focus of the post! This specifies that we are going to return a type int from this function. Then we have the name "add" which we saw above. Lastly, in parens ( "(" or ")" ) we have the parameters. The parameters are the things that we give to the method. It creates a variable that can be used within the function.

The next two lines go together:

We declare the variable with "int output" and then we assign a value to it.

Notice that we are using the parameter from the function declaration here. We can use input just like a variable we declared ourselves. So we add 1 to it and assign the result to output.

Now for the interesting part!

Boom! Now it's fun. Seriously. No, seriously, this is fun.

Remember this line:


And specifically the part


Well, return output is what links this all together. The return keyword takes output, goes all the way back up to the function call and inserts whatever value was in output into that point in the code where the function call was. So after the function call is done and the return keyword runs, here's what we have:


Note, we have six because out function added 1 to 5.

And then the call System.out.println() will print "6" to the console.

No comments:

Post a Comment