← Java 처음부터
레슨 23 / 88 · 10 XP
메서드
이론과 문제
기계 번역이에요. 아직 원어민이 검토하지 않았어요.
메서드는 클래스 안의 이름이 붙은 코드 블록이에요:
public class Main {
static void greet() { // void — 아무것도 돌려주지 않아요
System.out.println("Hello!");
}
static int square(int x) { // int를 돌려줘요
return x * x;
}
public static void main(String[] args) {
greet();
System.out.println(square(7)); // 49
}
}
static— 메서드가 클래스에 속하고 객체 없이 불려요(static main에서는static메서드만 바로 부를 수 있어요 — 아니면 오류non-static method cannot be referenced from a static context가 나요);- 반환 자료형은 이름 앞에 써요;
return이 메서드를 끝내요; - 메서드는 어떤 순서로든 선언할 수 있어요 —
main위든 아래든.
과제. static boolean isPrime(int n)을 쓰고, 2부터 n까지의 모든 소수를 공백으로 구분해 출력하세요.