Multiple return values. A method is called. It returns 3 values—2 ints and a String. In Java we must use a class instance, an array or other collection to return these values.
With an object array, we can return many different types of elements. But the simplest and best solution involves a class. We can return a class with multiple values.
Object array example. Here we introduce a getSizes method that returns an Object array. It can return any number of elements, and these can have any type.
class Dog {
public int weight;
public String name;
}
public class Program {
public static Dog computeDog() {
// Return multiple values in an object instance.
Dog dog = new Dog();
dog.weight = 40;
dog.name = "Spark";
return dog;
}
public static void main(String[] args) {
Dog dog = computeDog();
// Print return values.
int weight = dog.weight;
String name = dog.name;
System.out.println(weight);
System.out.println(name);
}
}40
Spark
For many return values, or a variable number of return values, an ArrayList is effective. Return an ArrayList from your method. A type like Integer (or Object) can be used.
A summary. In Java objects are meant to encapsulate data. So multiple return values are often placed in objects. With methods and logic, we have object-orientation.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 10, 2023 (edit).