Java Math.abs Method

Java Math.abs Method

Absolute value of a number x is denoted as |x| and there are two scenarios when calculating absolute value

1. If x is positive (for example x = 8), then absolute value of 8 is 8 (|x|=8)

2. If x is negative (for example x = -8), then absolute value of -8 is 8 (|x|=8)

absolute value maths

Example 1: Find Absolute Value of 8 and -8 in Java.

System.out.println(Math.abs(8));  //8
System.out.println(Math.abs(-8)); //8

Example 2: Find Absolue value of 8 and -8 as variables.

int num1 = 8;
int num2 = -8;
		
System.out.println(Math.abs(num1)); //8
System.out.println(Math.abs(num2)); //8

Example 3: Create eight variables (positive and negative int, float, double and long variables) and find each variables absolute value using Math.abs method.

//int variables
int num1 = -62; 
int num2 = 114; 

System.out.println(Math.abs(num1)); //62
System.out.println(Math.abs(num2)); //114 

//float variables
float num3 = -63.8f; 
float num4 = 114.6f; 
 
System.out.println(Math.abs(num3)); //63.8
System.out.println(Math.abs(num4)); //114.6

//double variables
double num5 = -63.8; 
double num6 = 114.65; 
  
System.out.println(Math.abs(num5)); //63.8
System.out.println(Math.abs(num6)); //114.65
//long variables
long num7 = -6278224; 
long num8 = 114633255; 
  
System.out.println(Math.abs(num7)); //6278224
System.out.println(Math.abs(num8)); //114633255