Programming Examples
Java program to find absolute value of number
Write a Java program that takes a number as input and calculates its absolute value using the Math.abs() function.
Solution
import java.util.Scanner;
public class AbsoluteValue
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = sc.nextDouble();
double absoluteValue = Math.abs(number);
System.out.println("The absolute value of " + number + " is " + absoluteValue);
}
}
Output
Write a program to input any integer number and print its absolute value.
Non sign representation on number is known as Absolute value.
Solution
import java.util.Scanner;
public class AbsoluteValue
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
int absoluteValue=number;
if (number < 0)
{
absoluteValue = -number; // If number is negative, make it positive
// alternate method is : absoluteValue=number*-1;
}
System.out.println("Absolute value of " + number + " is: " + absoluteValue);
}
}
Output