Sams Teach Yourself C in 21 Days

(singke) #1
ThemethodNameis the method’s name, which you’ll use to call it. It is constructed using
the rules for Java identifiers that were presented on Bonus Day 4.
A method can take any number of arguments. For each argument, the method declaration
includes the type of the argument and the argument identifier. For example, here is a dec-
laration for a method that takes two type intarguments and returns a type long:
public long SomeMethod (int arg1, int arg2)
{
}
If a method takes no arguments, use an empty set of parentheses after the method name.
When you call a method, the arguments passed must match the number and type of argu-
ments in the method definition.
To return a value from a method, use the returnstatement inside the method as follows:
return expression;
Expressionis any Java expression that evaluates to a value of the same type as the
method’s declared return type. When execution reaches a returnstatement the expres-
sion is evaluated, and the method terminates. A method can have more than one return
statement in it, but only the first one that execution reaches has any effect.

728 Bonus Day 5

Some methods do not return a value to the calling program. To create such
a method, use voidas the return type in the method definition. Then use
return, by itself, to terminate the method. Lacking a returnstatement, a
typevoidmethod terminates when execution reaches the closing brace.

Note


A Method Demonstration ..............................................................................


The following program demonstrates a class with methods. In fact, this class has nothing
but methods, lacking any properties! The definition of the class ClassWithMethodsis
shown in Listing B5.3, and the sample program that uses this class, MethodsDemo, is
shown in Listing B5.4.

LISTINGB5.3 Source code for ClassWithMethods.java
1: import java.lang.String;
2:
3: public class ClassWithMethods {
4:

40 448201x-Bonus5 8/13/02 11:23 AM Page 728

Free download pdf