Java Number – Explore the Different Number Methods with Syntax!

We use numbers in our everyday life since childhood, whether it be some calculation, score or something to measure, numbers make it all possible.

Numbers are something that can never leave our side, whether we like it or not. Similarly, it isn’t possible that we learn Java without learning about Numbers.

The most basic data type of any computer language is number. Generally while working with numbers in Java, we use primitive data types which are byte, short, int, long, float and double.

As we know that these data types are just data values and not class objects, sometimes we need numerical values in the form of objects. Java solves this problem by providing wrapper classes.

Java provides six numeric wrapper subclasses under the abstract class Number which is present in java.lang package.

Wrapper classes are part of Java’s standard library java.lang, which converts the primitive data types into an object.

These wrapper subclasses come under the umbrella of abstract class Number. These six wrapper classes which provide additional power to numbers in Java are:

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

The following diagram shows a hierarchical view of these wrapper classes:

wrapper class java

Java Number Class

In this article, we will discuss the Number Class in Java which wraps the value of numerical primitive data types into their corresponding objects. We will cover all the subclasses under this superclass Number.

The following table shows all the numeric data types with their corresponding wrapper class:

Numeric Datatype Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double

Autoboxing and Unboxing

The Java compiler automatically converts the numeric data types into an object of the respective wrapper class. This process of converting primitive data type into an object is called autoboxing and, the reverse process, that is, converting the object into primitive data types is called unboxing.

For example, converting an ‘int’ into an object of ‘Integer’ and ‘double’ into an object of ‘Double’ is called Autoboxing. While converting the object of ‘Integer’ and ‘Double’ class into ‘int’ and ‘double’ data type respectively is called Unboxing.

Code to understand Autoboxing and Unboxing:

package com.TechVidvan.JavaNumbers;
public class AutoandUnBoxing
{
  public static void main(String args[])
  {
      Integer operand1 = 5; // Autoboxing: boxes int datatype to an 	Integer object
      Double operand2 = 44.9; // Autoboxing: boxes double datatype to an Double object
      operand1 = operand1 + 10; //Unboxing: unboxes the Integer to a int
      operand2 = operand2 + 30; //Unboxing: unboxes the Double to a double
      System.out.println("Value of the operand1 is: "+operand1);
      System.out.println("Value of the operand2 is: "+operand2);
  }
}

Output:

Value of the operand1 is: 15
Value of the operand2 is: 74.9

Methods of Java Number Class

The Number Class comes with several methods that are useful for performing operations on numbers. We will discuss each of these methods in detail with the help of examples:

java number methods

1. type typeValue() method

This method converts the value of the object of Number class to the specified primitive number data type and returns it. Here type represents primitive number data types: byte, short, int, long, float, double.

Syntax of typeValue() method for each data type:

byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()

Code to illustrate typeValueMethod:

package com.TechVidvan.JavaNumbers;
public class typeValueMethodDemo
{
  public static void main(String[] args)
  {

  // Creating a Double Class object with value "45.13627"
    Double doubleVariable = new Double("45.13627");

  // Converting this Double(Number) object to different primitive data types
    byte byteVariable = doubleVariable.byteValue();
    short shortVariable = doubleVariable.shortValue();
    int integerVariable = doubleVariable.intValue();
    long longVariable = doubleVariable.longValue();
    float floatVariable = doubleVariable.floatValue();
    double doubleVariableObject = doubleVariable.doubleValue();

  //Printing the converted variables
    System.out.println("Converting double into byte: " + byteVariable);
    System.out.println("Converting double into short: " + shortVariable);
    System.out.println("Converting double into int: " + integerVariable);
    System.out.println("Converting double into long: " + longVariable);
    System.out.println("Converting double into float: " + floatVariable);
    System.out.println("Converting double into Double object: " + doubleVariableObject);
  }
}

Output:

Converting double into byte: 45
Converting double into short: 45
Converting double into int: 45
Converting double into long: 45
Converting double into float: 45.13627
Converting double into Double-object: 45.13627

Note: There may be a possible loss of precision while conversion. For example, we can note that the fraction part(“.13627”) has been left out while converting the Double-object into int data type.

