Return values let a method send back a result after it finishes. This helps you reuse results in your program.
0
0
Return values in Java
Introduction
When you want a method to calculate and give back a number, like adding two numbers.
When you need to get a true or false answer from a method, like checking if a user is logged in.
When you want to get a text message or data from a method, like getting a user's name.
When you want to break a big task into smaller parts that return results to use later.
Syntax
Java
returnType methodName(parameters) {
// code
return value;
}The returnType is the type of value the method sends back, like int or String.
The return keyword sends the value back and ends the method.
Examples
line_end_arrow_notchThis method adds two numbers and returns the sum as an
int.Java
int add(int a, int b) { return a + b; }
line_end_arrow_notchThis method checks if a number is even and returns
true or false.Java
boolean isEven(int number) { return number % 2 == 0; }
line_end_arrow_notchThis method returns a greeting message using the given name.
Java
String greet(String name) { return "Hello, " + name + "!"; }
Sample Program
This program defines a method multiply that returns the product of two numbers. The main method calls it and prints the result.
Java
public class ReturnExample { public static int multiply(int x, int y) { return x * y; } public static void main(String[] args) { int result = multiply(4, 5); System.out.println("4 times 5 is " + result); } }
OutputSuccess
Important Notes
line_end_arrow_notch
Every method with a return type other than void must return a value of that type.
line_end_arrow_notch
Once return runs, the method stops immediately.
line_end_arrow_notch
Methods with void do not return a value and cannot use return with a value.
Summary
Return values let methods send back results to use elsewhere.
Use the return keyword followed by the value to send it back.
The method's return type must match the type of the returned value.
