🎯 What you will learn
- Write static methods
- Use parameters and return types
- Call methods from main
👋 Let’s get started!
Methods are Java’s version of functions 🛠️. You give them a name, inputs and the TYPE of answer they return. Then call them as often as you like!
🪜 Step by step
1. 🛠️ A simple method
void means it doesn’t return anything.
static void cheer() {
System.out.println("Hooray! 🎉");
}
2. 📥📤 Parameters & return
Say the return type before the name, and the parameter types inside ( ).
static int add(int a, int b) {
return a + b;
}
3. 📞 Calling
Call methods from main.
public static void main(String[] args) {
cheer();
System.out.println(add(4, 6));
}
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Area calculator
public class Main {
static int area(int w, int h) {
return w * h;
}
public static void main(String[] args) {
System.out.println("Room: " + area(5, 4));
System.out.println("Garden: " + area(10, 7));
}
}Greeting method
static void greet(String name) {
System.out.println("Hi " + name);
}📖 Key words
Tap a card to flip it over!
- Method
- A named block of reusable code 🛠️
- void
- Returns nothing 🚫
- Return type
- The type of answer a method gives back 📤
- Argument
- The value you pass in when calling 📥
🏆 Challenge
Predict the output of this method call.
Challenge
static int triple(int n) {
return n * 3;
}
// in main:
System.out.println(triple(9));Knowledge Check Quiz
- What does void mean?
- What prints?
- Which method returns a String?