자바의 Math는 계산 도구 상자로, 객체를 만들지 않고 Math.메서드()로 부릅니다. 자바는 자료형이 엄격해 반환값을 모르면 컴파일 오류부터 만납니다. 반환 자료형까지 정리한 사전입니다.
| 메서드 | 하는 일 | 반환값 |
|---|---|---|
Math.abs(n) |
절댓값 | 넣은 것과 같은 형 |
Math.max(a, b) |
둘 중 큰 값 | 넣은 것과 같은 형 |
Math.min(a, b) |
둘 중 작은 값 | 넣은 것과 같은 형 |
Math.pow(a, b) |
a의 b제곱 | 항상 double |
Math.sqrt(n) |
제곱근 | 항상 double |
Math.round(n) |
가까운 정수로 | long (float면 int) |
Math.floor(n) |
작은 쪽으로 내림 | double (4.0 형태) |
Math.ceil(n) |
큰 쪽으로 올림 | double (5.0 형태) |
Math.random() |
0.0 이상 1.0 미만 난수 | double |
Math.PI |
원주율 (상수) | double |
Math.addExact(a, b) |
넘침을 감지하는 덧셈 | 같은 형, 넘치면 예외 |
메서드는 원래 값을 바꾸지 않고 결과를 새로 돌려줍니다. 형 변환이 낯설다면 자바 변수와 자료형 편을 보십시오.
절댓값과 크기 비교 — abs, max, min
두 값의 차이를 부호 없이 구하거나 최고 점수를 뽑을 때 씁니다.
System.out.println(Math.abs(95 - 120)); // 25
System.out.println(Math.max(82, 95)); // 95
System.out.println(Math.min(82, 95)); // 82
// 배열의 최댓값 — Math.max는 두 개씩만 비교합니다
int[] scores = {82, 95, 60, 77};
int best = scores[0];
for (int s : scores) best = Math.max(best, s);
System.out.println(best); // 95
Math.max는 값을 두 개만 받으므로 배열의 최댓값은 반복문으로 비교해야 합니다.
거듭제곱과 제곱근 — pow, sqrt, PI
넣은 값이 정수라도 결과가 항상 double입니다.
System.out.println(Math.pow(2, 10)); // 1024.0 정수를 넣어도 소수
System.out.println(Math.sqrt(144)); // 12.0
// int value = Math.pow(2, 10); 컴파일 오류
System.out.println((int) Math.pow(2, 10)); // 1024 형 변환이 필요합니다
System.out.println(Math.PI * Math.pow(3, 2)); // 28.274333882308138 원 넓이
(int)처럼 앞에 자료형을 적어 바꾸는 것을 형 변환이라고 합니다. Math.PI에 괄호가 없는 것은 메서드가 아니라 상수이기 때문입니다.
올림·내림·반올림 — round, floor, ceil
세 메서드의 반환 자료형이 서로 다른 점이 자바의 특징입니다.
System.out.println(Math.round(4.6)); // 5 (long)
System.out.println(Math.floor(4.6)); // 4.0 (double)
System.out.println(Math.ceil(4.1)); // 5.0 (double)
System.out.println(Math.round(-4.5)); // -4 0.5는 큰 쪽으로
System.out.println(Math.floor(-4.1)); // -5.0 더 작은 쪽으로
int rounded = (int) Math.round(4.6); // int에 담으려면 형 변환 필요
System.out.println(Math.round(85.6789 * 100) / 100.0); // 85.68 둘째 자리
floor와 ceil이 4.0처럼 출력되어 당황하는 경우가 많습니다. 정수로 쓰려면 (int)로 변환합니다. 100.0으로 나눈 이유는 다음 절에 있습니다.
난수 만들기 — random
Math.random()은 0.0 이상 1.0 미만의 소수를 돌려줍니다. 1.0은 절대 나오지 않습니다.
System.out.println(Math.random()); // 0.4712... 매번 다릅니다
System.out.println((int) (Math.random() * 6) + 1); // 1 ~ 6 주사위
int min = 10, max = 20; // min 이상 max 이하 정수
System.out.println((int) (Math.random() * (max - min + 1)) + min); // 10 ~ 20
괄호 위치가 중요합니다. (int) Math.random() * 6처럼 쓰면 난수가 먼저 0으로 잘려 결과가 늘 0입니다. 곱셈까지 괄호로 묶은 뒤 (int)를 붙이십시오.
자주 하는 실수 — 정수 나눗셈과 오버플로
Math 메서드보다 기본 연산에서 더 많이 틀립니다.
// 실수 1: 정수끼리 나누면 소수점이 사라집니다
int total = 7, count = 2;
System.out.println(total / count); // 3 3.5가 아닙니다
System.out.println(total % count); // 1 나머지
System.out.println((double) total / count); // 3.5 한쪽만 실수로
// 실수 2: int 범위를 넘으면 음수가 됩니다 (오버플로)
int limit = Integer.MAX_VALUE;
System.out.println(limit); // 2147483647
System.out.println(limit + 1); // -2147483648 한 바퀴 돌았습니다
System.out.println((long) limit + 1); // 2147483648 long이면 안전합니다
System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648 절댓값이 음수
평균을 정수로 계산해 놓고 값이 이상하다는 경우가 많습니다. 소수가 필요하면 한쪽을 실수로 바꾸는 것을 습관으로 만드십시오. 결과를 문장으로 다듬는 방법은 자바 String 메서드 편에 있습니다.
핵심 정리
- 바로 호출 — 객체를 만들지 않고
Math.메서드()로 씁니다. - 반환 자료형 — pow·sqrt는 double, round는 long입니다.
- 난수 —
(int) (Math.random() * n) + 1로 괄호를 묶습니다. - 정수 나눗셈 —
7 / 2는 3, 한쪽을 실수로 바꿉니다. - 오버플로 — int 범위를 넘으면 음수가 되니 큰 수는
long으로