Methods
Methods package a block of code behind a name, letting you run the same logic from many places, give it a clear return type and parameters, and keep programs organized instead of one long stream of statements.
A method is a named, reusable block of code that performs a task, optionally accepting input (parameters) and optionally producing output (a return value). Methods are how Java organizes behavior — every line of executable Java code lives inside some method, and breaking a program into well-named methods is fundamental to writing readable, maintainable code.
What Is a Method
A method groups a sequence of statements under a single name so that logic can be written once and invoked (called) many times, from many places, each time potentially with different input values. Every method belongs to a class.
public class Calculator {
public static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square(5)); // 25
System.out.println(square(12)); // 144
}
}Method Syntax: The Pieces
A method declaration has this general shape: accessModifier [static] returnType methodName(parameterList) { body }.
public static int square (int n) { ... }
^access ^static ^return ^name ^params ^body
modifier keyword typepublic static double average(int a, int b) {
return (a + b) / 2.0;
}Return Type
The return type declares what kind of value the method produces — a primitive (int, double, boolean, ...), a reference type (String, an array, a custom class), or void if the method produces no value at all and is called purely for its side effects.
static int add(int a, int b) {
return a + b; // must return an int (or something assignable to int)
}
static void printGreeting(String name) {
System.out.println("Hello, " + name); // no return value
}Method Name
By convention, Java method names use lowerCamelCase and are usually verbs or verb phrases describing the action performed (calculateTotal, isValid, printReport). Names must follow the same identifier rules as variables — they can't be a reserved keyword and can't start with a digit.
// Conventional
static boolean isEven(int n) { return n % 2 == 0; }
static int calculateTotal(int[] prices) { /* ... */ return 0; }
// Legal but unconventional (avoid)
static boolean IsEven(int n) { return n % 2 == 0; } // should be lowerCamelCaseParameters
Parameters, written inside the parentheses as Type name, are the method's inputs. A method can take zero, one, or many parameters, each with its own declared type.
static int max(int a, int b) { // two parameters
return (a > b) ? a : b;
}
static void sayHello() { // zero parameters
System.out.println("Hello!");
}Method Body
The body is the block of statements enclosed in { } that runs each time the method is called. It can declare local variables, contain loops and conditionals, call other methods, and — if the return type isn't void — must return a value along every possible execution path.
static String classify(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C or below";
}
// every path above returns, so this compiles - no missing return
}Invocation: Calling a Method
Calling (invoking) a method means writing its name followed by parentheses containing the arguments, in an order matching its parameters. If the method returns a value, that call is itself an expression you can use, store, or ignore.
int result = add(3, 4); // stores the returned value
System.out.println(add(3, 4)); // uses the returned value directly
add(3, 4); // legal but pointless - the returned value is discarded
printGreeting("Ada"); // void method: called purely for its side effectvoid: No Return Value
void means the method performs an action but does not produce a value to be used by the caller. A void method can still use a bare return; (no value) to exit early.
static void printIfPositive(int n) {
if (n <= 0) {
return; // exit early, nothing more to do
}
System.out.println(n + " is positive");
}Method Scope
Local variables and parameters declared inside a method exist only for the duration of that call and are not visible outside it — each call gets its own fresh set. This is what lets the same method be called repeatedly (even recursively) without calls interfering with each other's local state.
static int square(int n) {
int result = n * n; // 'result' exists only inside this call
return result;
}
// 'n' and 'result' are not accessible here, outside the methodStatic vs Instance Methods
A static method belongs to the class itself and is called as ClassName.methodName(...) (or unqualified from within the same class), without needing an object. An instance method belongs to individual objects, operates on that object's state via an implicit this, and is called on a reference: object.methodName(...).
A static method cannot directly access instance fields or call instance methods, because there's no implicit object (this) associated with it — it only has access to its own parameters, local variables, and other static members.
class Counter {
private int count = 0; // instance state
void increment() { // instance method - operates on THIS object's count
count++;
}
static int doubleIt(int n) { // static method - no object state involved
return n * 2;
}
}
Counter c1 = new Counter();
c1.increment(); // instance method call, needs an object
int x = Counter.doubleIt(5); // static method call, needs only the classPractical Usage: Why Break Code into Methods
Methods avoid duplicated logic (write it once, call it many times), make code easier to test in isolation, give complex logic a descriptive name that documents intent, and let a large program be understood one small piece at a time.
// Without a method: logic repeated and inlined everywhere it's needed
double circleArea1 = 3.14159 * 5 * 5;
double circleArea2 = 3.14159 * 10 * 10;
// With a method: intent is named, logic lives in one place
static double circleArea(double radius) {
return Math.PI * radius * radius;
}
double circleArea1 = circleArea(5);
double circleArea2 = circleArea(10);Edge Cases
A non-void method must return a value on every possible path through its body — the compiler performs "definite assignment/return" analysis, and code paths that can fall off the end without returning are a compile error, even if you (the programmer) know that path is unreachable at runtime.
// Compile error: "missing return statement" - the compiler can't prove
// every path returns, even though a human might reason it always does
static int sign(int n) {
if (n > 0) {
return 1;
} else if (n < 0) {
return -1;
}
// missing: what if n == 0?
}Complete Example
toLetterGrade returns a value that printReport (a void method) uses to build its output, showing a value-returning method and a void method working together.
public class ReportCard {
static char toLetterGrade(int score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
static void printReport(String student, int score) {
char grade = toLetterGrade(score);
System.out.println(student + ": " + score + " (" + grade + ")");
}
public static void main(String[] args) {
printReport("Amara", 92);
printReport("Diego", 71);
printReport("Lin", 58);
}
}Mental Model
Think of a method as a small, named machine: you feed it inputs through its parameters, it does work using its own private local variables, and it either hands back a single result through return or just performs an effect and hands back nothing (void). Each call gets a brand-new, isolated run of the machine.
Quick Reference
accessModifier [static] returnType methodName(paramType paramName, ...) {
// body
return value; // required unless returnType is void
}
void method performs an action, returns nothing
static belongs to the class; called as ClassName.method(...)
instance belongs to an object; called as object.method(...)
parameters the method's declared inputs
arguments the actual values passed at a call siteKey Takeaways
A method groups statements under a name so logic can be written once and called many times.
Its declaration specifies an access modifier, optional static, a return type, a name, and a parameter list.
void means the method performs an action but produces no value; any other return type must return a value on every possible path.
Local variables and parameters exist only for the duration of a single call and are invisible outside it.
static methods belong to the class and need no object; instance methods belong to an object and operate on its state via an implicit this.
static int sign(int n) { if (n > 0) return 1; if (n < 0) return -1; // no return for n == 0 } static int sign(int n) { if (n > 0) return 1; if (n < 0) return -1; return 0; }
A non-void method must return a value along every possible execution path; the compiler cannot verify that n == 0 is unreachable, so a missing final return is a compile error.
class Counter { private int count = 0; static void increment() { count++; // error: no implicit object for a static method } } class Counter { private int count = 0; void increment() { // instance method count++; } }
A static method has no associated object (no implicit this), so it cannot directly access an instance field like count; either make the method an instance method or operate on an explicitly passed object.
add(3, 4); // returned sum is silently discarded, caller probably meant to use it int sum = add(3, 4); System.out.println(sum);
Calling a value-returning method without using the result compiles fine but is usually a sign the caller forgot to capture the value it needed.
static void Add(int a, int b) { // PascalCase method name System.out.println(a + b); } static void add(int a, int b) { // lowerCamelCase, conventional System.out.println(a + b); }
Java naming convention uses lowerCamelCase for method names; PascalCase is reserved by convention for class names, and mixing the two makes code harder for other Java developers to read at a glance.
What are the required pieces of a method declaration (ignoring optional modifiers)?
A return type (or void), a name, a parenthesized parameter list (which may be empty), and a body enclosed in braces.
What does it mean for a method's return type to be void, and can a void method still use return?
void means the method produces no value for the caller to use — it's called purely for its side effects. It can still use a bare return; with no value to exit early, but it cannot use return someValue;.
Why must a non-void method return a value on every possible path through its body?
Because the compiler statically verifies that no execution path can fall off the end of the method without producing a return value; if it can't prove every path returns, it's a compile-time error, even if a human could argue the missing path is unreachable at runtime.
What is the practical difference between calling a static method and calling an instance method?
A static method is called on the class itself (ClassName.method(...)) and needs no object, since it isn't tied to any particular instance's state; an instance method is called on an object reference (object.method(...)) and operates on that specific object's fields via an implicit this.
Why can't a static method directly access an instance field of its own class?
A static method has no implicit 'this' — it isn't associated with any particular object — so there's no specific instance's field for it to read or write without being handed an object reference explicitly.
What is the scope and lifetime of a local variable declared inside a method?
It exists only for the duration of that particular call to the method; it's created when execution reaches its declaration and disappears when the method call ends, and it's invisible to code outside the method (including other calls to the same method).
Give two concrete benefits of extracting repeated logic into a named method.
It avoids duplicating the same logic in multiple places (fix a bug once instead of everywhere it was copied), and it gives the logic a descriptive name that documents what it does, making the calling code easier to read at a glance.
Write a static method isPrime(int n) that returns true if n is a prime number greater than 1, false otherwise, and call it to check 17.
static boolean isPrime(int n) { if (n <= 1) { return false; } for (int d = 2; d * d <= n; d++) { if (n % d == 0) { return false; } } return true; } // call: System.out.println(isPrime(17)); // true
The method first rejects numbers 1 and below, then checks for any divisor up to the square root of n; if none divide evenly, n is prime. 17 has no divisors other than 1 and itself, so isPrime(17) returns true.
What does this print, and why?
9 — mystery(-5) returns -1 (since -5 < 0), and mystery(5) returns 10 (5 * 2); -1 + 10 = 9.
Write a void static method printTimesTable(int n) that prints n's multiplication table from 1 to 5 (n x 1 through n x 5), one line each.
static void printTimesTable(int n) { for (int i = 1; i <= 5; i++) { System.out.println(n + " x " + i + " = " + (n * i)); } }
The method has no return value (void) because its job is entirely the side effect of printing; the loop generates each line by multiplying n by i for i from 1 to 5.
Does this compile, and what would happen if it did?
This does not compile — Java's compiler flags code that appears after an unconditional return (and can never execute) as 'unreachable statement,' which is a compile-time error, not just a warning.
static int mystery(int x) {
if (x < 0) {
return -1;
}
return x * 2;
}
System.out.println(mystery(-5) + mystery(5));static void greet() {
System.out.println("Hi");
return;
System.out.println("Bye"); // unreachable
}