Returning multiple values from a method

Strictly speaking you cannot return multiple values from a method call. A method can only return a single primitive value or Object.

Since however, you can return an Object you can always create a new class that contains the values you want to return and simply return a single Object of that class which contains the values needed.

Here we’re trying to get the first and last names of a user with a single call to the User object.

public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";

   /**
    * This isn't really what you want, since the two values
    * are merged together.
    */
   public String getName() {
      return ivFirstName+" "+ivLastName;
   }
}

Here, we use a new class called UserName that can hold the two values in question.

public class UserName {
   protected String ivFirstName, ivLastName;
 
   public UserName(String first, String last) {
      ivFirstName = first;
      ivLastName  = last;
   }
 
   public String getFirstName() {
      return ivFirstName;
   }
 
   public String getLastName() {
      return ivLastName;
   }
}
 
public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";
 
   /**
    * This is returning a single Object, which contains
    * multiple values.
    */
   public UserName getName() {
      return  new UserName(ivFirstName, ivLastName);
   }
}

It’s better in general to just return a single value. There are some rare instances where multiple values need to be returned, but these are the exception, and can be dealt with by the preceeding example.

public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";
 
   /**
    * This is better practice all around.
    */
   public String getFirstName() {
      return ivFirstName;
   }
 
   /**
    * This is better practice all around.
    */
   public String getLastName() {
      return ivLastName;
   }
}