METHODS
METHODS
– Modularity with methods. Break complex code into smaller tasks and organize it
using methods.
An object’s behavior refers to what the object can do (or what can be done to it). A
method is simply a named group of statements.
– main is an example of a method
Example
Consider the following code which asks the user to enter two numbers
and print out the average.
// method body
}
6 Methods Declaration Components
1. Modifiers- such as public, private
2. The return type — the data type of the value returned by the
method, or void if the method does not return a value.
3. The method name — the rules for field names apply to method
names as well, but the convention is a little different.
4. The parameter list in parenthesis - a comma-delimited list of
input parameters, preceded by their data types, enclosed by
parentheses, ( ). If there are no parameters, you must use empty
parentheses.
6 Methods Declaration Components
message2();
public static void message2() {
} System.out.println("This is message2.");
System.out.println("Done with message2.");
Output:
}
} This is message1.
This is message2.
Done with message2.
...
}
Method Signature
A method signature for a method consists of the method name and the ordered, possibly empty,
list of parameter types.
public void name(parameters){
statements;
}
Examples:
public static void method1(){
… void: no value is no parameters
} returned when
method ends.
public static void method2(int x, double y){
…
}
The parameters in the method header are formal parameters.
Static Example
When calling a method with parameters, values provided in the parameter list
need to correspond to the order and type in the method signature.
public class MyProgram{
public static void main(String[] args){
mystery1(3, 4); // error, incompatible types!
mystery1(); // missing actual parameters
mystery1(3); // missing actual parameters
mystery1(3, true); // correct
mystery2(3.2, 3.0); // error, incompatible types!
double a = 2.5;
int b = 5;
mystery2(double a, int b); // error, no type in actual parameters
mystery2(a, b); // correct
}
public static void mystery1(int x, boolean y){
…
}
public static void mystery2(double x, int z){
…
}
}
Method Returns
Methods in Java can have return types. Such non-void methods return values
back that can be used by the program. A method can use the keyword “return” to
return a value.