CHAPTER 2 ■ JAVA SYNTAX
Listing 2-10. Methods
// a classic getter method
@Override
public int[] getInts() {
return ints;
}
// a classic setter method
@Override
public void setInts(int[] ints) throws IllegalArgumentException {
if (ints.length == 0){
throw new IllegalArgumentException(EXCEPTION_MESSAGE);
}
this.ints = ints;
}
Let's have a closer look at the “setter” method, starting with the first line (not counting the
comment, which starts with //. We cover comments later in the chapter).
public is the method's access modifier. We cover access modifiers earlier in the chapter.
void is the return type. The return type tells any code that called this method what to expect. All
methods must have a return type. void indicates that the method won't return anything. So, all methods
must have a return type, but not all methods must return something. If we look at the other methods in
the class, we can see that they often do return something.
setInts is the method's name. By convention, method names start with a lowercase letter and have
capital letters wherever a logical word appears. This is sometimes called camel case.
The parentheses contain a list of arguments. In this example, the list is only one argument long.
Each argument has a type and a name. In this case, the type is int[] (the brackets indicate an array), and
the name is ints. The arguments are separated by commas when more than one is present, as in the
following method declaration from the AverageTest class:
private static String buildTestString(int[] values, float average, long time) {
The brace character opens the code block that is the method's body. We cover blocks later in this
chapter.
Methods can also be static. On a method, the static keyword means that only one such method
exists in the system, no matter how many objects of that class might exist. For that reason, a static
method is also known as a class method. Also, the method cannot use any of the class's fields other than
fields that have themselves been declared static (usually constants). Static methods can be a handy way
to provide utility methods for use throughout your code. For example, a method that takes a date and
returns a formatted string might be static, provided it doesn't need to use any of its containing class's
non-static methods. Also, static methods can be slightly more efficient, because they don't access
anything outside the method body.