Number Class


Normally, when we work with numbers, we use primitive data types such as byte, int, long, double, etc.:

   int       i = 5000;
   float   gpa = 13.65;
   double mask = 0xaf;

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. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number, which is part of the java.lang package. The object of the wrapper class contains or wraps its respective primitive data type. The following is an example of boxing and unboxing:

 public class Test {
   public static void main( String args[ ] ) {
     Integer x = 5;              // Boxes int to an Integer object.
             x = x + 10;         // Unboxes the Integer to an int.
     System.out.println( x );    // Output: 15
   }
 }

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

MyPrime.java (checking whether a number is prime)

 public class MyPrime {
   public static void main( String[ ] args ) {
     Integer number = ;
     Boolean prime  = true;

     if ( number > 1 )
       for ( int i = 2; i <= number / 2; i++ )
         // If the number is perfectly divisible, it is not prime.
         if ( number  i == 0 ) {
           prime = false;
           break;
         }
     if ( prime )
       System.out.println( number + " is prime."     );
     else
       System.out.println( number + " is NOT prime." );
   }
 }
       




      What did the pirate say when he turned 80?    
      Aye Matey.