Static methods
The sum of 2 and 5 is 7 |
Method's return type: Method's arguments: Method returns Method expects two int values arguments of type int ↘ ↙ ↙ static int sum ( int a, int b) { int result = a + b; return result; } ↖ Returning a value of 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: |
|
No. 88
Defining methods
|
Q: |
Consider: /**
* Returns the absolute value of a given integer.
* @param value
* @return The absolute value of the given integer.
*/
static int abs(int value) {
if (value < 0) {
return -value;
}
}This causes a “Missing return statement” compile time error. Explain the underlying cause and correct the implementation. |
|
A: |
There is no /**
* Returns the absolute value of a given integer.
* @param value
* @return The absolute value of the given integer.
*/
static int abs(int value) {
if (value < 0) {
return -value;
} else {
return value;
}
} |
