Methods in Java
Objectives
- Write and call (use) methods
- Pass arguments to a method
- Return a value from a method
- Understand how calling a method alters execution flow
Prerequisites
- Understand Java primitive types
- Understand execution flow and control statements
- Sequence
- Selection (if statement)
- Repetition (while, for, do while statements)
Writing a Method
- The main reason for writing code inside methods, is to make the
code resuable.
- Write code inside methods also helps to organize a program.
- A method consists of a header and a body.
- The header is the first line of the method.
- The body begins and ends with braces.
- Syntax:
modifiers returnType methodName(parameter1, parameter2, ..., parameterN)
{
method body;
}
- Example:
public static
double
average(double a, double b, double c)
{
double sum;
sum = a + b + c;
return sum / 3.0;
}
Calling a Method
- The computer will not execute the code in a method until the
method is called.
- To call a method, simply type the method name followed by an
argument list to match the method's parameter list.
- Syntax:
varName = methodName(argument1, argument2, ..., argumentN);
- Examples:
double avg;
avg = average(3.1, 5.4, 2.3);
double avg2 = average(6, 2, 3);
Complete Example
public class MethodTest
{
public static void main(String args[])
{
double num1 = 4.1;
double num2 = 4.2;
double num3 = 5.7;
double avg = average(num1, num2, num3);
System.out.println("average is " + avg);
}
public static double average(double a, double b, double c)
{
double sum;
sum = a + b + c;
return sum / 3.0;
}
}
Copyright © 2010, Maia L.L.C. All rights reserved.