Codectionary / Developer documentation / Java

Methods

A method is a named, reusable block of code that performs a specific task, defined with a return type, a name, and a parameter list. Methods can return a value (with any type, including primitives and objects) or return nothing at all using the void keyword. Java supports method overloading, where multiple methods share the same name but differ in their parameter lists.

Syntax

returnType methodName(parameters) {\n  // code\n  return value;\n}

Examples

Return a calculated result

Save as Main.java and run with a JDK.

public class Main {
  static int total(int price, int quantity) {
    return price * quantity;
  }
  public static void main(String[] args) {
    System.out.println(total(12, 3));
  }
}

Basic Method Definition and Call

Defining a method with parameters and a return value, then calling it.

public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println(result);  // 8
    }
}

void Methods

A method that performs an action but doesn't return a value.

public class Printer {
    public static void printGreeting(String name) {
        System.out.println("Hello, " + name + "!");
        // no return statement needed
    }

    public static void main(String[] args) {
        printGreeting("Fola");
    }
}

Method Parameters and Default-Like Behavior

Java has no true default parameters, but overloading achieves a similar effect.

public class Greeter {
    public static String greet(String name) {
        return greet(name, "Hello");
    }

    public static String greet(String name, String greeting) {
        return greeting + ", " + name + "!";
    }

    public static void main(String[] args) {
        System.out.println(greet("Fola"));            // Hello, Fola!
        System.out.println(greet("Zain", "Hey"));       // Hey, Zain!
    }
}

Passing Arrays and Objects to Methods

Objects and arrays are passed by reference, so a method can modify their contents.

public class ArrayModifier {
    public static void doubleValues(int[] numbers) {
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] *= 2;
        }
    }

    public static void main(String[] args) {
        int[] values = {1, 2, 3};
        doubleValues(values);
        System.out.println(java.util.Arrays.toString(values));  // [2, 4, 6]
    }
}

Best practices

  • Use void as the return type when a method performs an action but produces no result to hand back
  • Keep methods focused on a single, well-defined task - if a method needs a long comment to explain what it does, consider splitting it
  • Use descriptive verb-based method names (calculateTotal, not total) so a call site reads clearly
  • Remember arrays and objects are passed by reference in Java, so modifying them inside a method affects the original outside it - primitives, however, are passed by value (copied)

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

In plain English

A method names an operation inside a class or interface. Its declaration tells callers which inputs it accepts and which result it returns.

What you’ll learn

  • Read a method signature.
  • Return a typed result.
  • Distinguish static and instance calls.

Before you start: Classes · Variables & Primitive Data Types

Breaking down the syntax

return type
The result type, or void when no value is returned.
parameters
Typed input variables for a call.
static
The method belongs to the class and has no current instance.

How it works

Call

Supply arguments matching the method parameters.

Execute

Run the statements with local variables.

Return

Return a value matching the declared result type, or complete a void method.

When should I use this?

Use methods to give operations clear names and keep each operation focused.

Common mistakes

An absent result

A method declared to return int must return a compatible value on every path that completes normally.

Incorrect

static int doubleValue(int n) {
  System.out.println(n * 2);
}

Corrected

static int doubleValue(int n) {
  return n * 2;
}

Compare approaches

  • Instance method: Operate on a particular object’s state.
  • Static method: Perform an operation without a current instance.

Explore deeper

Overloading

Methods can share a name when their parameter lists differ. The return type alone does not distinguish overloads. The compiler chooses an applicable overload using argument types and Java’s invocation rules.

Specifications & further reading

Related Java documentation

Variables & Primitive Data Types
Java is a statically-typed language, meaning every variable must be declared with an explicit type before use, and that type cannot change afterward. Java has eight primitive types - byte, short, int, long, float, double, char, and boolean - which store simple values directly rather than references, making them fast and memory-efficient. Anything beyond primitives (String, arrays, custom classes) is a reference type instead.
System.out.println / print / printf
System.out is Java's standard output stream, and it exposes three main methods for writing text to the console. println() prints its argument followed by a newline, print() prints without adding a newline, and printf() gives C-style formatted output using format specifiers like %d, %s, and %.2f for precise control over how values are displayed.
Comments & Javadoc
Java supports single-line comments with //, multi-line comments with /* */, and a special documentation format called Javadoc, written as /** */. Javadoc comments support tags like @param, @return, and @throws, and can be processed by the javadoc tool to automatically generate HTML API documentation - the same format used for Java's own official standard library docs.
Arithmetic & Assignment Operators
Java provides the standard arithmetic operators for numeric computation: +, -, *, / for division, and % for the remainder (modulus). It also has compound assignment operators (+=, -=, etc.) that combine an operation with assignment, along with increment (++) and decrement (--) operators in both prefix and postfix forms, which subtly differ in when the value is updated relative to being used.