Number methods in Java

In this module, we are going to discuss number methods in Java. This number methods belong to number class which is of abstract type and it is defined under java.lang package. These are the numbers present in Java Programming.

  • Byte
  • Integer
  • Long
  • Float
  • Double
  • Short

Syntax:

datatype var=number_varia_to_be_converted.datatypeValue()

Understanding of Number Methods in Java

The methods are defined based on these numbers mentioned above. The methods defined by numbers in java.lang are as follows:

  • byteValue(): it returns the passed argument in the number format of the Byte.
  • shortValue(): it returns the passed argument in the number format of the Short.
  • intValue(): it returns the passed argument in the number format of the Integer.
  • longValue(): it returns the passed argument in the number format of the Long.
  • floatValue(): it returns the passed argument in the number format of the Float.
  • doubleValue(): it returns the passed argument in the number format of the Double.

The following code gives a clear understanding of value() methods.

public class method{
    public static void main(String args[]) {
      Integer i=new Integer("32");
      Double d1=new Double("2334678.3263636");
      byte b=d1.byteValue();               //byte conversion
      short s=d1.shortValue();             //short conversion
      long l=d1.longValue();               //long conversion
      float f=i.floatValue();              //float conversion
      double d=i.doubleValue();            //double conversion
      System.out.println(b+" "+s+" "+i+" "+l+" "+f+" "+d);
    }
}

Output:

-42 24618 32 2334678 32.0 32.0

Explanation:

Byte and short values size are less than the allocated value, therefore, they have been internally converted to appropriate values. The float and double values they have converted integer value to their respective types. If we take the double value as 3209.3635 then we get byte value and short value as 3209.

https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html

Leave a Reply

Your email address will not be published. Required fields are marked *