Good question there.
A method is a collection of statements that are grouped together to perform an operation. It helps you a lot in finding and calculate many tasks without needing of declaring the same variables and other stuffs. For example, you can create your own method for finding the maximum number between a group of numbers, and to output the result at anytime you just write the method name, which let's say it's "max" and find the max. number easily.
There are methods that they are already built in Java, like using Math class and find the double tangent by using this: Math.tan , or you can use the random method. It also may help you in big programs which require you the same operation in many steps, so you use methods in this case.
In general to create a method, you need to follow this syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
To make it simple to you and see the benefit of using methods while you coding, here you are the code for the max.:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
This method takes two parameters which they are here
num1 and
num2
now to call that method, you need to declare a new variable and write as this: int larger = max(30, 40);
The result will be of course: 40
I hope you understand ^_^