All lessons

Methods

9 min · Java

Package code under a name so you can reuse it (Java calls them methods).

Java · Methods0/5 cleared

Enemy 1 of 5

A method is Java's name for what other languages call a function: a named, reusable block of code you write once and run as many times as needed by calling its name. Methods are how Java programs avoid repeating the same logic in multiple places.

Declaring a method means writing its return type, its name, and its parameter types (each parameter also needs an explicit type, just like variables do) — static int doubleIt(int n) declares a method named doubleIt that takes one int parameter and promises to return an int. The static keyword lets main (which is itself static) call the method directly, without needing to create an object first — you'll see the deeper reason for static once you get into classes and objects beyond this course's scope, but for now it's enough to know it's required for methods called straight from main.

Use return to hand a value back to whoever called the method. If a method is declared to return int but some path through its body tries to return something else — or forgets to return at all — Java's compiler will refuse to build the program, catching that mistake immediately rather than letting it surface later.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10