3.3. Create methods with arguments and return values

[6.1] Create methods with arguments and return values; including overloaded methods

In this section, you’ll work with the definitions of methods, which may or may not accept input parameters and may or may not return any values.

A method is a group of statements identified with a name. Methods are used to define the behavior of an object. A method can perform different operations, as shown in figure 3.13.

Figure 3.13. Different types of methods

  1. The method setModel can access and modify the state of a Phone instance.
  2. The method printVal uses only the method parameter passed to it.
  3. The method todaysDate initializes a java.util.Date instance and returns its String presentation.

In the following subsections, you’ll learn about the components of a method:

  • Return type
  • Method parameters
  • return statement
  • Access modifiers (covered in chapter 1)
  • Nonaccess modifiers (covered in chapter 1)

Figure 3.14 shows the code of a method accepting method parameters and defining a return type and a return statement.

Let’s get started with a discussion of the return type of a method.

Figure 3.14. An example of a method that accepts method parameters and defines a return type and a return statement

3.3.1. Return type of a method

The return type of a method states the type of value that a method will return. A method may or may not return a value. One that doesn’t return a value has a return type of void. A method can return a primitive value or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, a class, or an interface.

In the following code, the method setWeight doesn’t return any value, and the method getWeight returns a value:

If a method doesn’t return a value, you can’t assign the result of that method to a variable. What do you think is the output of the following class TestMethods, which uses the preceding class Phone?

The preceding code won’t compile because the method setWeight doesn’t return a value. Its return type is void. Because the method setWeight doesn’t return a value, there’s nothing to be assigned to the variable newWeight, so the code fails to compile.

If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable. Look at the following code:

In the preceding example, the value returned by the method getWeight isn’t assigned to any variable, which isn’t an issue for the Java compiler. The compiler will happily compile the code for you.

Exam Tip

You can optionally assign the value returned by a method to a variable. If you don’t assign the returned value from a method, it’s neither a compilation error nor a runtime exception.

The value that you return from a method must be assignable to the variable to which it’s being assigned. For instance, the return value of getWeight() in Phone is double. You can assign the return value of getWeight() to a variable of type double but not to a variable of type int (without an explicit cast). Here’s the code:

In the preceding code, will compile successfully because the return type of the method getWeight is double and the type of the variable newWeight is also double. But won’t compile because the double value returned from method getWeight can’t be assigned to variable newWeight2, which is of type int. You can make it happen by an explicit cast:

But an explicit cast won’t work with data types that aren’t compatible:

We’ve discussed how to transfer a value out from a method. To transfer a value into a method, you can use method arguments.

3.3.2. Method parameters

Method parameters are the variables that appear in the definition of a method and specify the type and number of values that a method can accept. In figure 3.15, the variables phNum and msg are the method parameters.

Figure 3.15. An example of a method that accepts method parameters and defines a return type and a return statement

You can pass multiple values to a method as input. Theoretically, no limit exists on the number of method parameters that can be defined by a method, but practically it’s not a good idea to define more than three method parameters. It’s cumbersome to use a method with too many method parameters because you have to cross-check their types and purposes multiple times to ensure that you’re passing the right values at the right positions.

Note

Although the terms method parameters and method arguments are not the same, you may have noticed that many programmers use them interchangeably. Method parameters are the variables that appear in the definition of a method. Method arguments are the actual values that are passed to a method while executing it. In figure 3.15, the variables phNum and msg are method parameters. If you execute this method as sendMsg("123456", "Hello"), then the String values "123456" and "Hello" are method arguments. As you know, you can pass literal values or variables to a method. Thus, method arguments can be literal values or variables.

A method may accept zero or multiple method arguments. The following example accepts two int values and returns their average as a double value:

The following example shows a method that doesn’t accept any method parameters:

void printHello() {
    System.out.println("Hello");
}

If a method doesn’t accept any parameters, the parentheses that follow the name of the method are empty. Because the keyword void is used to specify that a method doesn’t return a value, you may think it’s correct to use the keyword void to specify that a method doesn’t accept any method parameters, but this is incorrect. The following is an invalid definition of a method that accepts no parameters:

You can define a parameter that can accept variable arguments (varargs) in your methods. Following is an example of the class Employee, which defines a method days-OffWork that accepts variable arguments:

class Employee {
    public int daysOffWork(int... days) {
        int daysOff = 0;
        for (int i = 0; i < days.length; i++)
            daysOff += days[i];
        return daysOff;
    }
}

The ellipsis (...) that follows the data type indicates that the method parameter days may be passed an array or multiple comma-separated values. Reexamine the preceding code example and note the usage of the variable days in the method daysOffWork—it works like an array. When you define a variable-length argument for a method, Java creates an array behind the scenes to implement it.

You can define only one variable argument in a parameter list, and it must be the last variable in the parameter list. If you don’t comply with these two rules, your code won’t compile:

If your method defines multiple method parameters, the variable that accepts variable arguments must be the last one in the parameter list:

Exam Tip

In the OCA exam, you may be questioned on the valid return types for a method that doesn’t accept any method parameters. Note that there are no valid or invalid combinations of the number and type of method parameters that can be passed to a method and the value that it can return. They’re independent of each other.

You can pass any type and number of parameters to a method, including primitives, objects of a class, or objects referenced by an interface.

Rules to remember

Here are some points to note with respect to defining method parameters:

  • You can define multiple parameters for a method.
  • The method parameter can be a primitive type or object.
  • The method’s parameters are separated by commas.
  • Each method parameter is preceded by the name of its type. Each method parameter must have an explicit type declared with its name. You can’t declare the type once and then list the parameters separated by commas, as you can for variables.

3.3.3. Return statement

A return statement is used to exit from a method, with or without a value. For methods that define a return type, the return statement must be immediately followed by a return value. For methods that don’t return a value, the return statement can be used without a return value to exit a method. Figure 3.16 illustrates the use of a return statement.

Figure 3.16. An example of a method that accepts method parameters and defines a return type and a return statement

In this example, we’ll revisit the previous example of method calcAverage, which returns a value of type double, using a return statement:

The methods that don’t return a value (the return type is void) aren’t required to define a return statement:

But you can use the return statement in a method even if it doesn’t return a value. Usually this statement is used to define an early exit from a method:

Also, the return statement must be the last statement to execute in a method, if present. The return statement transfers control out of the method, which means that there’s no point in defining any code after it. The compiler will fail to compile such code:

Note that there’s a difference in the return statement being the last statement in a method and being the last statement to execute in a method. The return statement need not be the last statement in a method, but it must be the last statement to execute in a method:

void setWeight(double val) {
    if (val < 0)
        return;
    else
        weight = val;
}

In the preceding example, the return statement isn’t the last statement in this method. But it’s the last statement to execute for method parameter values of less than zero.

Rules to remember when defining a return statement

Here are some items to note when defining a return statement:

  • For a method that returns a value, the return statement must be followed immediately by a value.
  • For a method that doesn’t return a value (return type is void), the return statement must not be followed by a return value.
  • If the compiler determines that a return statement isn’t the last statement to execute in a method, the method will fail to compile.

Do you think we’ve covered all the rules for defining a method? Not yet! Do you think you can define multiple methods in a class with the same name? You can, but you need to be aware of some additional rules, which are discussed in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.133