Methods

Method Declarations

Methods in Kenya have the following structure:

	returnType methodName( arguments... ){
		statements...
	}

The return type for a function can be any valid type ( basic, array, class or user defined ), if you don't wish to return something from a function, use the keyword void.

The arguments are a list of variable declarations which are passed in from the calling method, see the example below:

Returning from a Method

Returning from a method is usually directed by the keyword return.

If a method is declared to return a type (i.e. isn't declared void), then all possible routes through the method that could run to completion must feature a return statement, with an expression which is what-to-return.

If a method is declared void, then return statements with no expression may be used to prematurely return from the method, or the method can just "run off the end" where an implicit return is assumed.

For more, see the example below.

Method Invoking

To invoke a method, use its name, and pass in arguments of the correct type in the same order as declared.

If a method has a non-void return type, you can also use the returned value from the function as part of an expression.

Methods Example

Example 1.2. Methods Example

void main(){
	int seven = addTwoNumbers( 3, 4);
	
	printANumber( seven );
	
	int[] nums = { 1,2,3,4,5,6 };
	printANumber ( getLargest( nums ));
}

int addTwoNumbers(int a, int b){
	return a + b;
}	

void printANumber( int number ){
	println(number);
}

int getLargest( int[] array ){

	if( array.length == 0 ){
		return -1;
	}
	
	int cLargest = array[0];
	
	for(int i = 1 ; i < array.length ; i++ ){
		if( array[i] > cLargest ){
			cLargest = array[i];
		}
	}
	
	return cLargest;

}