Skip to Content

Find absolute value of float, int, double and long using Math.abs

  1. /*
  2.   Find absolute value of float, int, double and long using Math.abs
  3.   This java example shows how to find absolute value of any double,
  4.   float, long or java int value using abs method of Math class.
  5. */
  6.  
  7. public class FindAbsoluteValueExample {
  8.  
  9.   public static void main(String[] args) {
  10.    
  11.     int i = 8;
  12.     int j = -5;
  13.    
  14.     /*
  15.      * To find absolute value of int, use
  16.      * static int abs(int i) method.
  17.      *
  18.      * It returns the same value if the agrument is non negative value, otherwise
  19.      * negation of the negative value.
  20.      *
  21.      */
  22.    
  23.      System.out.println("Absolute value of " + i + " is :" + Math.abs(i));
  24.      System.out.println("Absolute value of " + j + " is :" + Math.abs(j));
  25.    
  26.      float f1 = 10.40f;
  27.      float f2 = -50.28f;
  28.  
  29.     /*
  30.      * To find absolute value of float, use
  31.      * static float abs(float f) method.
  32.      *
  33.      * It returns the same value if the agrument is non negative value, otherwise
  34.      * negation of the negative value.
  35.      *
  36.      */
  37.     System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1));
  38.     System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2));
  39.    
  40.     double d1 = 43.324;
  41.     double d2 = -349.324;
  42.     /*
  43.      * To find absolute value of double, use
  44.      * static double abs(double d) method.
  45.      *
  46.      * It returns the same value if the agrument is non negative value, otherwise
  47.      * negation of the negative value.
  48.      *
  49.      */
  50.     System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1));
  51.     System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2));
  52.    
  53.     long l1 = 34;
  54.     long l2 = -439;
  55.     /*
  56.      * To find absolute value of long, use
  57.      * static long abs(long l) method.
  58.      *
  59.      * It returns the same value if the agrument is non negative value, otherwise
  60.      * negation of the negative value.
  61.      *
  62.      */
  63.     System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1));
  64.     System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2));
  65.    
  66.   }
  67. }
  68.  
  69. /*
  70. Output would be
  71. Absolute value of 8 is :8
  72. Absolute value of -5 is :5
  73. Absolute value of 10.4 is :10.4
  74. Absolute value of -50.28 is :50.28
  75. Absolute value of 43.324 is :43.324
  76. Absolute value of -349.324 is :349.324
  77. Absolute value of 34 is :34
  78. Absolute value of -439 is :439
  79. */