Java Methods

beginner80 min

What methods are

A method is a named block of statements you can run from elsewhere in the program. You have already called methods such as System.out.println() and Integer.valueOf().

Splitting work into methods keeps each part small, makes bugs easier to find, and lets you reuse the same logic in several places.

Method structure

Method Parameters

Parameters are variables listed in the method header. When you call the method, the argument values are copied into those parameters for the duration of the call.

Single parameter

Multiple parameters

Method Call Stack

Each method call gets its own stack frame for local variables. When a method returns, that frame is popped and execution continues in the caller.

Call stack example

Basic method examples

Method Naming Conventions

Name methods with camelCase verbs (initializeSensors, not doStuff). Indent the method body by four spaces.

Good vs bad method names

Parts of a method header

  • public static: visibility and whether the method belongs to the class (common in lesson examples)
  • Return type: void, int, double, String, boolean, etc.
  • Name: camelCase verb
  • Parameters: (type name, ...) in the parentheses
  • Body: statements inside { }, indented four spaces

Methods calling other methods

One method can call another. Each call pushes a new frame onto the stack.

The Main Method

main is the entry point: the JVM calls public static void main(String[] args) first. Other methods are reached from main or from methods main calls.

Try It Yourself:

Exercise 1: Method Fundamentals

  • Create a simple greet method and call it multiple times
  • Build a method with parameters that prints robot status
  • Write a method that returns a calculated value
  • Create a complex method that calls other methods
Practice creating and calling methods: