When we write code, we frequently need a way to do more than just show text on a screen.
We need it to determine a value and give it to us so we can use it elsewhere. This is when you need to know what Java Return Values are.
In this article, we will see the syntax, look at some real-world examples, and compare them to void methods to help you develop code that is cleaner and more professional.
What Are Java Return Values?
In Java, every method has a return type. This type tells the compiler what kind of data the method returns when it finishes.
Use the word "void" if you don't want the method to return anything. You must specify the data type you want to return, though, like an int, float, double, or even a complex object.
The Return Keyword
The return keyword is the primary way to exit a method and return a value to the code that called it.
Once the program executes a return statement, the method stops immediately, and no further code inside that method is executed.
Java Return Values Syntax
You need to follow a certain structure when declaring a method in order to use Return Values. This is the usual way to break it down:
- Access Modifier: Indicates who can see the method (e.g., public or private).
- Return Type: The type of data returned (for example, int or String).
- Method Name: The name of the method.
- Return Statement: The line inside the method body that starts with the term "return."
Simple Syntax Example:
Java
public int methodName() {
return 5; // Returns an integer value
}
Another Basic Example for Beginners:
public class Test {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3)); // Output: 8
}
}
In this example, the method directly returns a value, which is printed without storing it in a variable.
Java Return Values vs Void Methods
One of the most common things that new programmers get confused about is whether to use a return value or void.
- Void Methods do something, like displaying a message or changing a global variable, but they don't provide you with a result that you can save in a variable.
- Methods with return values are like machines that take in something and return something. You can save the result, change it, or send it to another method.
| Feature |
Void Method |
Return Value Method |
| Keyword Used |
void |
int, double, String, etc. |
| Output Capability |
Does not return data |
Returns specific data types |
| Storage |
Cannot be assigned to a variable |
Can be stored in a variable |
| Control Flow |
Ends when code finishes |
Ends as soon as 'return' is hit |
| Use Case |
Printing, Logging, Setting values |
Calculations, Data processing |
Java Return Values Data Types
Java is a statically typed language, which means you must be very specific about the data type you intend to return. You cannot return a String if your method signature says int.
Primitive Types
Most example scenarios involve primitive types:
- int: For whole numbers.
- double/float: For decimal values.
- boolean: For true/false logic.
Reference Types
You can also return complex types, such as:
- String: For text.
- Arrays: To return multiple values of the same type.
- Objects: To return an instance of a class.
Java Return Values Program
Let’s look at a practical program to see how these concepts work in a real-world scenario. Suppose we want to create a method that calculates the sum of two numbers and then uses that sum for further math.
Java
public class Calculator {
// Method with an int return type
static int addNumbers(int x, int y) {
return x + y;
}
public static void main(String[] args) {
// Storing the return value in a variable
int result = addNumbers(10, 20);
// Using the stored value
System.out.println("The total sum is: " + result);
// We can even use the return value directly in a calculation
int finalCalculation = result * 2;
System.out.println("Double the sum: " + finalCalculation);
}
}
In this example, Java Return Values in methods allow the main method to "capture" the result of addNumbers and perform extra steps with it.
Using Return Values in Different Ways:
// Direct usage
System.out.println(addNumbers(5, 3));
// Storing in a variable (recommended for reuse)
int sum = addNumbers(5, 3);
System.out.println(sum);
Storing return values in variables makes your code more reusable and easier to read, especially in larger programs.
Using Return Values Inside a Loop:
for (int i = 1; i <= 5; i++) {
System.out.println(addNumbers(i, i));
}
This shows how a method can be reused multiple times, making your code efficient and modular.
How to Use Java Return Values in Different Ways
A method returns one value, but that value can be an object containing multiple values. You can use logic to determine which value gets returned. This is common in conditional statements.
Using Return with If-Else
You can have multiple return statements within a method, provided they are inside different branches of logic. However, only one will ever execute.
Java
static String checkAge(int age) {
if (age >= 18) {
return "Access Granted";
} else {
return "Access Denied";
}
}
Can we have Java Return Values multiple results?
Strictly speaking, a method cannot return two separate integers like return x, y;. To achieve this, you must wrap the values in:
- An Array: return new int[]{val1, val2};
- A Collection: Using a List or Map.
- An Object: Creating a custom class to hold multiple fields.
Common Mistakes in Java Return Values
- If you write code right after a return statement in the same block, you will get an "unreachable code" problem.
- When the method header says an int but you try to return a double, the code won't compile unless you cast it.
- If a method has a return type other than void, every potential execution route, including all if/else branches, must finish with a return statement.
Why Java Return Values Are Important in DSA
When you progress to Data Structures and Algorithms, Return Values become your best friend. For example, recursive algorithms depend on methods that return results to the "call stack."
Being able to transmit results between function calls is what makes complicated reasoning possible. For example, you can find a node in a binary tree or figure out a Fibonacci sequence.
You may make your code modular by learning how to use Return Values. You don't write one big piece of code.
Instead, you make small, reusable tools that communicate via inputs (parameters) and outputs (return values).
Java Return Values Short Summary
- The return keyword sends data back and terminates method execution.
- The Return Type in the method header must match the data being returned.
- Return Values vs void is the choice between providing data or simply performing an action.
- To return multiple pieces of data, use arrays or objects.
- Using return values is essential for writing clean, testable, and modular code.
Also Read :