Write a Java program to Find the absolute value of a number using library method
This Java program reads a double value from the user and then uses the Math.abs method to determine the absolute value of the number. Here's a breakdown of the program:
- The import java.util.*; statement imports the java.util package, which contains the Scanner class that is used to read input from the user.
- The public class Absolute_Values statement declares a public class called Absolute_Values, which is the name of the Java file that this program is saved in.
- The public static void main(String[] args) method is the entry point for the program. It takes an array of strings as an argument, but in this program, that argument is not used.
- Inside the main method, a new Scanner object called input is created to read input from the user.
- A double variable num is declared and initialized to 0.
- The program prompts the user to enter a double value using System.out.print and reads it using input.nextDouble().
- The Math.abs(num) method is used to determine the absolute value of the number entered by the user.
- The result of the Math.abs method is printed to the console using System.out.print.
Source Code
import java.util.*;
public class Absolute_Values
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double num = 0;
System.out.print("Enter The Number : ");
num = input.nextDouble();
System.out.print("Absolute Number is : " + Math.abs(num));
}
}
Output
Enter The Number : -639
Absolute Number is : 639.0