9.6. Concepts SummaryThis chapter covered working with ranges in loops and how to return a value from a method. 9.6.1. Ranges in LoopsTo limit the range of a loop, change the starting value and/or ending value. For example, to create a new sound from just part of an original sound you can change the start and end values for the loop. This was seen in Program 72 (page 296). // copy from start to end from source into target for (int i = start; i <= end; i++, targetIndex++) { value = this.getSampleValueAt(i); target.setSampleValueAt(targetIndex,value); } 9.6.2. Returning a Value from a MethodTo declare a method you specify the visibility for the method, the type of thing it returns, the name of the method, and the parameter list inside parentheses. This is followed by the body of the method which is inside of an open and close curly brace. Methods that do not return any value use the keyword void as the returnType. If the method has a return type other than the keyword void it must contain a return statement in the method that returns a value of that type. Remember that a type is any of the primitive types or the name of a class. visibility returnType name(parameterList) { // statements in method // return a value return valueToReturn; } Here is an example public method declaration that doesn't return anything. The name of the method is mirrorFrontToBack and it doesn't take any parameters. public void mirrorFrontToBack() Here is an example public method declaration that returns an object of the class Sound. public Sound echo(int delay, int numEchoes) Notice that it gives a return type of Sound. The body of the method must have the keyword return in it, and it must return an object that is an instance of the class Sound. return echoSound; |