Java abs() Method

Math.abs() method gives the absolute value of the passed argument. This method accepts arguments of type  int, float, long, double.

Avaliable methods

int abs(int a)
float abs(float a)
long abs(long a)
double abs(double a)

 

Simple Example


package com.programtalk.beginner.tutorial;
public class AbsExample { 

   public static void main(String args[]) {
      int a = -10;
      System.out.println(Math.abs(a));
      
      int pa = 11;
      System.out.println(Math.abs(pa));
      
      double d = -20;
      System.out.println(Math.abs(d));

      double pd = 21;
      System.out.println(Math.abs(pd));
      
      long l = -30;
      System.out.println(Math.abs(l));

      long pl = 31;
      System.out.println(Math.abs(pl));
      
      float f = -40;
      System.out.println(Math.abs(f));
      
      float pf = 41;      
      System.out.println(Math.abs(pf));     
   }
}

output:

10
11
20.0
21.0
30
31
40.0
41.0

 

Real World Example

Problem

I need the difference between two dates in minutes. The result should be always a positive number.

Solution

So here is my utility method taking advantage of this abs() method.


public static long getDiffMinutesBetweenDates(Date d1, Date d2)
{
	long startTime = d1.getTime();
	long endTime = d2.getTime();
	long diffTime = startTime - endTime;
	return Math.abs(TimeUnit.MILLISECONDS.toMinutes(diffTime)); 
}

 

 

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.