Recommended Free Tools
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
The answer to “Java method return multiple values” is no for independent return slots: Java methods declare one return type and produce one value per call. To return several related results, wrap them in one object—usually a record for a small, fixed data structure, or a class when you need more customization, compatibility, or behavior.
Key takeaways
- Java has no syntax for returning several independent values from one method invocation.
- A record is usually the clearest Java 16+ solution for a small, fixed group of related results.
- A normal class remains useful for Java 8–15 compatibility, mutable state, inheritance requirements, and complex behavior.
- Arrays and collections are appropriate when the result is naturally homogeneous or variable-length, not merely because they avoid declaring a result type.
Optional<Result>represents an absent aggregate result, while a record containing severalOptionalcomponents represents independently optional fields.
Can a Java method return multiple values?
A Java method can return only one value of one declared return type per invocation. Java does not provide a syntax such as int, String getResult() for multiple independent return slots.
That single value can be an object containing multiple components. A record, class, array, list, map, Optional, or stream is still one returned value; the container determines how the related data is represented.
record Result(int value, String message) {}
static Result compute() {
return new Result(42, "success");
}
The method returns one Result object. The object contains an integer and a string, and the caller can read both components:
Popular on Amazon
Result result = compute();
int value = result.value();
String message = result.message();
The declared return type must be compatible with the expression in the return statement under Java’s normal return-type and assignment-conversion rules. A method declared void returns no value.
Do multiple return statements return multiple values?
Multiple return statements provide multiple possible exit paths, not multiple values returned at the same time. Each invocation completes with one value or with an exception.
static int absoluteValue(int value) {
if (value < 0) {
return -value;
}
return value;
}
The method has two return statements, but a particular call returns only one int. A method cannot use one execution path to return both an integer and a string unless those values are placed inside a common return type.
What is the best way to return multiple values in modern Java?
For a small, fixed group of related, data-oriented results, return a named record. Standard record classes are available in Java SE 16 and later; records were finalized in Java SE 16, as described in the official Java records overview.
record DivisionResult(int quotient, int remainder) {}
static DivisionResult divide(int dividend, int divisor) {
if (divisor == 0) {
throw new IllegalArgumentException("divisor must not be zero");
}
return new DivisionResult(
dividend / divisor,
dividend % divisor
);
}
The caller receives one DivisionResult and accesses the two named components:
DivisionResult result = divide(17, 5);
System.out.println(result.quotient()); // 3
System.out.println(result.remainder()); // 2
Record accessors use the component name followed by parentheses. The declaration above creates quotient() and remainder(); Java does not automatically create JavaBean-style methods named getQuotient() or getRemainder().
What does a Java record provide automatically?
A declaration such as record DivisionResult(int quotient, int remainder) {} is a compact declaration of a data carrier. Java supplies a canonical constructor accepting both components, component accessors, value-based equals, hashCode, and toString. Record components are represented by private final fields.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →The Java language documentation for records defines the generated members and record syntax. The java.lang.Record API documentation describes the guarantees and restrictions of record classes.
How can a record validate multiple returned values?
A record can use a compact constructor to validate its components before an instance is created. Centralizing validation prevents every caller from having to repeat the same invariant checks.
record DateRange(LocalDate start, LocalDate end) {
DateRange {
Objects.requireNonNull(start);
Objects.requireNonNull(end);
if (end.isBefore(start)) {
throw new IllegalArgumentException(
"end must not be before start"
);
}
}
}
A percentage result can apply the same pattern:
record Percentage(double value) {
Percentage {
if (value < 0 || value > 100) {
throw new IllegalArgumentException(
"value must be between 0 and 100"
);
}
}
}
Are Java records deeply immutable?
No. Records are shallowly immutable: the component references cannot be reassigned through the record, but referenced objects can still be mutable. A record containing a mutable list does not automatically make that list immutable.
record Report(List<String> warnings) {
Report {
warnings = List.copyOf(warnings);
}
}
List.copyOf creates an unmodifiable copy for the record component. Use a defensive copy or another appropriate boundary-protection strategy when callers must not mutate the returned data.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Also popular on Amazon
When should you use a class instead of a record?
Use an ordinary class when the result needs mutable state, inheritance-related design, framework-specific construction, more control over field exposure, complex lifecycle behavior, or compatibility with Java versions before 16.
An immutable class can provide the same basic shape as the record example:
public final class DivisionResult {
private final int quotient;
private final int remainder;
public DivisionResult(int quotient, int remainder) {
this.quotient = quotient;
this.remainder = remainder;
}
public int quotient() {
return quotient;
}
public int remainder() {
return remainder;
}
}
For Java 8 through Java 15, use a normal class because standard record syntax is not available. A class can also be the better long-term public API when the returned object has domain behavior rather than serving primarily as transparent data.
Records are implicitly final and cannot declare ordinary instance fields beyond their components. Records can still declare methods, static fields, static methods, nested types, and validation logic. Choose a class when those record restrictions conflict with the design.
How do arrays, lists, maps, and tuples compare?
The right alternative depends on whether the returned data has fixed fields, a variable length, homogeneous values, or dynamic keys. A container should reflect the data’s shape rather than merely conceal the absence of multiple return slots.
| Requirement | Recommended type | Why | Main caution |
|---|---|---|---|
| Two or more fixed, related values | Named record | Named, type-safe components with little boilerplate | Requires Java 16 or later |
| Domain object with behavior or complex invariants | Ordinary class | Provides greater control over construction, state, and methods | More code to maintain |
| Variable-length homogeneous sequence | List<T>, array, or Stream<T> |
Models a sequence naturally | Does not name fixed positions |
| Fixed homogeneous numeric output in private algorithmic code | Primitive array | Compact representation for same-typed values | Positions such as [0] and [1] are easy to misunderstand |
| Dynamic key/value data | Map<K,V> |
Models lookup by key | Keys and value types are less strongly enforced for loosely typed maps |
| One result that may be absent | Optional<T> |
Clearly represents presence or absence | Optional is not multiple return slots |
| Generic local pair with obvious semantics | Existing pair or tuple type | Reduces local boilerplate | first and second may hide meaning |
When is an array appropriate?
An array is reasonable when the values are homogeneous, the positional convention is obvious, and the result is local to algorithmic code.
static int[] minAndMax(int[] values) {
int min = values[0];
int max = values[0];
for (int value : values) {
min = Math.min(min, value);
max = Math.max(max, value);
}
return new int[] { min, max };
}
int[] result = minAndMax(values);
int min = result[0];
int max = result[1];
The array is concise and preserves primitive component types, but result[0] does not explain its meaning. The returned array is also mutable, and changing the number or order of elements can break callers. For a meaningful public API, record Bounds(int minimum, int maximum) {} communicates the contract more clearly.
When is a list appropriate?
Return a list when the number of results varies and the values form an ordered sequence.
Free tools Windows power users keep installed
One-click scans. No signup required.
static List<String> findMatchingNames(String query) {
// The number of results is not fixed.
return List.of("Alice", "Alina");
}
A list is usually a poor substitute for a fixed result with differently typed fields:
List<Object> result = List.of("Alice", 42, true);
String name = (String) result.get(0);
int count = (Integer) result.get(1);
This design loses the names and compile-time meaning of the fields. A record such as record UserProfile(String name, int age) {} gives callers typed accessors instead of casts and positional assumptions.
When is a map appropriate?
A map is appropriate when the result is genuinely key-oriented or dynamically shaped, such as properties whose names are not known when the method is compiled.
Also popular on Amazon
static Map<String, Object> getProperties() {
return Map.of(
"name", "Alice",
"age", 42
);
}
A fixed method contract generally should not use Map<String, Object> instead of a result type. Map keys can be misspelled, expected keys are not compiler-enforced, values require casts, and the API shape is less discoverable. Use a named record for stable fields.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Are pair and tuple types a good choice?
A pair or tuple can be useful for a local implementation detail when the meaning of each position is obvious and the project already has an established tuple type.
record Pair<A, B>(A first, B second) {}
Pair<String, Integer> result = new Pair<>("Alice", 42);
Pair<String, Integer> does not tell readers whether the values mean a name and age, text and length, or a key and value. For a stable domain contract, use a meaningful type instead:
record UserProfile(String name, int age) {}
The issue is not that tuples are inherently invalid. The issue is that generic positional names often communicate less than a domain-specific result type.
How should Optional represent multiple results?
Optional<T> represents one possibly absent result; it does not provide multiple return slots. Wrap the complete aggregate when the entire result may be absent.
record Coordinates(double latitude, double longitude) {}
static Optional<Coordinates> locate(String address) {
// Look up the address.
return Optional.empty();
}
Optional<Coordinates> says that coordinates either exist as a complete pair or do not exist. A result with independently optional fields can model those fields explicitly:
record UserLookup(
Optional<String> displayName,
Optional<String> email
) {}
Use the second design cautiously. If the fields must either all exist or all be absent, Optional<SomeRecord> is usually clearer than a record containing multiple optionals.
Should a method return a stream for multiple values?
A Stream<T> is suitable for a potentially variable sequence that should be processed lazily; it is not a container for several unrelated fixed values.
static Stream<String> matchingNames(List<String> names) {
return names.stream()
.filter(name -> name.startsWith("A"));
}
A stream represents a sequence of values of one element type. A record represents one named product of related components. Choose between them based on the data shape and evaluation model.
How can a lambda return multiple values?
A lambda also has one result type. Return a record or another object from the lambda when the computation produces multiple related pieces of data.
record NameLength(String name, int length) {}
Function<String, NameLength> describe =
name -> new NameLength(name, name.length());
The same rule applies to Function, Callable, Supplier, and other functional interfaces: the function produces one value of its generic result type. The generic result type can itself be a record, class, array, or other aggregate.
Also popular on Amazon
Can mutable arguments simulate output parameters in Java?
Java has no C#-style out parameters, but a method can mutate a caller-provided holder such as an array.
static void calculate(int input, int[] output) {
output[0] = input * 2;
output[1] = input * 3;
}
This approach is generally inferior to returning a result object. The caller must allocate storage, the method’s mutation is less visible in the signature, aliasing can create bugs, and null or incorrect-size arrays add failure modes.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchrecord Multiples(int doubleValue, int tripleValue) {}
static Multiples calculate(int input) {
return new Multiples(input * 2, input * 3);
}
The returned record is easier to compose, test, document, and use correctly.
How do you return a parsed value and metadata?
A named result type is particularly useful when a method returns a primary value together with metadata needed by the caller.
public final class ParseResult {
private final String value;
private final int nextIndex;
public ParseResult(String value, int nextIndex) {
this.value = value;
this.nextIndex = nextIndex;
}
public String value() {
return value;
}
public int nextIndex() {
return nextIndex;
}
}
static ParseResult parseToken(String input, int start) {
int end = input.indexOf(' ', start);
if (end == -1) {
end = input.length();
}
return new ParseResult(
input.substring(start, end),
end
);
}
ParseResult is more descriptive than Pair<String, Integer>: callers can understand that the integer is the next parsing position rather than guessing what the second component means.
How should you choose the return type?
Start by asking whether the result is a fixed group of named fields or a sequence. Then consider the types, API visibility, mutability requirements, and domain meaning.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minute| Question | Choose | Reason |
|---|---|---|
| Are there a few fixed, related fields? | Named record | Each component has a clear name and compile-time type. |
| Does the result need mutable state, inheritance, or custom lifecycle behavior? | Ordinary class | Classes have fewer structural restrictions than records. |
| Is the number of values variable? | List<T>, array, or Stream<T> |
The result is naturally a sequence. |
| Are the values dynamically addressed by keys? | Map<K,V> |
Key lookup is part of the data’s meaning. |
| Can the entire result be absent? | Optional<Result> |
Presence applies to the aggregate as a whole. |
| Are the values genuinely generic and local? | Existing pair or generic tuple | A generic container may avoid unnecessary domain boilerplate. |
| Are the values unrelated? | Reconsider the method design | The method may have too many responsibilities. |
For public APIs, name the result when the fields have stable domain meaning. Document nullability, ordering, units, and mutability. Avoid Object[], List<Object>, and loosely typed maps for stable contracts because those designs shift errors from compile time to runtime.
What common mistakes should you avoid?
Using incompatible return types
The returned expression must be compatible with the declared return type. This does not compile:
static int getValue() {
return "42";
}
Return a compatible integer, change the declared type, or model multiple differently typed fields with a record or class.
Using Object arrays for mixed values
An Object[] can hold mixed values, but callers must remember positions and cast each element.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsstatic Object[] getData() {
return new Object[] { "Alice", 42 };
}
Object[] data = getData();
String name = (String) data[0];
int age = (Integer) data[1];
A record makes the field names and types part of the method contract and allows the compiler to check component access.
Also popular on Amazon
Assuming a record protects mutable components
A record’s final component reference does not recursively freeze a list, map, array, or other mutable object. Copy mutable components when callers must not alter the returned state.
Returning too many fields
If a method returns eight or twelve values, the container may not be the real design problem. Consider splitting responsibilities, nesting related records, omitting derived values, or returning a domain object that represents the operation more directly.
Changing a return type without treating it as an API change
Changing int calculate(...) to return a Calculation record changes the method contract and the callers that compile against it. Treat the change as an API evolution issue rather than a private implementation detail, especially for published libraries.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
What is the final recommendation?
Use a named record for a small, fixed, related group of results when the project targets Java 16 or later. Use a normal class for Java 8–15 or whenever the result needs mutable state, inheritance, custom construction, or more extensive behavior. Use arrays, lists, maps, streams, pairs, and optionals only when their natural data shape matches the result.
The technically precise rule is simple: a Java method returns one value, and that one value can be an object that groups multiple named values.
Frequently Asked Questions
Can a Java method return two integers directly?
No. A Java method cannot declare two independent return slots, but the method can return one record such as record Result(int first, int second) {} containing both integers. A primitive array can also work for private algorithmic code when positional meanings are obvious.
What Java version supports records?
Standard Java record classes are available in Java SE 16 and later. Java 8 through Java 15 code should use an ordinary class or another compatible container instead of record syntax.
Recommended Free Tools
Are record fields immutable in Java?
Record component references are final, so records are shallowly immutable. A referenced list, map, array, or other mutable object can still change unless the record makes a defensive copy or uses an unmodifiable representation.
Should I return a Pair or a named record in Java?
Use a named record when the values have stable domain meanings because component names make the API clearer and type-safe. A pair can be reasonable for a local implementation detail when the meaning of the two positions is obvious and the project already uses that tuple type.
The Bottom Line
Bottom line: Java does not return several independent values from one method call. Return one aggregate value instead—normally a named record for a small fixed result, or a normal class when compatibility and customization matter.

