C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Types: Math.abs returns various types. These depend on the types passed to it. If we pass an int, we receive an int in return.
Java program that uses Math.abs
import java.lang.Math;
public class Program {
public static void main(String[] args) {
// This version uses an int.
int value = Math.abs(-1);
System.out.println(value);
// This version uses a double.
double value2 = Math.abs(-1.23);
System.out.println(value2);
int value3 = Math.abs(1);
System.out.println(value3);
}
}
Output
1
1.23
1
Here: The addAbsoluteValue adds if a number is positive, and subtracts if it is negative.
Tip: We can rewrite addAbsoluteValue with a call to Math.abs. This reduces code size and makes things clearer.
Java program that rewrites if-statement with Math.abs
public class Program {
static int addAbsoluteValue(int base, int number) {
// Add number if it is positive.
// ... Subtract if it is negative.
if (number > 0) {
return base + number;
} else {
return base - number;
}
}
public static void main(String[] args) {
// Use our custom method and rewrite it with Math.abs.
int result1 = addAbsoluteValue(5, -1);
int result2 = addAbsoluteValue(5, 10);
int result3 = 5 + Math.abs(-1);
int result4 = 5 + Math.abs(10);
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
System.out.println(result4);
}
}
Output
6
15
6
15