Labs ICT
โญ Pro Login

Methods

By now you have written a fair amount of code. But imagine if you had to rewrite the same logic every time you needed it. That would be exhausting. That is where methods come in.

A method is a reusable block of code that does one specific thing. You define it once and call it whenever you need it. Think of it as giving a name to a piece of code so you can use it again and again.

Defining and Calling a Method

A method has a return type, a name, parentheses for parameters, and curly braces for the body. Here is a simple method that prints something.

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

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

We defined a method called sayHello that prints a message. Then in main, we call it twice. It prints "Hello there!" twice. Simple as that.

Parameters

Methods can take input values called parameters. You put them inside the parentheses when defining the method, and pass values when calling it.

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

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

This prints "Hello Alice" and "Hello Bob". The method takes whatever name you give it and uses it in the message.

Return Types

Some methods do not just execute code โ€” they give you a result back. That is called a return value. Instead of void, you specify the type of value the method returns.

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

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

The add method takes two integers and returns their sum. The return keyword sends the result back to wherever the method was called.

Once a method hits a return statement, it stops running immediately. Any code after the return in that method will never execute.

๐Ÿงช Quick Quiz

What does the void keyword mean in a method declaration?