MyMisPal
← Java lessons
Lesson 6 of 9

Methods

JAVA
public class Main {
    static double vat(double amount) {
        return amount * 0.15;
    }

    static String grade(int score) {
        if (score >= 90) return "A";
        if (score >= 80) return "B";
        return "C";
    }

    public static void main(String[] args) {
        System.out.println(vat(1000));
        System.out.println(grade(85));
    }
}
Output
150.0
B
staticcallable without creating an object
double / Stringthe type of value it returns
voidreturns nothing
(double amount)parameters with their types

Overloading: several methods can share a name if their parameters differ:

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

    static double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 3.5));
    }
}
Output
5
6.0
Same idea in both languages
Python
def vat(amount):
    return amount * 0.15
Java
static double vat(double amount) {
    return amount * 0.15;
}
Spotted a mistake on this page, or have an idea to improve the site?