Absolute Difference of two integers in Java

Table of Contents

In Java, we can calculate the absolute difference between two integers by subtracting the smaller integer from the larger one and then taking the absolute value of the result.

Let’s go through the steps to do this in Java.

Step 1: Declare the Variables

First, we need to declare two integer variables that we want to find the absolute difference between. For example:

int num1 = 10;
int num2 = 7;

Step 2: Find the Difference

Next, we need to subtract the smaller number from the larger one. To do this, we can use the Math.max() and Math.min() methods to find the larger and smaller numbers, respectively:

int diff = Math.abs(Math.max(num1, num2) - Math.min(num1, num2));

The Math.abs() method is used to ensure that the difference is always a positive value, regardless of which number is larger.

Step 3: Print the Result

Finally, we can print the result of the absolute difference calculation:

System.out.println("The absolute difference between " + num1 + " and " + num2 + " is " + diff);

This will output:

The absolute difference between 10 and 7 is 3

Putting it All Together

Here’s the complete Java code to find the absolute difference between two integers:

public class AbsoluteDifference {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 7;
        int diff = Math.abs(Math.max(num1, num2) - Math.min(num1, num2));
        System.out.println("The absolute difference between " + num1 + " and " + num2 + " is " + diff);
    }
}

This will output:

The absolute difference between 10 and 7 is 3

Conclusion

In this article, we went through the steps to find the absolute difference between two integers in Java. By subtracting the smaller number from the larger one and taking the absolute value of the result, we can always get a positive difference value.

Command PATH Security in Go

Command PATH Security in Go

In the realm of software development, security is paramount. Whether you’re building a small utility or a large-scale application, ensuring that your code is robust

Read More »
Undefined vs Null in JavaScript

Undefined vs Null in JavaScript

JavaScript, as a dynamically-typed language, provides two distinct primitive values to represent the absence of a meaningful value: undefined and null. Although they might seem

Read More »