java · level 1 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A method is a recipe card with a name on top.
You have used methods like .length(). Now make your own. Write the recipe once, give it a name, then use it as often as you like, without copying a single line.
To one, write , a name, empty brackets and a block, inside Main but outside main. static lets main use it straight away, and means it hands nothing back. Defining it does not run it.
To it, write its name with brackets and a semicolon, like cheer();. Every line in its block then runs, top to bottom. Call it twice and it runs twice.
public class Main {
static void cheer() {
System.out.println("Go team!");
System.out.println("You can do it!");
}
public static void main(String[] args) {
cheer();
cheer();
}
} Now you can read the frame: main is a method too, and Java calls it for you when you press run.
guess first
The method comes last. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
cheer();
}
static void cheer() {
System.out.println("Go team!");
}
}
your turn
Your turn. Write your own chant.
Pick a name for your method and type it in all three name blanks. Put any words you like between the quotes, then run it.
output
press run to see what happens
fix it
The dog will not bark. Can you fix it?
output
press run to see what happens
- The method is written perfectly. Look at line 6, where you try to use it.
- Writing a method's name on its own does not call it. Something is missing after the name.
- Add brackets so line 6 says
bark();, then press run.
nailed it
you wrote your very own command. :D
- A method is a set of instructions with a name.
- Define it with
static void, a name, brackets and a block. - Call it with its name, brackets and a semicolon.
new words in your collection
- define
- call
- static
- void
This lesson isn’t saved. A free account remembers every lesson you finish.