Java Functions Cheat Sheet & Laboratory Exercises
CHEAT SHEET
1. Method Declaration & Definition
static int add(int a, int b) {
return a + b;
}
2. Return Values
static int square(int x) {
return x * x;
}
static void display() {
[Link]("Hello");
}
3. Parameters & Arguments
static void greet(String name) {
[Link]("Hello " + name);
}
4. Pass-by-Value
static void change(int x) {
x = 10;
}
5. Scope
int globalVar = 10;
void test() {
int localVar = 5;
}
6. Recursion
static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
7. Modular Programming
Break programs into reusable methods.
8. Code Reuse
Avoid repetition using reusable methods.
LABORATORY EXERCISES
1 Create a method that returns the sum of two integers.
2 Write a method that prints your name using parameters.
3 Create a method that calculates the square of a number.
4 Demonstrate pass-by-value using a variable.
5 Write a program showing local and global variable scope.
6 Create a recursive method to compute factorial.
7 Build a simple calculator using methods.
8 Create a method that finds the largest of three numbers.
9 Write a method that counts vowels in a string.
10 Create a reusable utility class with at least 3 methods.