0/30 Days Completed 0 Learning Days
Day 9 of 30 · Week 2 — Building Java Basics
Parameters and return values
1 Learn
Parameters are inputs to a method. You list them in the brackets with their types.
A method can send back a result with return. The return type (like int) is written before the method name.
2 See the Code
Java
public class Calc {
static int add(int a, int b) {
return a + b;
}
static double average(int a, int b) {
return (a + b) / 2.0;
}
public static void main(String[] args) {
int sum = add(4, 6);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average(4, 7));
}
}- add takes two ints and returns their sum.
- Dividing by 2.0 keeps the decimal part, so average(4, 7) is 5.5.
- The returned value can be stored in a variable or printed directly.
Output
Sum: 10 Average: 5.5
3 Practice
- Write a method isEven(int n) that returns a boolean, and print the result for 7 and 10.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. In add(int a, int b), what are a and b?
2. What does return do?
Step 5
Answer and check the Quick Check above to unlock this.