java · level 1 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
hands the answer back so you can keep it.
So far your methods print things. Printing shows a value on the screen, and then it is gone. Your program cannot catch it, keep it or do maths with it.
To return a value, swap void for a , like int, and end with return and the value. The call then turns into the answer, as if twice(4) were the number 8.
Java checks that the method really hands something back. Forget the return and it stops with missing return statement before anything runs.
public class Main {
static int twice(int number) {
return number * 2;
}
public static void main(String[] args) {
int answer = twice(4);
System.out.println(answer);
System.out.println(twice(answer));
}
} Printing is showing someone your answer, and return is handing it to them.
guess first
This one prints instead. What will it show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static void twice(int number) {
System.out.println(number * 2);
}
public static void main(String[] args) {
int answer = twice(4);
System.out.println(answer);
}
}
your turn
Your turn. Build a dog years machine.
In the first blank, type how many dog years each year counts as. People often say 7. In the second, type your dog's age, real or made up. Then run it.
output
press run to see what happens
fix it
Your score should double, but it stays at 5. Fix it!
output
press run to see what happens
- The method works and hands back 10. But does anything catch that answer?
- Line 7 calls twice, but the returned value is dropped on the floor. Store it in a box.
- Change line 7 to
score = twice(score);, then run.
nailed it
your methods can hand back answers. :D
printlnshows a value.returnhands it back to use.- Write the return type in place of
void. - Catch a returned value in a variable to keep it.
new words in your collection
- return
- return type
This lesson isn’t saved. A free account remembers every lesson you finish.