Repository navigation
Expand file tree
/
Copy pathReturnValues.java
More file actions
82 lines (72 loc) · 2.38 KB
/
Copy pathReturnValues.java
File metadata and controls
82 lines (72 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package javakb.ch04_methods;
/**
* ReturnValues demonstrates returning values from methods in Java.
*
* Key Concepts:
* 1. Method return type specifies what data type the method gives back to the caller.
* 2. Use 'void' if the method does not return any value.
* 3. The 'return' statement exits the method immediately and optionally yields a value.
*/
public class ReturnValues {
/**
* Calculates the sum of two integers.
*
* @param a First integer
* @param b Second integer
* @return Sum of a and b
*/
public static int add(int a, int b) {
return a + b; // Must return an int
}
/**
* Calculates the average of three numbers.
* Fixes operator precedence: (a + b + c) / 3.0 instead of a + b + c / 3.
*
* @param a First number
* @param b Second number
* @param c Third number
* @return Average of a, b, and c as double
*/
public static double average(double a, double b, double c) {
return (a + b + c) / 3.0;
}
/**
* Checks if a given number is even.
*
* @param number Integer to check
* @return true if even, false otherwise
*/
public static boolean isEven(int number) {
return number % 2 == 0;
}
/**
* Demonstrates early return to guard against invalid inputs.
*
* @param age Age of user
*/
public static void printEligibility(int age) {
if (age < 0) {
System.out.println("Invalid age provided: " + age);
return; // Early return to exit method early
}
if (age >= 18) {
System.out.println("Age " + age + ": Eligible to vote.");
} else {
System.out.println("Age " + age + ": Not eligible to vote yet.");
}
}
public static void main(String[] args) {
System.out.println("--- 1. Returning Primitive Values ---");
int sum = add(15, 25);
System.out.println("Sum is: " + sum);
double avg = average(3.0, 4.0, 5.0);
System.out.println("Average of 3, 4, 5 is: " + avg);
System.out.println("\n--- 2. Boolean Return Values ---");
int testNum = 8;
System.out.println("Is " + testNum + " even? " + isEven(testNum));
System.out.println("\n--- 3. Early Return Guard Clause ---");
printEligibility(-5);
printEligibility(16);
printEligibility(21);
}
}