New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Methods and Parameters

Methods and Parameters

💻 Java

Break programs into small methods with clear inputs and outputs.

Lesson 4 of 9 Tutorial
0 of 9 completed

A method names a piece of work. Good methods are short, do one thing and make the calling code read like a sentence.

By the end of this lesson you can:
  • Define and call methods.
  • Pass parameters and return values.
  • Overload methods.

Defining a Method

A method declares its return type, name and parameters. Use void when nothing is returned.

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

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

    public static void main(String[] args) {
        System.out.println(add(3, 4));
        greet("Amina");
    }
}

Parameters and Arguments

Parameters are the names in the method definition. Arguments are the values passed at the call site. Java passes primitives by value.

Overloading

Several methods can share a name if their parameter lists differ. The compiler chooses the matching one.

static int area(int side) {
    return side * side;
}

static double area(double length, double width) {
    return length * width;
}
Tip If a method needs a comment to explain what it does, the name is probably too vague. Rename it first.

Practice

  1. Write a method that returns the larger of two numbers.
  2. Write a void method that prints a separator line.
  3. Overload a greet method for one name and for two names.

Hands-on exercise

Write a method grade(int score) that returns:
A for 70 or more, B for 60 to 69, C for 50 to 59, otherwise F.
Call it with 72, 64 and 41 and print each result.

Recap

Methods name work, take parameters and return results. Keep them short and give them honest names.

Example

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

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

    public static void main(String[] args) {
        System.out.println(add(3, 4));
        greet("Amina");
    }
}

Exercises

Exercise 1. Grade method Easy
Write a method grade(int score) that returns:
A for 70 or more, B for 60 to 69, C for 50 to 59, otherwise F.
Call it with 72, 64 and 41 and print each result.
Java exercise-1.java
Expected Output
A
B
F

Lesson Nav

Lesson sections