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
}
Method
A method is a group of code that has a name and can be called using parentheses.
public class Main{
public static void main(String[] args){ Enter a number: 4
// calling it the first time Enter a number: 6
average(); The average is 5.0
// calling it again to repeat the task
average();
}
public static void average(){ Enter a number: 10
Scanner console = new Scanner(System.in); Enter a number: 11
int num1, num2; The average is 10.5
System.out.print("Enter a number: ");
num1 = console.nextInt();
System.out.print("Enter a number: ");
num2 = console.nextInt();
System.out.println("The average is " + (num1 + num2)/2.0);
}}
Static Method Inside Driver Class
The driver class is the class with the main method. Note that the main method is the begin
point of a run of any program.
message2();
public static void message2() {
System.out.println("This is message2.");
message1();
Output:
System.out.println("Done with message2.");
} This is message1. }
This is message2.
This is message1. public static void message1() {
... Done with message2. System.out.println("This is message1.");
} }
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.