Commit fe97b75
committed
feat: Add Sum class with overloaded methods for different summations
WHAT the code does:
- Defines a `Sum` class demonstrating different ways of summing integers.
- `sum2()`:
- Reads two integers from user input via `Scanner`.
- Returns their sum.
- `sum3(int, int)`:
- Returns sum of two integers passed as arguments.
- `sum4(int, int, int)`:
- Returns sum of three integers.
- `main()` demonstrates:
- Calling `sum2()` interactively.
- Calling `sum3(20, 30)` → outputs 50.
- Calling `sum4(100, 200, 300)` → outputs 600.
WHY this matters:
- Demonstrates **method overloading** with different parameter counts.
- Shows difference between interactive input-based and parameter-based methods.
- Reinforces **return values vs printing** in methods.
HOW it works:
1. `sum2()` asks user for two inputs and returns their sum.
2. `sum3()` is a straightforward addition of two integers.
3. `sum4()` adds three integers.
4. All results are stored in variables (`ans`, `ans2`, `ans3`) and printed.
Tips & gotchas:
- `Scanner` in `sum2()` should be closed after use → currently left open.
- Avoid using `System.out.println` after a `return` (unreachable code).
- Method naming (`sum2`, `sum3`, `sum4`) could be improved for clarity.
- Could add `varargs` method (`sum(int... nums)`) to generalize addition.
Use-cases:
- Teaching example for **methods and overloading** in Java.
- Practice with interactive input handling using `Scanner`.
- Useful as a simple calculator demonstration.
- Basis for extending into math utility classes.
Short key: class-sum-method-overloading.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 491b333 commit fe97b75
1 file changed
+15
-25
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
| 5 | + | |
9 | 6 | | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
10 | 13 | | |
11 | 14 | | |
12 | | - | |
| 15 | + | |
13 | 16 | | |
14 | | - | |
15 | | - | |
| 17 | + | |
16 | 18 | | |
17 | 19 | | |
18 | | - | |
19 | 20 | | |
20 | 21 | | |
| 22 | + | |
21 | 23 | | |
22 | 24 | | |
| 25 | + | |
23 | 26 | | |
24 | 27 | | |
| 28 | + | |
25 | 29 | | |
26 | 30 | | |
27 | | - | |
| 31 | + | |
28 | 32 | | |
29 | 33 | | |
30 | | - | |
31 | | - | |
32 | | - | |
33 | | - | |
34 | | - | |
35 | | - | |
36 | | - | |
37 | | - | |
| 34 | + | |
| 35 | + | |
38 | 36 | | |
39 | | - | |
40 | | - | |
41 | | - | |
42 | | - | |
43 | | - | |
44 | | - | |
45 | | - | |
46 | | - | |
47 | 37 | | |
0 commit comments