Return Absolute Difference of Two Integers in Java

06 May 2023 Balmiki Mandal 0 Core Java

Return Absolute Difference of Two Integers in Java

In Java, the absolute difference between two integers can be found using the Math.abs() method. Math.abs() is a static method that returns the absolute value of an integer. This method takes an int as its argument and returns its absolute value as an int. In other words, it takes the absolute difference of the two numbers and returns the result as an int.

The syntax of the Math.abs() method is:

int absDifference = Math.abs(int x - int y);

In the above example, x and y are two integers whose absolute difference needs to be found. The result of the Math.abs() method is stored in the int absDifference. Then, the result can be printed or used for further computation.

Here is an example of how to use Math.abs() to find the absolute difference between two integers:

//declare two integers
int x = 10;
int y = 8;

//find the absolute difference
int absDifference = Math.abs(x-y);

//print the result
System.out.println("Absolute difference between x and y is: " + absDifference);

The output of the above program will be:

Absolute difference between x and y is: 2

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.