Java Tutorial/Methods

So far, we've been putting all our code into one method or function,. However, we can also have more than one method! To make a new method, just write something like:

Note that there is nothing in the parentheses. Anything within it is called a parameter. But first, lets learn how to use our new method...

The main method calls anotherMethod, by writing its name. Now, say you wanted the main method to tell anotherMethod what to write. Then...

As you can see, anotherMethod takes in a String (what_to_print) as a parameter, and then accesses its value. However, this is not all that methods can do. As you can see, we are using something called void. This means, essentially, nothing. What if we wanted anotherMethod to tell the main method what to print? Well, look at this:

anotherMethod returns a string for main to print. Because it does this,  is just like a variable, except that it's code is being executed instead of its value being accessed. You can change what it returns, but it has to be a String, as that's what we specified it would return.

Excercises

 * Change what anotherMethod returns to an integer
 * Try removing main's parameter, and see what errors you get

Answer: