← Java from Scratch Lesson 23 of 88 · 10 XP

Methods

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A method is a named block of code inside a class:

public class Main {
    static void greet() {                 // void — returns nothing
        System.out.println("Hello!");
    }

    static int square(int x) {            // returns an int
        return x * x;
    }

    public static void main(String[] args) {
        greet();
        System.out.println(square(7));    // 49
    }
}
  • static — the method belongs to the class and is called without an object (from a static main you can call only static methods directly — otherwise you get the error non-static method cannot be referenced from a static context);
  • the return type goes before the name; return ends the method;
  • methods can be declared in any order — above or below main.

Task. Write static boolean isPrime(int n) and print, separated by spaces, all the prime numbers from 2 to n.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.