Java Reference
In-Depth Information
This snippet of code will perform the sum of all integers between 40 and 60 , and it will print 1050 . Note the
similarities and differences between the two snippets of code. The logic is the same in both. However, the lower limit
and the upper limit of the range are different. If you can ignore the differences that exist between the two snippets of
code, you will be able to avoid the duplicating of logic in two places.
Let's consider the following snippet of code:
int sum = 0;
int counter = lowerLimit;
while(counter <= upperLimit) {
sum = sum + counter;
counter = counter + 1;
}
System.out.println(sum);
This time, you did not use any actual values for the lower and upper limits of any range. Rather, you used
lowerLimit and upperLimit placeholders that are not known at the time the code is written. By using lowerLimit and
upperLimit placeholders in your code, you are hiding the identity of the lower and upper limits of the range. In other
words, you are ignoring their actual values when writing the above piece of code. You have applied the process of
abstraction in the above code by ignoring the actual values of the lower and upper limits of the range.
When the above piece of code is executed, the actual values must be substituted for lowerLimit and upperLimit
placeholders. This is achieved in a programming language by packaging the above snippet of code inside a module
(subroutine or subprogram) called a procedure. The placeholders are defined as formal parameters of that procedure.
Listing 1-2 has the code for such a procedure.
Listing 1-2. A Procedure Named getRangeSum to Compute the Sum of All Integers Between Two Integers
int getRangeSum(int lowerLimit, int upperLimit) {
int sum = 0;
int counter = lowerLimit;
while(counter <= upperLimit) {
sum = sum + counter;
counter = counter + 1;
}
return sum;
}
A procedure has a name, which is getRangeSum in this case. A procedure has a return type, which is specified
just before its name. The return type indicates the type of value that it will return to its caller. The return type is int
in this case, which indicates that the result of the computation will be an integer. A procedure has formal parameters
(possibly zero), which are specified within parentheses following its name. A formal parameter consists of data type
and a name. In this case, the formal parameters are named as lowerLimit and upperLimit , and both are of the data
type int . It has a body, which is placed within braces. The body of the procedure contains the logic.
When you want to execute the code for a procedure, you must pass the actual values for its formal parameters.
You can compute and print the sum of all integers between 10 and 20 as follows:
int s1 = getRangeSum(10, 20);
System.out.println(s1);
This snippet of code will print 165 .
 
Search WWH ::




Custom Search