Java Methods

Parameters, return values, overloading and recursion.

✍️ 2 exercises in this lesson

A method is a block of code inside a class that runs when called.

  • static int add(int a, int b) { return a + b; }
  • void means the method returns nothing.
  • Overloading: several methods with the same name but different parameters.
  • Recursion: a method that calls itself, with a stopping condition.

Key Takeaways: Java Methods

Mastering Java Methods helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Methods Code Example

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

    static int factorial(int n) {
        return n <= 1 ? 1 : n * factorial(n - 1);
    }

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

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 3.5));
        System.out.println(factorial(6));
        greet("Usman");
    }
}
Output
5
6.0
720
Hello, Usman
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Methods Practice Exercises

Check what you learned in “Java Methods”.

/ 2 solved
Fill in the blank

This method returns nothing.

static  greet(String name) { }
✓ Correct! Not quite. Try again.
Multiple choice

What is method overloading?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services