about


Scribe:

chrono

blog

Time

science!

book musings

gov

'punk

missle defense

jams

antiques

cultcha blog


Construct:

scripts & programs

on the town

snaps


Self:

creds (PDF)

key

missive


Java Functions

A programming task that is somewhat generic and is done more than once can be abstracted into what is called, in Java, a method. (In other languages, it can be called a procedure, or a function).

The method itself is a standard block of Java code. You have to DEFINE the method correctly, though. Here is how you package it:

modifier returnDataType methodName(List of parameters) {code}
The methodName is the name of this method being created. The list of parameters are the list, one by one, of the names of the input variables, preceded by their data types. The returnDataType is the data type that the method will hand back, once its finished its chore (i.e. "int"). More on the modifier later...

O.K., with that in mind, here is how you call a method, from your code:

int nameOfResultVariable = nameOfMethod(parameter, parameter, ...)
When the method is called, the control of the program is shifted to the method. When the method is finished doing its thing, control is returned to the rest of the program.

The call of the method can itself be treated as a value.

Here is some sample code:

public class MethodMan {


	public static void main(String[] args) {
		int a = 1;
		int b = 2;
		int c = total (a, b);
			System.out.println(c);
	}
	
	public static int total(int firstNumber, int secondNumber){
	int sum;
	
		sum = firstNumber + secondNumber;
	
	return sum;

}

}
In this method call, we add two numbers numbers together. The numbers are declared as variables a and b. We hand a and b to a function called "total," which requires two integers as inputs.

The function renames a and b as firstNumber and secondNumber, respectively. It adds firstNumber and secondNumber together, calling the total "sum." Sum is returned to retuned to the main program, which is renamed as "c" and printed.

Material taken (& probably abused) from the book, "Introduction to Java Programming" (7th edition), by Y. Daniel Liang....

...as well as from the materials of a class I am taking.--Joab Jackson