Modern programming languages are very small, but they allow you to extend the language by creating new command words.
In Java, a new word is called a function or method. Functions are a powerful way to keep your code readable and easy to maintain.
A function is an abstraction: it does something, but you don't have to know how it does it in order to use it.
You can think of a function as a machine. All machines have some function (do something):
- Some machines (like a meat grinder) require input of raw materials and output (return) processed materials.
- Other machines (like a music box) produce output (music) without any specific input.
- Still other machines have neither inputs nor outputs but affect other things (like pressing the button on your car remote control)
Every Java function has 4 primary characteristics:
- a name followed by parentheses
- optional inputs (called parameters) placed inside the parentheses
- a body (the code that defines what the function does)
- an optional output (called a return value)
Consider the following function:
int square(int a) { return a * a; }
- The function's name is square (notice that function names are typically verbs because they do something).
- It takes an input parameter that is an integer and is referred to within the function as a.
- The function returns an integer that it computes by multiplying a by itself.
You could use the square function as follows:
int a = 9; int b = square(a);
The two pieces of code above can be used to create the following program.
public class function { static int square(int a) { return a * a; } public static void main(String args[]) { int a = 9; int b = square(a); System.out.println("b=" + b); } }
Functions can take more than one parameter, but they can only return 1 value (or no values). Consider this function that takes two input parameters and returns no value:
void echo(String msg, int times) { for (int n=0; n<times; n++) { System.out.println(msg); } }
Create a new EchoExample project folder and in it create an Echo program as follows:
public class Echo { static void echo(String msg, int times) { for (int n=0; n<times; n++) { System.out.println(msg); } } public static void main(String args[]) { echo("howdy", 10); } }
- Save the program as Echo.java
- Run the program and observe the output
- For now, we're going to ignore the keywords public and static, we'll get to those soon