How to Call or Invoke a User-defined Method?

Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method.


\begin{lstlisting}
import java.util.Scanner;
public class EvenOdd {
public st...
...m=scan.nextInt();
//method calling
findEvenOdd(num);
}
}
\end{lstlisting}

In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the method and gives the output accordingly. Let's combine both snippets of codes in a single program and execute it.


\begin{lstlisting}
import java.util.Scanner;
public class EvenOdd {
public st...
... even'');
else
System.out.println(num+'' is odd'');
}
}
\end{lstlisting}

Output 1:


\begin{lstlisting}
Enter the number: 12
12 is even
\end{lstlisting}

Output 2:


\begin{lstlisting}
Enter the number: 99
99 is odd
\end{lstlisting}

Let's see another program that return a value to the calling method. In the following program, we have defined a method named add() that sum up the two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the sum.


\begin{lstlisting}
public class Addition
{
public static void main(String[] ar...
...ters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
The sum of a and b is= 24
\end{lstlisting}