Java Reference
In-Depth Information
exits the method. For example, if you want to exit out of the sit method before sitting down, you
can change this method as follows:
void sit() {
if (isSitting)
return; // Exit out method if already sitting
isSitting = true;
}
This will especially come in handy for governing the control flow of your program. This aspect will
be discussed in detail in the next chapter.
Recall that methods can also take one or more arguments. Consider, for example, the following
method declarations:
void giveCookie(Cookie cookie) { /*...*/ }
void chaseDog(Dog dog) { /*...*/ }
void lickPerson(Person person, int nrLicks) { /*...*/ }
void giveNickNames(String[] nickNames) { /*...*/ }
void giveNickNames(String... nickNames) { /*...*/ }
The last example in this listing will look unfamiliar to you, and it uses a construct called varargs
(variable arguments). Basically, the last two methods are equivalent in the sense that the nickNames
variable will be available as an array of strings in the method body, for instance:
void giveNickNames(String... nickNames) {
System.out.println("You have given me "+nickNames.length+" names");
}
The way these two methods are called, however, differs. In the first case ( String[] nickNames ), the
method is called using an array of strings as an argument, as you'd expect:
String[] newNames = new String[] {"Puppers", "Droopy"};
myDog.giveNickNames(newNames);
In the second case, however ( String... nickNames ), you can just supply an arbitrary number of
strings (including none at all), like so:
myDog.giveNickNames("Puppers", "Droopy");
// Or any other amount of strings:
myDog.giveNickNames("Puppers", "Droopy", "Tissues", "Clifford");
myDog.giveNickNames();
Varargs can provide a handy way of avoiding having to pass an array explicitly. However, keep in
mind that the varargs argument (the one with the three dots, ... ) must always be the last method
argument, and only one varargs argument can be defined for a method. With arrays, on the other
hand, you are free to define any number of arguments in any order you want. To illustrate:
method(String... s1) : Allowed
method(String... s1, String s2) : Not allowed
Search WWH ::




Custom Search