Math.abs() 是否可能为负数?

答案:

  positive, 可能.

效果:

Math.abs() 是否可能为负数?

代码:

package com.jiajava.jiadis;

import org.junit.Test;
//import static org.assertj.core.api.Assertions.assertThat;
import org.assertj.core.api.Assertions;

/**
 * @ClassName MathAbsTest
 * @Description TODO
 * @Author guofangsky
 * @CreateAt 3/2/2019 18:26
 * @Version 1.0.0
 */
public class MathAbsTest {

    @Test
    public void test1(){
        int a = Integer.MAX_VALUE;
        System.out.println("a=" + a);
        System.out.println("a+1=" + (a+1));
        int b = Math.abs(a+1);
        System.out.println("b=" + b);
        Assertions.assertThat(b).isLessThan(0);
//        assertThat(fromJsonMessageQueue.getQueueId()).isEqualTo(messageQueue.getQueueId());
    }
}

解释:

jdk Math.abs doc:


 /**
     * Returns the absolute value of an {@code int} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     *
     * <p>Note that if the argument is equal to the value of
     * {@link Integer#MIN_VALUE}, the most negative representable
     * {@code int} value, the result is that same value, which is
     * negative.
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static int abs(int a) {
        return (a < 0) ? -a : a;
    }

如果是对Integer(Long也一样)取绝对值,如果原值是Integer.MIN_VALUE,则得到的绝对值和原值相等,是一个负数。为什么呢?因为看abs的实现,它很简单,如果原值是正数,直接返回,如果是负数,就简单地在前面加个负号。然而Integer的范围是[-2147483648,2147483647],如果原值是最小的值取反之后就越界了。
 

另外的示例:

Math.abs() 是否可能为负数?