As programs grow, putting everything inside main quickly becomes messy. A method is a named block of code that does one job. You write it once and call it whenever that job is needed, from main or from other methods.
You've already been calling methods: System.out.println(), name.length() and Integer.parseInt() are all methods written by the Java team. In this lesson you'll write your own.
Because Java is typed, every method states what it needs and what it gives back: the types of its parameters and its return type. That makes a method's purpose clear just from its first line.
Declaring and calling a method
public class Main {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
greet();
greet();
}
}- Methods are written inside the class, but outside other methods.
staticmeans the method belongs to the class itself, somaincan call it directly. You'll meet non-static methods in the classes lesson.voidmeans the method doesn't return anything.- Call a method by writing its name followed by brackets:
greet();
Parameters
Parameters are variables listed in the method's brackets, each with its type:
static void greet(String name, int times) {
for (int i = 0; i < times; i++) {
System.out.println("Hi " + name);
}
}When you call it, pass arguments of the right types, in the right order: greet("Zoe", 2);. Passing greet(2, "Zoe") won't compile, which is exactly the kind of mistake Java's types catch for you.
Return types
Replace void with a type when the method gives back a value, and use return to send it:
static int square(int n) {
return n * n;
}
int result = square(7); // 49- The returned value must match the declared return type.
returnends the method immediately.- A method can return any type:
int,double,boolean,String, arrays or your own classes.
Overloading
Java allows several methods with the same name as long as their parameter lists differ in number or types. This is called overloading:
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }Java picks the right version from the arguments you pass. println is overloaded too, which is why it can print numbers, text and booleans.
How Java passes arguments
Java always passes arguments by value: the method receives a copy of each value. For primitives such as int, that means a method can't change the caller's variable:
static void addOne(int n) {
n = n + 1; // changes the copy only
}After int x = 5; addOne(x);, x is still 5. To get a new value out of a method, return it: x = plusOne(x);.
For objects and arrays, the value that gets copied is the reference, the arrow pointing to the object. Both the caller and the method then point at the same object, so a method can change the object's contents, for example by appending to a StringBuilder or changing an array element. But assigning a brand-new object to the parameter only changes the method's copy of the arrow; the caller still sees the original object.
Varargs: any number of arguments
Sometimes a method should accept any number of values. Add ... after the parameter type to make a varargs parameter, which arrives inside the method as an array:
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}Now sum(), sum(4) and sum(1, 2, 3) all work, returning 0, 4 and 6. A varargs parameter must be the last one in the list, and a method can have only one. String.format and List.of use varargs, which is why they accept as many values as you like. The companion lessons on parameters and return values and overloading go further.
Java Methods Syntax
Method syntax
static returnType methodName(Type param1, Type param2) {
// body
return value; // not needed for void
}
methodName(arg1, arg2);Java Methods Summary
- A method is a named, reusable block of code inside a class.
static void name()defines a method that returns nothing; call it withname();.- Parameters are typed:
(String name, int age). Arguments must match in type and order. - A return type replaces
void;returnsends the value back and ends the method. - Overloaded methods share a name but take different parameters.
Java Methods Examples
Each example shows the code, the output it produces and what each part does.
A method with no return value
public class Main {
static void printLine(char symbol, int length) {
for (int i = 0; i < length; i++) {
System.out.print(symbol);
}
System.out.println();
}
public static void main(String[] args) {
printLine('=', 12);
System.out.println(" RECEIPT");
printLine('-', 12);
}
}============
RECEIPT
------------Line-by-line explanation
- Line 2Two parameters: a char and an int.
- Line 10The method draws a line of 12 equals signs.
- Line 12The same method, called again with different arguments, draws a line of dashes.
Methods that return values
public class Main {
static double celsiusToFahrenheit(double c) {
return c * 9 / 5 + 32;
}
static boolean isHot(double c) {
return c >= 30;
}
public static void main(String[] args) {
double today = 31.5;
System.out.println(today + "C = " + celsiusToFahrenheit(today) + "F");
System.out.println("Hot day? " + isHot(today));
}
}31.5C = 88.7F
Hot day? trueLine-by-line explanation
- Lines 2 to 4Returns a double calculated from the parameter.
- Lines 6 to 8A method that answers a yes/no question returns a boolean.
- Line 12The returned value is used directly inside println.
Overloading in action
public class Main {
static int biggest(int a, int b) {
return a > b ? a : b;
}
static int biggest(int[] numbers) {
int max = numbers[0];
for (int n : numbers) {
if (n > max) max = n;
}
return max;
}
public static void main(String[] args) {
System.out.println(biggest(8, 3));
System.out.println(biggest(new int[] {4, 19, 7, 11}));
}
}8
19Line-by-line explanation
- Line 2The first version of biggest takes two ints.
- Line 6The second version has the same name but takes an array.
- Lines 15 to 16Java chooses the right version from the arguments.
Common Java Methods Mistakes
Forgetting to return a value
static int doubleIt(int n) {
int result = n * 2;
}static int doubleIt(int n) {
int result = n * 2;
return result;
}The compiler reports "missing return statement" for any non-void method without a return.
Defining a method inside main
public static void main(String[] args) {
static void hello() { System.out.println("Hi"); }
}static void hello() { System.out.println("Hi"); }
public static void main(String[] args) {
hello();
}Methods belong directly inside the class, never inside another method.
Using the result of a void method
static void add(int a, int b) { System.out.println(a + b); }
int total = add(2, 3);static int add(int a, int b) { return a + b; }
int total = add(2, 3);A void method gives nothing back, so there's nothing to store.
Java Methods in Real Projects
Methods in real projects
A checkout system might have calculateSubtotal(), applyDiscount() and calculateShipping(), each tested on its own. Large Java codebases contain thousands of small, well-named methods, and tools like IntelliJ let you jump from a call to its definition with one click.
Java Methods FAQ
What is the difference between a parameter and an argument?
A parameter is the variable declared in the method's brackets, such as int n in square(int n). An argument is the actual value passed in a call, such as 7 in square(7). When the method runs, each parameter starts with the value of its argument.
Can a Java method return more than one value?
Not directly: a method has a single return type. To return several values, return an object that groups them, such as a record like record MinMax(int min, int max) {}, an array, or a collection. A record is usually the clearest choice, because each value gets a name.
What does static mean on a method?
A static method belongs to the class, not to any particular object, so you call it without creating an object, as in Math.max(3, 7) or calling a helper from main. A method without static is an instance method and works on one object's fields.
Can I overload a method by changing only its return type?
No. Java chooses between overloads using the method name and the parameter types, called the method signature. Two methods that differ only in their return type would be ambiguous at the call site, so the compiler rejects them.
Can a method call itself?
Yes. A method that calls itself is recursive. Each call must move closer to a base case that stops the recursion, otherwise the program fails with a StackOverflowError. The recursion basics lesson explains how it works.
Java Methods Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the method so it returns the sum of two ints.
static sum(int a, int b) {
a + b;
}
What does this print?
static String shout(String s) {
return s.toUpperCase() + "!";
}
// in main:
System.out.println(shout("hey"));
Which return type should a method use if it only prints something?
What does this print?
static int f(int x) { return x + 1; }
static int f(int x, int y) { return x * y; }
// in main:
System.out.println(f(3) + f(3, 4));
Which pair of methods is valid overloading?
Java Methods Quiz
5 questions to check what you learned.
What does
voidmean in a method declaration?- The method doesn't return a value
- The method is empty
- The method can't have parameters
- The method is private
What is method overloading?
- Calling a method too many times
- Several methods with the same name but different parameter lists
- A method that calls itself
- A method with too many lines
Where must methods be declared?
- Inside main
- Outside any class
- Inside a class, outside other methods
- In a separate file only
What happens to code after a
returnstatement in the same block?- It runs after returning
- It runs first
- It runs only for void methods
- It never runs, and Java reports it as unreachable
What does
voidmean in a method declaration?- The method doesn't return a value
- The method is empty
- The method can't be called
- The method is private