A method is like a function in java that makes your code look clear, concise, readable and reusable. You can say it is a collection of statements, instructions or code designed to perform some specific functions. Methods may or may not have parameters passed to them and have their own return type.
package Lesson1;
public class Method {
public static void main(String[] args) {
addition(2,3);
addition(5,6);
multiplication(4,5);
}
public static void addition(int a, int b) {
System.out.println(a+b);
}
public static void multiplication(int a, int b) {
System.out.println(a*b);
}
}
This is the sample output of the above code:
This is how code would've looked if we hadn't used the method.
public class WithoutMethod {
public static void main(String[] args) {
int a=2;
int b=3;
System.out.println(a+b);
int c=5;
int d=6;
System.out.println(c+d);
int e=4;
int f=5;
System.out.println(e*f);
}
}
What if we have to print let's say thousands of this statement, then instead of typing such long codes, methods come to our aid by making our code readable and reusable.