Write a Java program to convert a float value to absolute value


This Java program prompts the user to enter a float number, and then converts the number to its absolute value using a ternary operator. The result is printed to the console.

  • The program first creates a Scanner object called input to read user input from the console. It then prompts the user to enter a float number using the System.out.print statement and reads the user's input using the input.nextFloat() method. The entered number is assigned to the variable n.
  • The program then uses a ternary operator to calculate the absolute value of n by checking if n is greater than or equal to zero. If n is greater than or equal to zero, the absolute value is simply n. If n is negative, the absolute value is -n (the negation of n). The result is assigned to the variable abs_val.
  • Finally, the program prints both the original value of n and its absolute value abs_val to the console using System.out.println.

Note that the ternary operator is used to write a concise conditional expression that evaluates to one of two values based on a condition. In this case, the ternary operator replaces the use of an if statement to determine the sign of the input number. However, it's worth noting that the use of the ternary operator with floating-point numbers can sometimes result in unexpected behavior due to rounding errors, and so it may be safer to use the Math.abs() method instead.

Source Code

import java.util.*;
public class Float_Absolute
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a Float Number : ");
		float  n = input.nextFloat();  
		float abs_val = (n >= 0) ? n : -n;
		System.out.println("Given value : "+n);
		System.out.println("Convert Float to Absolute value : "+abs_val);
	}	
}

Output

Enter a Float Number : -84.921
Given value : -84.921
Convert Float to Absolute value : 84.921

Example Programs