Methods
Methods are named code blocks. They:
- are defined inside a class definition.
- can have arguments and return value.
- They can return
void.
- They can return
- correspond to functions or procedures in other languages.
Defining Methods
modifiers returnType methodName (parameters){
// method body code here
}
modifiersdetermine how the method can be accessed.returnTypeis the type of the returned value.methodNamean identifier.-
parametersa (comma-separated) list of arguments, each given as a type and an identifier.Order matters!
// method bodythe code block that defines the method’s behaviour.
Example
public class MaximumDemo {
public static int maximum(int a, int b) {
if(a>= b)
return a;
else
return b;
}
}
publicandstaticare modifiers.intis the return value.maximumis the identifier.aandbare two arguments of typeint.
Signatures
The modifiers, spelling of the identifier, types and ordering of the parameters together form the signature of the method.
A method is uniquely identified by it’s signature.
The following all have different signatures:
public static int max (int a, int b) {}
public static int maX (int a, int b) {}
public static int max (int a, double b) {}
public static int max (double b, int a) {}
public int max (int a, int b) {}
This is the same as the first above:
public static int max(int b, int a) {}
This is because the identifier of the parameter doesn’t change the signature.
main
The main method is a method like any other, except that the interpreter will look it up and call it when it starts.
We can access it’s command-line parameters via args:
public class Hello {
public static void main(String[] args){
System.out.print("Hello " + args[0] + "!");
}
}
This will produce the following when run:
$ java Hello Ben Weston
Hello Ben!
As the second argument is not used, it is not printed.