Wednesday, October 16, 2013

Number Class

Insurance, Loans,Mortgage,Attorney, Credit, Lawyer, Donate, Degree, Hosting, Claim, Conference Call, Trading, Software, Recovery, Transfer, Gas/Electricity, Classes, Rehab, Treatment, Cord Blood,


Number class

When working with numbers, most of the time you use the primitive types in your code.
For example:
int i = 500;
float gpa = 3.65f;
byte mask = 0xff;
However, in development, we come across situations where we need to use objects instead of primitive data types. In-order to achieve this Java provides wrapper classes for each primitive data type.

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive is used when an object is required, the compiler boxes the primitive type in its wrapper class. Similarly, the compiler unboxes the object to a primitive as well. The Number is part of the java.lang package.

There are three reasons that you might use a Number object rather than a primitive:

  • As an argument of a method that expects an object (often used when manipulating collections of numbers).
  • To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
  • To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary)
Boxing and UnBoxing
boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Example of boxing :
class BoxintExample {

    public static void main(String args[]) {
      int x = 10;
      Integer integer = x;
        System.out.println(integer);
    }
}
Output is :- 10

Example of UnBoxing :
class UnBoxintExample {

    public static void main(String args[]) {
      int x = 10;
      x = x+10;
    }
}
Output is 10


No comments:

Post a Comment