Java Reference
In-Depth Information
documentation for your version of Java. The API describes how to use the standard
libraries that are available to Java programmers. It can be a bit overwhelming, because
the Java libraries are vast. Wander around a bit if you are so inclined, but don't be dis-
mayed that there are so many libraries to choose from in Java.
If you do look into the Math API, you'll notice that the Math class has several
overloaded methods. For example, there is a version of the absolute value method
( Math.abs ) for integers and another for doubles. The rules that govern which method
is called are complex, so we won't cover them here. The basic idea, though, is that
Java tries to find the method that is the best fit. For the most part, you don't have to
think much about this issue; you can just let Java choose for you, and it will generally
make the right choice.
Defining Methods That Return Values
You can write your own methods that return values by using a special statement known
as a return statement. For example, we often use a method that returns a value to
express an equation. There is a famous story about the mathematician Carl Friedrich
Gauss that illustrates the use of such a method. When Gauss was a boy, his teacher
asked the class to add up the integers 1 through 100, thinking that it would take a while
for them to complete the task. Gauss immediately found a formula and presented his
answer to the teacher. He used a simple trick of adding two copies of the series
together, one in forward order and one in backward order. This method allowed him to
pair up values from the two copies so that their sum was the same:
First series
Second series
Sum
1
100
101
2
99
101
3
98
101
4
97
101
. . .
. . .
. . .
100
1
101
Every entry in the right-hand column is equal to 101 and there are 100 rows in this
table, so the overall sum is 100
10100. Of course, that's the sum of two copies
of the sequence, so the actual answer is half that. Using this approach, Gauss deter-
mined that the sum of the first 100 integers is 5050. When the series goes from 1 to n ,
the sum is ( n
101
n / 2.
We can use Gauss' formula to write a method that computes the sum of the first n
integers:
1)
public static int sum(int n) {
return (n + 1) * n / 2;
}
 
 
Search WWH ::




Custom Search