Return Statement Example in Java
On this page (10sections)
Introduction
Return Statement is a classic Java console program that demonstrates the concept with complete source code and sample output. break, continue and return alter the normal flow inside loops and methods.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
The return statement returns value to the caller. Any time the return statement is called, the process is executed and the value is transferred to the caller.
Syntax
return;
(or)
return value;
Return Statement Example Program
import java.util.Scanner;
class ReturnStatementExample{
public static void main(String[] args){
System.out.println("Jump Statement Example");
System.out.println("Enter 2 numbers for adding");
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int additionResult = additionMethod(num1,num2);
System.out.println("Addition Result is : "+additionResult);
System.out.println("Enter 2 numbers for subtracting");
int num3 = scanner.nextInt();
int num4 = scanner.nextInt();
int subtractionResult = subtractionMethod(num3,num4);
System.out.println("Subtraction Result is : "+subtractionResult);
}
static int additionMethod(int num1, int num2){
int result = num1+num2;
return result; //returns the result to the caller
}
static int subtractionMethod(int num1, int num2){
int result = num1-num2;
return result; //returns the result to the caller
}
}
Sample Output
Jump Statement Example
Enter 2 numbers for adding
40
50
Addition Result is : 90
Enter 2 numbers for subtracting
60
40
Subtraction Result is : 20
When to use
Use this return statement example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
int num1 = scanner.nextInt();updates a variable used in the calculation or output. -
int num2 = scanner.nextInt();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.