2. int compareTo() method

This method compares the input argument with the Number object. It returns 1 (positive number) if the value of Number object is greater than the argument, -1 (negative number) if it is less than the value of argument and 0 if it is equal to the argument.

But both the argument and the number should be of the same type, then only they can be compared. The reference type can be a byte, double, float, long, or short.

Syntax of compareTo() method:

public int compareTo( NumberSubClass referenceName )
SubClassObject.compareTo(valueToBeCompared)

Code to illustrate compareTo() method:

package com.TechVidvan.JavaNumbers;
public class CompareToMethodDemo
{
  public static void main(String[] args)
  {
      // creating an Double Class object with value "12.55"
      Double doubleObject = 12.55;
    
      //initializing double variables 
      double comparisonValue1 = 8.66;
double comparisonValue2 = 12.55;
double comparisonValue3 = 15.98;
    
      // comparing value of doubleObject
System.out.println("Comparing 12.55 with 37.5:");

//we can directly pass the value of argument
System.out.println(doubleObject.compareTo(37.5));

      System.out.println("Comparing 12.55 with 6.66:");
      System.out.println(doubleObject.compareTo(comparisonValue1));
      System.out.println("Comparing 12.55 with 12.55:");
      System.out.println(doubleObject.compareTo(comparisonValue2));
      System.out.println("Comparing 12.55 with 15.98:");
      System.out.println(doubleObject.compareTo(comparisonValue3));
}

Output:

Comparing 12.55 with 37.5:
-1
Comparing 12.55 with 6.66:
1
Comparing 12.55 with 12.55:
0
Comparing 12.55 with 15.98:
-1

3. boolean equals(Object object) method

This method checks whether the Number object is equal to the argument (also of Number Type). Both Number object and argument may be of different types. It returns true if the values are equal, otherwise, it returns false.

Syntax of equals() method:

public boolean equals(Object object)
object1.equals(object2);

Code to illustrate equals() method:

package com.TechVidvan.JavaNumbers;
public class EqualsMethodDemo
{
public static void main(String[] args)
{
  // creating three Short Class objects
  Short shortObject1 = 15;
  Short shortObject2 = 4;
  Short shortObject3 = 4;

  // creating an Integer Class object
  Integer integerObject1 = 15;

  // creating an Double Class object
  Double doubleObject1= 28.65;
  System.out.println(shortObject1.equals(shortObject2));
  System.out.println(shortObject1.equals(integerObject1));
  System.out.println(shortObject2.equals(shortObject3));
  System.out.println(shortObject1.equals(doubleObject1));
}
}

Output:

false
false
true
false

Note: See even if the numeric values of Integer and Short object are the same (that is, 15), the method returns false because their types are not the same.

4. int parseInt() method

While working with strings, sometimes we need to convert a number represented in the form of string into an integer type. The method parseInt() is generally used to convert String to Integer in Java.

We can also pass the argument radix in this method which represents decimal, octal, or hexadecimal type as output. This method returns the primitive data type of a String.

Syntax of parseInt() method::

static Integer parseInt(int i)
static Integer parseInt(String s)
static Integer parseInt(String s, int radix)

Code to illustrate parseInt() method:

package com.TechVidvan.JavaNumbers;
public class ParseIntMethodDemo
{
  public static void main(String[] args)
  {
    // parsing different strings
    int intVariable1 = Integer.parseInt("567",8); 				//string to octal conversion
    int intVariable2 = Integer.parseInt("567"); //String to int
    int intVariable3 = Integer.parseInt("-AC", 16); //string to hexadecimal
    long longVariable = Long.parseLong("3615345721",10); //string to decimal 
    short shortVariable = Short.parseShort("216",8); // String to octal conversion
    double doubleVariable = Double.parseDouble("216");//String to double

    System.out.println(intVariable1);
    System.out.println(intVariable2);
    System.out.println(intVariable3);
    System.out.println(longVariable);
    System.out.println(shortVariable);
    System.out.println(doubleVariable);

   // NumberFormatException will occur because "TechVidvan" is not a parsable string
    int intVariable4 = Integer.parseInt("TechVidvan",16);

   // NumberFormatException will occur here(for octal(8),allowed digits are [0-7])
    int intVariable5 = Integer.parseInt("978",8);
  }
}

Output:

375
567
-172
3615345721
142
216.0
Exception in thread “main” java.lang.NumberFormatException: For input string: “TechVidvan” under radix 2
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at project1/com.TechVidvan.JavaNumbers.ParseIntMethodDemo.main(ParseIntMethodDemo.java:23)

5. String toString() method

This method is used to get the String object representation of any Number object. This method takes a primitive data type as an argument and returns a String object representing the primitive data type value.

There are three variants of this method-

