Functions

The program asks the user to enter the length and width. A function is called to print the area.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Area program: using area function that returns nothing
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
	  Scanner keyboard=new Scanner(System.in); //do just once
	  double length, width;
	  System.out.print("Enter length:");
	  length=keyboard.nextDouble();
	  System.out.print("Enter width:");
	  width=keyboard.nextDouble();
	  area(length,width);
  }//main
  public static void area(double l, double w){
	  double a;
	  a=l*w;
	  System.out.println("The area is "+a);
  }//area
}//class
CODE

Sample output:

Enter length:8
Enter width:9
The area is 72.0

The function area does not return anything (void) and must receive 2 double values. The two values will be stored in the variables l and w. These are the parameters.

In main we call function area and pass the values of length and width. These values are called the arguments. The compiler will compare the parameters with the arguments in the calling statements to make sure that the function is called correctly.

NEXT: