Return statement in java with example

Return statement in used to explicitly return from a method. Return causes program control to transfer back to the caller of the method.

The return statement immediately terminates the method in which it is executed.

Syntax:-

return;

Example:-

Program to find sum of 2 number

import java.util.Scanner;

class group{
public static void main(String arng[]){
Scanner data = new Scanner(System.in);
int num1, num2;
System.out.println("Enter 1st number");
num1 = data.nextInt();
System.out.println("Enter 2nd number");
num2 = data.nextInt();

total(num1,num2);

}

public static void total(int numx, int numy){
int sum=0;
sum=numx+numy;
if(sum==0)
return;
System.out.println("Sum of 2 number:"+sum);

}
}

Here total method is terminated when sum is zero.

if(sum=0) is necessary in above example because java compiler shows error "unreachable code" to avoid this error i used if condition to demonstration return statement.


Previous Code:-
Goto statement(labeled break)

List Code:-
Java codes

Next Code:-
Arrays

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top