0/30 Days Completed 0 Learning Days
Day 8 of 30 · Week 2 — Building Java Basics
Methods: creating and calling
1 Learn
A method is a named block of code that does one job. You write it once and call it whenever you need it.
Methods keep programs short and organized. Instead of repeating code, you call the method by name.
For now we write static methods so main can call them directly.
2 See the Code
Java
public class Greet {
static void sayHello() {
System.out.println("Hello, student!");
}
public static void main(String[] args) {
sayHello();
sayHello();
}
}- static void sayHello() — defines a method that returns nothing (void).
- sayHello(); — calls the method. Calling it twice prints the message twice.
Output
Hello, student! Hello, student!
3 Practice
- Write a method printLine() that prints ---------- and call it before and after a heading.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. What does void mean for a method?
2. Why use methods?
Step 5
Answer and check the Quick Check above to unlock this.