Write a Java program to convert an integer value to absolute value


This Java program prompts the user to enter an integer 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 an integer number using the System.out.print statement and reads the user's input using the input.nextInt() 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.

Source Code

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

Output

Enter an Integer Number : -2653
Given value : -2653
Convert Integer to Absolute value : 2653

Example Programs