A method (sometimes referred to as functions) is a collection of code that you can call from your program. You can pass values to them and they can return a result. They help keep your programs organised, a method can be called multiple times and can be reused in other programs.
Methods also help with security and maintenance, any improvements to a method benefits your program anywhere it is called.
The following simple method calculates the area of a rectangle. It takes two values and returns the result as an integer.
int myarea(int width,int height){ return (width*height); }
A method does not have to take or return a value:
void hello(){ System.out.println("Hi there!"); }
With the Java JDK installed, from a command line:
class Area{ // Take two values and return the area of a rectangle public static int myarea(int width,int height){ return (width*height); } public static void main(String[] args){ // The result of the function gets put in our result variable int result=myarea(10,20); System.out.println("The area is "+result); } }
Created (04/05/2025)