Lesson 21 +10 XP

Java Methods

Java Methods

A method is a block of code that only runs when you call it. You can pass data into a method, and it can return data.

Declaring a method

static void myMethod() {
  System.out.println("Hello World!");
}
  • static means the method belongs to the class and can be called without creating an object.
  • void means the method does not return a value.

Calling a method

To call a method, write its name followed by parentheses:

myMethod();

Call a method multiple times

static void myMethod() {
  System.out.println("Hello World!");
}

public static void main(String[] args) {
  myMethod();
  myMethod();
  myMethod();
}

Each call runs the block again.

Why use methods

  • Reuse code without rewriting it.
  • Organize a program into clear pieces.
  • Make changes in one place instead of many.

TL;DR

  • Methods are reusable blocks of code.
  • void methods return nothing.
  • Call a method with its name and parentheses.