Method is a block of code which runs only when it is called or invoked.
Method is used to perform certain behaviors or actions.
Method can accept data which are called parameters.
To create a method, you need the follow things:
1. name
2. return type
3. parameters
4. statements
5. return value
int addOne(int num){ int answer = num +1; return answer; }
Methods must be inside of a class.
class MathClass{ int addOne(int num){ int answer = num +1; return answer; } }
Calling a method
A method can be called multiple times.
class MathClass{ static int addOne(int num){ int answer = num +1; return answer; } public static void main(String[] args) { int answer = addOne(5); System.out.println("answer is "+answer);// 6 } }
Method Parameters
You can pass in however many parameters you would like just separate them by comma.
int add(int num1, int num2, int num3, int num4){ int answer = num1 + num2 + num3 +num4; }
Return values
Our example above indicates that add must return an int. Every method must return either a value or void.
void sayHello(String name){ System.out.println("Hello "+name+"!"); }
sayHello method has a return type of void.