How to Java programming- Methods.
A Java method is a collection of statements that are grouped together to perform an operation. Each method has its own name. The name is encountered in a program, the execution of the program branches to the body of that method. Once the method is finished, execution returns to the area of the program code, and the program continues on to the next line of code. This guide explains you Java methods.
Methods have two main advantages, Code Reusability, and Code Optimization.
There are two basic types of methods: Built-in: Built-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0). And User-defined.
1 2 3 4 5 6 7 |
modifier returnType nameOfMethod (Parameter List) { // method body } |
Modifier: It defines the access type of the method and it is optional to use.
returnType : Method may return a value.
NameOfMethod: This is the method name. The method signature consists of the method name and the parameter list.
Parameter List: The list of parameters, it is the type, order, and a number of parameters of a method. These are optional, the method may contain zero parameters.
method body: The method body defines what the method does with the statements.
There is two type of methods
1. Methods without parameters.
2.Methods with parameters.
1.Methods without Parameters.
The process of method calling is simple. Once the program invokes a method, the program control gets transferred to the called method. The method then returns control to the caller in two conditions, when the return statement is executed and when it reaches the method ending closing brace.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package FirstPackage; public class MyFirstClass{ public static void main(String[] args){ //Method called here MyFirstMethod(); } //Method public static void MyFirstMethod(){ System.out.println("Hello World"); } } |
1 2 3 4 5 |
Hellow World |
The void keyword allows us to create methods which do not return a value.
2.Methods with parameters.
On method calling process, you can pass arguments. These should be in the same order as their respective parameters in the method specification. The parameters are value or reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package FirstPackage; public class MyFirstClass{ public static void main(String[] args){ //Method with parameter example int a = 15; int b = 10; int c = FindMinimum(a, b); System.out.println("Minimum value is" + c); } //Method public static void MyFirstMethod(int n1, int n2){ int min; if(n1 > n2) min = n2; else min = n1; return min; } } |
1 2 3 4 5 |
Minimum value is 10 |