How to find the absolute value of a number using Java?

You can use the abs method in the Math class to calculate the absolute value of a number. Below is an example program written in Java:

public class AbsoluteValue {
    public static void main(String[] args) {
        int num = -5;
        int absValue = Math.abs(num);
        System.out.println("绝对值为:" + absValue);
    }
}

In this example, we defined an integer variable ‘num’ and assigned it a value of -5. Next, we used the Math class’s abs method to calculate the absolute value of ‘num’ and assigned the result to a variable called ‘absValue’. Finally, we used the System.out.println statement to output the calculation result to the console.

When you run this program, it will output: Absolute value is: 5. This indicates that the absolute value of -5 is 5.

bannerAds