Monday 6 June 2016

Number Class in Java

In this blog post we will learn about how to use number class in day -to-day coding.Number class is mostly using by the programmers.When we started work with numbers, we use primitive data types such as byte, int, long, double, etc.

Demo Example:

int i = 3000;
float f1 = 16.89;
byte b1 =23;

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are sub classes of the Number Class.The Number class is part of the java.lang package.














Number Sub classes:

The object of the wrapper class contains or wraps its respective primitive data type.converting primitive data types into object is called boxing, and this is taken care by the compiler. therefore while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class and the Wrapper class object will be converted back to a primitive data type, and this process is called unboxing.

Here is an example of boxing and unboxing:

public class NumberDemo  {

   public static void main(String args[]){
      Integer x = 70;             // boxing int to an Integer object
      x =  x + 10;               // unboxing the Integer to a int
      System.out.println(x); 
   }
}

O/P Result:

80

When x is assigned integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as integer.


Number Methods:

Here is the list of the various  methods supported by the subclasses of the Number class.


1 -xxxValue()

Converts the value of this Number object to the xxx data type and returned it.

2 -compareTo()

Compares this Number object to the argument.

3-equals()

Determines whether this number object is equal to the argument.

4-valueOf()

Returns an Integer object holding the value of the specified primitive.

5-toString()

Returns a String object representing the value of specified int or Integer.

6-parseInt()

This method is used to get the primitive data type of a certain String.

and the other methods so on....

7-abs()

8-ceil()

9-floor()

10-rint()

11-round()

12-min()
13-max().

14-exp()

15-log()

16-pow()

17-sqrt()

18-sin()

19-cos()

20-tan().

21-asin()

22-acos()

23-atan()

24-atan2()

25-toDegrees()

26-toRadians()

27-random()

No comments:

Post a Comment