Java Reference
In-Depth Information
Note As mentioned earlier in this chapter, the Java community frowns on the use of labels, because they
dislike the use of goto -like idioms, and jumping to a label comes close to being a goto instruction. The designers
of Java intentionally did not include a goto instruction, and the community has embraced the no- goto idea to the
extent of frowning on labels as well. The accepted view is that if your code has to jump around, you've done a poor
job designing your code. I concur, because I've never yet found a use for break or continue statements with
labels, other than in writing examples to show how they work.
Let's redo that bit of code to show how it works without a label and thus fits the best practices of the
Java community (see Listing 5-20).
Listing 5-20. Removing a label
String[] detectives = {"Sam Spade", "Sherlock Holmes", "Charlie Chan"};
int charactersBeforeSpaces = 0;
for (String str : detectives) {
char[] strChars = str.toCharArray();
for (char ch : strChars) {
if (ch == ' ') {
break;
}
charactersBeforeSpaces++;
}
}
System.out.println(charactersBeforeSpaces);
As you can see, removing the label and replacing the continue statement with a break statement
produces the same result and is simpler to follow. Labels are appropriate in some rare cases, but you'll
probably write Java code for a long time before you find such a case. (I've been writing Java code since
1995, and we've yet to need a label.) In the meantime, try to structure your code to avoid jumping
around beyond the use of label-free break and continue statements. Instead, structure your code so that
your logic catches every possible case. That way, you won't need to jump anywhere.
The return Statement
The final branching instruction is the return statement, which has two forms. If a method returns
nothing (that is, its return type is void ), the return statement has no arguments. If a method returns a
value or object (that is, the return type is not void ), the return statement takes one argument (the value
or object being returned). Return statements stop any further processing within the method and return
processing to the code that called the method. Let's consider an example of a method that returns a
string (see Listing 5-21).
Search WWH ::




Custom Search