Spaces:
Running
Running
Create 5a Methods and return values
Browse files
Week 2: Methods, strings and lists/5a Methods and return values
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The method can also return a value.
|
| 2 |
+
The return is done in the usual way with a return statement.
|
| 3 |
+
The type of return value is specified in the method's header line: in practice, the empty return value type void is replaced by the return value type.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
For example, a method that returns the sum of two integers (which is also an integer) would look like this:
|
| 8 |
+
public static int sum(int num1, int num2) {
|
| 9 |
+
return num1 + num2;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
Example method call:
|
| 14 |
+
public static void main(String[] args) {
|
| 15 |
+
System.out.println(sum(4, 2));
|
| 16 |
+
System.out.println(sum(10, 5 * 4));
|
| 17 |
+
|
| 18 |
+
int result = sum(5, 15);
|
| 19 |
+
System.out.println(result);
|
| 20 |
+
}
|
| 21 |
+
Program outputs:
|
| 22 |
+
6
|
| 23 |
+
30
|
| 24 |
+
20
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|