Java Numbers – Number Methods with Syntax and Examples

In the previous article, we learned about the concept of Java Wrapper classes and why we need them during development. Java String class, Java Number class are all examples of these wrapper classes which convert a primitive datatype to an object of the class. Here in this article, we are going to talk about the Number class and its methods in Java programming.

Java Number class

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Number Class in Java

We have to note that the number class is not a real class but an abstract class. It has the following wrapper classes that define the functions inside it.

a. Integer
b. Byte
c. Double
d. Short
e. Float
f. Long

The number class is a part of the java.lang package.
You can see and remember that these are the same as the primitive data types we learned about in the previous articles. But all of these are individual classes that are signified by the capital letters starting each class name(This is a class naming convention).

The compiler automatically converts the primitive data type to an object and vice versa as and when required by a particular function or scope of the program. This is called Autoboxing and Unboxing. We will learn about them soon.

Why should you use a wrapper class instead of a primitive datatype?

Now, the question arises as to why you should use Wrapper Class objects when you can simply use primitive datatypes?
The answer lies in the use of these objects.

  • There are many methods that take an Object as an argument. We can use Wrapper class objects there. Eg-MAX_VALUE, MIN_VALUE.
  • There is also a need for manipulating and performing particular functions on a datatype. That is when objects can be used.
  • Interconversion methods such as binary to hexadecimal can be used by passing the particular number as an object.
  • There are particular constants that are provided by the number class which is useful while programming.

Methods of Java Number Class

There are a lot of classes that implement the abstract class but there are some methods that are common to all the classes. Some of them are explained below.

Methods of Number Class in Java

1. Value Method in Java

This method converts the value of the number object into the datatype mentioned. It has the syntax as:

<variable>.<datatype>Value();

After conversion it stores the value in a datatype which is primitive.

Java program to illustrate the use of Value method:

package com.dataflair.numberclass;
public class ValueMethod {
  public static void main(String[] args) {
    Integer num1 = new Integer("5");
    float f = num1.floatValue();
    double d = num1.doubleValue();

    System.out.println("The integer value converted to float is " + f);
    System.out.println("The integer value converted to double is " + d);

  }

}

Output

The integer value converted to float is 5.0
The integer value converted to double is 5.0

2. Java compareTo Method

The compareTo function compares a given object to a different object of the same type. If both the values are the same then the function returns 0. If the given number is less than the argument then it returns -1. Else it returns 1.

Its syntax is:

int compareTo(NumberClass ReferenceName);

Java program to illustrate the use of compareTo:

package com.dataflair.numberclass;
public class CompareToMethod {
  public static void main(String[] args) {
    Integer num1 = new Integer("5");
    System.out.println("comparing num1 with 10 is " + num1.compareTo(10));
    System.out.println("comparing num1 with 1 is " + num1.compareTo(1));

  }

}

Output

comparing num1 with 10 is -1
comparing num1 with 1 is 1

3. equals Method in Java

The equals method checks if the number and the argument passed through the method is not null and equal to the number. If both the numbers are equal, it returns true. If not, it returns false. They also have to be of the same type.

The syntax is:

boolean <variable>.equals(Reference)

Java program to illustrate the usage of equals method:

package com.dataflair.numberclass;
public class EqualsMethod {
  public static void main(String[] args) {
    Integer num1 = new Integer("5");
    Short s = new Short("5");
    Integer num2 = new Integer("5");
    System.out.println("Is the short value equal to num1? " + num1.equals(s));
    System.out.println("is the integer value equal to num1? " + num1.equals(num2));

  }

}

Output

Is the short value equal to num1? false
is the integer value equal to num1? true

4. parseInt Method in Java

This method converts the value of the String passed through it into a data type which is a primitive datatype which, in this case, is int. If we want to convert to other datatypes such as float or long we have to use parseFloat or parseLong.

The radix is the base of the string from which it is to be converted to decimal. Care should be taken that the string does not contain any digits which lie outside the scope of the radix mentioned. For example, if the radix is 2 which signifies a binary base then the string cannot have numbers other than 0 or 1. If it does the compiler will throw an exception.

There are two methods of using the parseInt method:

a. int Integer.parseInt(String,radix);
b. int Integer.parseInt(String);

