Java

Math

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);
}
}1
1.23
1

If

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);
}
}6
15
6
15

Overload

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on May 9, 2022 (edit link).