  • toBinaryString(int i)
  • toHexString(int i)
  • toOctalString(int i)

Syntax of toString() method:

  1. String toString()
  2. String toString(int integerObject)

Code to illustrate toString() method:

package com.TechVidvan.JavaNumbers;
public class ToStringMethodDemo
{
  public static void main(String args[])
  {
    // creating integer object
    Integer integerObject = 25;
    System.out.println(integerObject.toString());
    System.out.println(Integer.toString(72)); //integer to string conversion

    //integer to binary string conversion
    System.out.println(Integer.toBinaryString(367));

    //integer to hex string conversion
    System.out.println(Integer.toHexString(367));

    //integer to an octal string conversion
    System.out.println(Integer.toOctalString(367)); }
}

Output:

25
72
101101111
16f
557

6. Integer valueOf() method

The valueOf method converts the value of an argument into the relevant Number Object. The argument can be any numeric primitive data type or String.

This method is a static method that can be called directly through the Integer class. The method can take two arguments, where one is a String or a primitive data type and the other is a radix.

Syntax of valueOf() method::

Integer valueOf(int i)
Integer valueOf(String stringValue)
Integer valueOf(String stringValue, int radix)

Code to illustrate valueOf() method:

package com.TechVidvan.JavaNumbers;
public class ValueOfMethodDemo
{
  public static void main(String args[])
  {
    // demonstrating valueOf(int integerObject) method
    Integer integerObject1 =Integer.valueOf(922);
    Double doubleObject = Double.valueOf(5.9);
    Float floatObject = Float.valueOf(80);
    System.out.println(integerObject1);
    System.out.println(doubleObject);
    System.out.println(floatObject);

    // demonstrating valueOf(String stringValue) method
    Integer integerObject2 = Integer.valueOf("444",16);
    Integer integerObject3 = Integer.valueOf("-953");
    System.out.println(integerObject2);
    System.out.println("\n" +integerObject3);

    // demonstrating valueOf(String stringValue,int radix) method
    Integer integerObject4 = Integer.valueOf("333",8);
    Long longObject = Long.valueOf("51688245",16);

    System.out.println("\n" +integerObject4);
    System.out.println(longObject);
  }
}

Output:

922
5.9
80.01092
-953219
1365803589

Apart from these methods, there are some more methods in Java.lang.Math, that are helpful for performing various operations on numbers. We will briefly look at each of these methods through the following table.

Method Description
abs() Returns the absolute value of the argument.
ceil() Returns the smallest integer that is greater than or equal to the argument in double format.
floor() Returns the largest integer that is less than or equal to the argument in double format.
min() Returns the smaller of the two arguments.
max() Returns the larger of the two arguments.
exp() Returns e, to the power of the argument.
log() Returns the natural logarithm of the argument.
pow() Returns the value of the first argument raised to the power of the second argument.
sqrt() Returns the square root of the argument.
random() Returns a random number
sin() Returns the sine of the specified double value.
cos() Returns the cosine of the specified double value.
tan() Returns the tangent of the specified double value.

Summary

Here we came to the end of our tutorial on Java Numbers. In this article, we learned about the abstract class number along with its subclasses in Java. We also discussed the different methods associated with the Number class with the help of their syntax and code.

I hope this article will help you to understand the complex codes related to numbers in Java.

Thank you for reading our article. Do share your feedback through the comment section below.