When no radix is mentioned it has a default value of 10 which means all the strings passed without a radix would be converted to a decimal number.

Java program to illustrate the use of parseInt:

package com.dataflair.numberclass;
public class ParseIntMethod {
  public static void main(String[] args) {
    int num1 = Integer.parseInt("AB", 16);
    int num2 = Integer.parseInt("1001", 2);
    int num3 = Integer.parseInt("543"); //if no radix is mentioned it is converted to decimal. 

    System.out.println("num1 " + num1); //Hexadecimal converted to decimal
    System.out.println("num2 " + num2); //Binary converted to decimal
    System.out.println("num3 " + num3); //Direct conversion of string to decimal

  }

}

Output

num1 171
num2 9
num3 543

5. toString Method in Java

Java toString method is used for converting a numeric datatype to a string. This helps in returning the value of an object. Calling this method means, overriding the .toString() method. It is useful while printing the value of the object. Although while printing an object, the compiler automatically invokes the .toString() method.

It has four variations:

a. <variable>.toString()
b. Integer.toBinaryString(int i);
c. Integer.toHexString(int i);
d. Integer.toOctalString(int i);

The variation where an integer value i is passed returns a decimal String object of value i.

Java program to illustrate the use of toString method:

package com.dataflair.numberclass;
public class ToStringMethod {
  public static void main(String[] args) {
    Integer int1 = new Integer("167");
    System.out.println("Converting to decimal string" + int1.toString());
    System.out.println("Converting to octal string " + Integer.toOctalString(int1));
    System.out.println("Converting to Hexadecimal string " + Integer.toHexString(int1));

  }

}

Output

Converting to decimal string167
Converting to octal string 247
Converting to Hexadecimal string a7

6. valueof Method in Java

This method returns the number object which is relevant. Simply put, this method converts the argument passed through it to an Integer object. However if there is a radix mentioned in the argument, the respective data is converted into the base of the radix first and then converted to an Integer object. This is a static method.

There are three alternative ways to use this method:
a. valueOf(int i)- This returns an Integer object which represents the integer value.
b. valueOf(String i)- This returns an Integer representation of the string passed
c. valueOf(String i,radix)-This returns an Integer representation of the string passed of base radix.

Java program to illustrate the use of valueOf:

package com.dataflair.numberclass;
public class ValueOfMethod {
  public static void main(String[] args) {
    Integer int1 = new Integer("167");
    System.out.println("Using Integer.valueOf(int1) is " + Integer.valueOf(int1));

    System.out.println("Using Integer.valueOf(\"542\") is " + Integer.valueOf("542"));

    System.out.println("Using Integer.valueOf(\"AB2\") is " + Integer.valueOf("AB2", 16));

  }

}

Output

Using Integer.valueOf(int1)is 167
Using Integer.valueOf(“542”) is 542
Using Integer.valueOf(“AB2”)is 2738

Autoboxing and Unboxing in Java

Java Autoboxing is the process of converting a primitive datatype to its specific wrapper class object. This is useful when:

  • Primitive datatype is passed as an argument to a method that expects an object.
  • Variable is assigned to the corresponding wrapper class.

Java Unboxing is the reverse of autoboxing. It is the process of converting the Wrapper class object into its corresponding primitive datatype. This is useful when:

  • Wrapper class object is used where a primitive datatype is expected.
  • It is assigned to a primitive variable.

Java program to illustrate the concept of Autoboxing and Unboxing:

package com.dataflair.numberclass;
public class AutoboxingUnboxing {
  public static void main(String[] args) {
    System.out.println("Understanding Autoboxing");
    //This is a primitive datatype
    Integer i = 10;
    //Autoboxing of the primitive value 10 to an object

    System.out.println("The integer is " + i);

    System.out.println("Understanding Unboxing");

    Integer num = new Integer(98);
    int unboxnum = num;
    //Unboxing of the num object to a primitive datatype int
    System.out.println("The value of the integer is " + unboxnum);
  }
}

Output

Understanding Autoboxing
The integer is 10
Understanding Unboxing
The value of the integer is 98

Summary

In this Java Tutorial, we learnt about Java Number Class. We learnt about a lot of methods of the Integer class which have specific functions. These functions save us a lot of time while doing minute manipulations such as converting the bases and so on.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.