A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a program and reuse it in many other program.
Therefore, you don't have to repeatedly write the same code again and again. You just need to define it just once and reuse it in other programs.
The syntax for defining a method is as follows:
modifier returnValueType methodName (list of parameters) {
//method body;
}
// method to find a maximum number between two numbers
public static int findMax(int num1, int num2){
int max;
if (num1 > num2)
max = num1;
else
max = num2;
return max;
}
modifier: public static
returnValueType: int
methodName: findMax
list of parameters: num1, num2
return value: max
formal parameter: num1, num2
A method may return a value.
A method that returns a value is called a value returning method.
A method that does not return a value is called a void method.
A variables defined in the method header are known as formal parameters.
A parameter is like a placeholder.
When a method is invoked, you pass a value of the actual parameters to the formal parameters.
Parameters are optional.
A method body contains a collection of statements that define what the method does.
A return statement using the keyword return is required for a value-returning method to return a result.
The method terminates when a return statement is executed.
In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it.
Example: to invoke the method findMax.
int maxNumber = findMax(4, 5);
this statement will call method findMax, pass the value to formal parameters, get the result, and assign the result of the method to variable maxNumber.
You can also use with print statement, for example:
System.out.println(findMax(4,5));
this statement will print the return value of the method findMax.
The following program shows how to define and invoke the method.
public class MaxNumbers{
public static void main(String[] args){
int i = 5;
int j = 2;
int k = findMax(i,j);
System.out.println("The maximum between " + i + " and " + j + " is " + k);
System.out.println("The maximum between " + 6 + " and " + 16 + " is " + findMax(6,16));
}
public static int findMax(int num1, int num2){
int max;
if (num1 > num2)
max = num1;
else
max = num2;
return max;
}
}
The output will be as the following.
The maximum between 5 and 2 is 5
The maximum between 6 and 16 is 16
void method does not return any value. A call to a void method must be a statement.
public class MaxNumbers{
public static void main(String[] args){
int i = 5;
int j = 2;
findMax(i,j);
findMax(12,23);
}
public static void findMax(int num1, int num2){
int max;
if (num1 > num2)
max = num1;
else
max = num2;
System.out.println("The maximum between " + num1 + " and " + num2 + " is " + max);
}
}
The output will be as the following.
The maximum between 5 and 2 is 5
The maximum between 12 and 23 is 23
When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value.
If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method.
public class SwapNumber{
public static void main(String[] args) {
int num1 = 2;
int num2 = 7;
swap(num1, num2);
}
public static void swap(int n1, int n2) {
System.out.println("Before: " + n1 + " and " + n2);
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("After: " + n1 + " and " + n2);
}
}
The output will be:
Before: 2 and 7
After: 7 and 2
we can pass arrays to methods just like passing primitive type values to methods. For example:
// this method displays the elements in an int array.
public static void printArray(int[] list) {
for (int i=0; i<list.length; i++) {
System.out.print(list[i] + " ");
}
}
so, to invoke this method just write:
printArray(list);
There are important differences between passing the values of variable of primitive data types and passing arrays.
for an argument of a primitive type, the argument's value is passed.
for an argument of an array type, the value of the argument is a reference to an array; this reference value is passed to the method. Semantically, it can be best described as pass-by-sharing i.e, the array in the method is the same as the array being passed. So, if you change the array in the method, you will see the change outside the method.
Example:
public class TestTry{
public static void main(String[] args) {
int numX = 1;
int[] list = new int[10];
readArray(list);
printArray(list);
}
public static void readArray(int[] list) {
for (int i=0; i<list.length; i++) {
list[i] = i*2;
}
}
public static void printArray(int[] list) {
for (int i=0; i<list.length; i++) {
System.out.print(list[i] + " ");
}
}
}
The output will be:
0 2 4 6 8 10 12 14 16 18
We can pass arrays when invoking a method. A method may also return an array. For example, the method shown below returns an array that is the reversal of another array.
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--)
result[j] = list[i];
return result;
}
result is a new array created in method reverse. Elements from array list is copied into array result backwards (the first element of array list is copied into the last cell of array result).
public class TestTry{
public static void main(String[] args) {
int numX = 1;
int[] list = new int[10];
readArray(list);
System.out.println("Original list:");
printArray(list);
System.out.println("After reverse:");
list = reverse(list);
printArray(list);
}
public static void readArray(int[] list) {
for (int i=0; i<list.length; i++) {
list[i] = i*2;
}
}
public static void printArray(int[] list) {
for (int i=0; i<list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--)
result[j] = list[i];
return result;
}
}
The output will be:
Original list:
0 2 4 6 8 10 12 14 16 18
After reverse:
18 16 14 12 10 8 6 4 2 0
A variable defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and assigned a value before it can be used.
A method parameter is a local variable. The scope of a method parameter covers the entire method.
Example:
public static void swap(int n1, int n2) {
System.out.println("Before: " + n1 + " and " + n2);
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("After: " + n1 + " and " + n2);
}
In the above method, n1, n2, and temp are local variables for method swap.
Example:
for (int i=0; i<10; i++) {
System.out.println(i);
}
A variable i was declared in a for loop header. Therefore, the scope for variable i is just in the loop body/block.
Write a program that prompts the user to enter two integers and displays their greatest common divisor. The sample output is as follows:
Enter first integer: 45
Enter second integer: 75
The greatest common divisor for 45 and 75 is 15
The program:
import java.util.Scanner;
public class TestTry{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
int num1 = input.nextInt();
System.out.print("Enter second integer: ");
int num2 = input.nextInt();
System.out.println("The greatest common divisor for " + num1 +
" and " + num2 + " is " + gcd(num1, num2));
}
public static int gcd(int n1, int n2){
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2){
if (n1%k == 0 && n2%k == 0)
gcd = k;
k++;
}
return gcd;
}
}
Write the following method to display an integer in reverse order:
Public static void reverse(int number).
Eg: reverse(1234) will displays 4321
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
int num;
Scanner scan = new Scanner(System.in);
System.out.println("Input an integer:");
num = scan.nextInt();
reverse(num);
}
public static void reverse(int number){
int rev = 0;
while( number != 0 ){
rev = rev * 10;
rev = rev + number%10;
number = number/10;
}
System.out.println("Reverse of entered number is "+rev);
}
}