The first thing most developers come across in Java is subprogram or procedures.
A subprogram is a division of code that separates operations from each other. A subprogram allows code to be organised based on it's purpose.
A subprogram could be created to carry out a task that involves something specific on the computer such as deleting a file. If this was what the subprogram does, then the subprogram should have an appropriate name to make it clear that this is what it does.
When the code is required or must be run, it is called. The part of the subprogram that uniquely identifies it is the name combined with the parameters. This is called the signature.
Below is a simple diagram that explains the subprogram structure:
Defining a subprogram
Below is an example subprogram:
void main(String[] argv){ // Do something }
The subprogram shown above is called main. It is the entry point of every Java program, and it is where the program begins executing.
Subprograms can also return values. For example, a subprogram that performs a calculation might return the result to the part of the program that called it. This is done using a return type.
int addNumbers(int a, int b){ return a + b; }
In this example, the subprogram is called addNumbers and it takes two int (integer) parameters. When called, it adds them together and returns the result. The return keyword is used to send a value back to the code that called it.
Calling subprograms
Subprograms can be called from other parts of the program. When a subprogram is called, the program temporarily leaves the current section of code and runs the subprogram instead. Once the subprogram finishes, the program returns to where it left off.
int result = addNumbers(5, 3); System.out.println("The result is " + result);
This will display:
The result is 8
Subprograms that return no value are called procedures, whereas subprograms that return a value are called functions.
Parameters
Parameters are variables that allow data to be passed into a subprogram. They make subprograms more flexible by allowing the same code to be reused with different inputs. Each parameter has a type and a name.
When a subprogram is called, values are sent into it. These values are known as arguments. The arguments must match the parameters in both number and data type.
void greet(String name){ System.out.println("Hello, " + name + "!"); } greet("Jamie");
Hello, Jamie!
In this example, the subprogram greet accepts a single parameter called name. When the subprogram is called with the argument "Jamie", that value is assigned to the parameter and used inside the subprogram.
