If it makes sense for a method to accept parameters
(input), there are times when it needs to return a value to the code that
invoked it (output). Again, here the
notion of output is related to the data flow out of a method, not data being
displayed to the screen. A method that
does not return any value is said to return void, which is a keyword in Java.
We’ve seen this keyword in the main method implementation: public static void main(String
[] args). In fact, we’ve been actually using methods
with return values. Remember the Scanner class, which we used to obtain input from the user. To create a Scanner object, we
have the statement: Scanner
input = new Scanner(System.in); Once we’ve
created the Scanner object, we can use various methods to read values of
different types. The one method we’ve
seen is nextInt, which accepts no arguments, but returns
the integer value read from the keyboard.
To store the value read, we use the assignment operator as follows: int num = input.nextInt(); In this
case, the nextInt method retrieves the
keyboard input and returns it as an integer value, which we store in the
variable num. Another
method defined in the Scanner class allows us to read a double value from the
keyboard. A Java statement to invoke
the method would be: double
x = input.nextDouble(); Just as we need to know the number and types of
the parameters for a method, we also need to know the type of the return
value in order for us to invoke it properly. That information is available to us in
the method header. In essence, we need
to look at how we go about creating methods, not just how to invoke
them. We’ll start with implementing
methods with no parameters and then move to ones with parameters and a return
value. It may at times make sense not to store the
value returned from a method. Here’s a
code segment that first creates a 50x100 Board object and then invokes the
method getCols to obtain the number of
columns. The value returned is
displayed without storing it in a separate variable. Board b
= new Board(50, 100); System.out.print(“Number of columns: “ + b.getCols()); |