Static methods
The sum of 2 and 5 is 7 |
Method returns Method expects two int values arguments of type int ↘ ↙ ↙ static int sum ( int a, int b) { int result = a + b; return result; } ↖ Corresponding to return type int
public static void main(String[] args) {
...
// Compile error: Non-static method 'sum(int, int)'
// cannot be called from a static context
int result = sum (i,j);
...
}
// No static modifier
int sum ( int a, int b) {
return a + b;
}/**
* Calculates the sum of two integers.
*
* @param a the first integer to add
* @param b the second integer to add
* @return the sum of the two integers
*/
static int sum (int a, int b) {
int result = a + b;
return result;
}| Method definition | Method usage |
|---|---|
public class Helper { static int sum(int a, int b) { int result = a + b; return result; } } |
public class Add {
public static void main(String[] args) {
int i = 2, j = 5;
int result = Helper.sum(i, j);
System.out.println("The sum of " + i +
" and " + j + " is " + result);
}
} |
No. 87
Defining methods
|
Q: |
Follow Figure 193, “Separating usage and definition ” and define the
following two methods in a separate class
Provide Javadoc™ based documentation as being shown in Figure 192, “Documentation: Javadoc™ is your friend! ”. Then generate HTML documentation from it and view it in a Web browser of your choice. On completion the following sample should work (if the
|
||||
|
A: |
|
