beginnerFree

Methods

Reusable blocks of code with inputs and outputs

Methods

Methods let you organize code into named, reusable pieces.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:21

The Big Picture

Methods are named blocks of code that perform actions. They accept parameters, do work, and optionally return a value.

  • Organize code into reusable, testable pieces
  • Signature: name + parameter types (not return type)
  • void methods return nothing; others must return a value

Good methods do one thing well and have descriptive names.

How It Works

Method calls use the call stack. Each call creates a frame holding local variables and return address.

  • Java passes primitives by value (copy)
  • Java passes object references by value (ref is copied)
  • static methods belong to the class, not an instance
  • Overloading: same name, different parameter types/count

In the Java Landscape

Methods are how Java implements behavior in OOP.

  • Java 8 added default methods in interfaces
  • Varargs (Java 5+): void log(String... msgs)
  • Records auto-generate accessor methods (Java 16+)
  • Method references: String::length (Java 8+)
  • final methods can't be overridden by subclasses

Pitfalls and Best Practices

  • Keep methods short - 20 lines max is a good target
  • One responsibility per method (Single Responsibility)
  • Use @Override when overriding to catch typos
  • Avoid side effects - prefer returning results
  • Validate parameters at method entry (fail fast)
  • Name with verbs: calculateTotal(), findUser()
#java#fundamentals#methods