티스토리 뷰

728x90

Java8부터 추가된 Math 클래스의 정적 메서드를 실습해본다.
기본적으로 자바에 있는 클래스들의 정적 메서드를 많이 알고 활용하는 것이 소스코드의 가독성에서도 좋은 것 같다.
개발자가 구현하려고 하면 할수있지만 괜한 수고를 할뿐더러 예외처리까지 다 적용되어있는 정적 메서드를 쓰는 편이 마음이 편하다.
전부는 아니지만 몇가지만 살펴본다.

더하기 Math.addExact

addExact 메서드로 덧셈을 실행한다. 인수값으로 int형 또는 long형 값이 들어올 수 있다.
int형과 long형으로 오버로딩 되어있다.
MAX값을 넘어서는 값을 보내면 ArithmeticException overflow가 발생한다.

@Test
@DisplayName("더하기")
void addExactTest() throws Exception {
    int a = 1000;
    int b = 2000;
    assertThat(Math.addExact(a, b)).isEqualTo(3000);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.addExact(1, Integer.MAX_VALUE))
            .withMessageMatching("integer overflow");

    long x = 10L;
    long y = 20L;
    assertThat(Math.addExact(x, y)).isEqualTo(30L);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.addExact(1, Long.MAX_VALUE))
            .withMessageMatching("long overflow");
}

빼기 Math.subtractExactTest

덧셈과 똑같다.

@Test
@DisplayName("빼기")
void subtractExactTest() throws Exception {
    int a = 1000;
    int b = 2000;
    assertThat(Math.subtractExact(a, b)).isEqualTo(-1000);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.subtractExact(Integer.MAX_VALUE, -1))
            .withMessageMatching("integer overflow");

    long x = 10L;
    long y = 20L;
    assertThat(Math.subtractExact(x, y)).isEqualTo(-10L);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.subtractExact(Long.MAX_VALUE, -1))
            .withMessageMatching("long overflow");
}

곱하기 Math.multiplyExactTest

@Test
@DisplayName("곱하기")
void multiplyExactTest() throws Exception {
    int a = 1000;
    int b = 2000;
    assertThat(Math.multiplyExact(a, b)).isEqualTo(2_000_000);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.multiplyExact(Integer.MAX_VALUE, 2))
            .withMessageMatching("integer overflow");

    long x = 10L;
    long y = 20L;
    assertThat(Math.multiplyExact(x, y)).isEqualTo(200L);
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.multiplyExact(Long.MAX_VALUE, 2))
            .withMessageMatching("long overflow");
}

값 1 증가 Math.incrementExact

인수를 하나만 넘기는데 넘긴 인수값에 +1 한 값을 리턴해준다.
만약 그게 MAX_VALUE를 넘어서면 overflow가 발생한다.

@Test
@DisplayName("인수에 1증가 값")
void incrementExactTest() throws Exception {

    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.incrementExact(Integer.MAX_VALUE))
            .withMessageMatching("integer overflow");

    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.incrementExact(Long.MAX_VALUE))
            .withMessageMatching("long overflow");
}

값 1 감소 Math.decrementExact

incrementExact와 반대

@Test
@DisplayName("인수에 1마이너스 값")
void decrementExact() throws Exception {
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.decrementExact(Integer.MIN_VALUE))
            .withMessageMatching("integer overflow");

    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.decrementExact(Long.MIN_VALUE))
            .withMessageMatching("long overflow");
}

부호 변경 Math.negateExact

부호를 변경해서 준다.
주의할 점은 자바의 int형식은 -2147483648 ~ +2147483647 인데 MIN_VALUE를 넘겼을 때는

양수의 범위를 초과하므로 overflow가 발생한다. long도 똑같음.

@Test
@DisplayName("부호를 변경")
void negateExactTest() throws Exception{
    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.negateExact(Integer.MIN_VALUE))
            .withMessageMatching("integer overflow");

    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.negateExact(Long.MIN_VALUE))
            .withMessageMatching("long overflow");
}

long 타입을 int로 변경 Math.toIntExact

int 타입 범위를 넘어가는 값을 넘기면 overflow가 발생한다.

@Test
@DisplayName("long을 int로 변환")
void toIntExactTest() throws Exception{

    assertThat(Math.toIntExact(20L)).isEqualTo(20);

    assertThatExceptionOfType(ArithmeticException.class)
            .isThrownBy(() -> Math.toIntExact(Long.MAX_VALUE))
            .withMessageMatching("integer overflow");
}

참고

bit.ly/3qqg1Am

 

www.programiz.com/java-programming/library/math/negateexact

 

소스코드

github.com/sskim91/java-spring-lab/blob/main/sample-java/test/exact/ExactTests.java

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함