Organizing Code with Methods

Giving a block of code its own name

8 min read

As programs grow, repeating the same block of code in many places becomes messy and hard to maintain. Methods solve this by letting you give a name to a block of code so you can reuse it whenever you need it.

public static void greet() {
    System.out.println("Hello there!");
}

This defines a method named greet. To actually run it, you call it by name followed by parentheses, usually from inside main:

public static void main(String[] args) {
    greet();
    greet();
}

That would print Hello there! twice, once for each call, without you needing to write the println line more than once.

Methods that accept information

Methods become far more useful when they accept information through parameters, which are placed inside the parentheses:

public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

Calling greet("Amir") would print Hello, Amir! while greet("Priya") would print Hello, Priya! using the exact same method.

Methods that send information back

So far, void in front of a method name has meant this method does not return a result. A method can also calculate something and hand the result back to whoever called it:

public static int addNumbers(int a, int b) {
    return a + b;
}

Calling addNumbers(3, 4) produces the value 7, which you could then print, store in a variable, or use in a further calculation.

Good to know: The word before a method's name, such as void or int, describes the type of value it returns. void simply means nothing is returned.

Breaking a program into small, well named methods is one of the most important habits you can build early on, since it keeps your code organized and easy to read as it grows.

Quick check

Q1 What does void mean in front of a method name?

Q2 What are the pieces of information a method accepts inside its parentheses called?

Want to save your progress? It's free.

Create a free account