How To - Java Methods

Let's begin with the basics. 
In the first post we took a look at the small Program HelloWorld which printed the message Hello World out into our command line.

This was a very simple program and with a basic command, but when we write scripts or programs that calculate values, or help sorting stuff we will need methods.

We will write a program that calculates the middle value of two fixed values we give the method.


Try to read the code and understand what part stands for what:
- class name, main method, what is being called in the main method

So here again in line 1 we have a public class with the class name MiddleVal for Middle Value, then open brackets to open the class body,
line 2 contains the main method (which makes this class autonomous in itself) which also calls out method in the 3. line with 2 parameters that we give to the method.

Now we can take a closer look into line 6 - what does the method in line 3 actually do?
It's called public static int middleValue and to use this method we need to give it 2 Integer parameters: int a and int b.

Also note the int which is placed right before the method name - this is our return value, what for a type of value you will get back from the method once it has finished its work.

In the method body we introduce a new Integer value called int middle, which gets it's value assigned by the term (a + b)/2 and as always we close commands with a semicolon

If you want to calculate the middle value for numerous fixed parameters, you need to add these to the parameter list in the round brackets of your method.


Comments