Skip to main content Skip to docs navigation
TechSpiderTutorials

java.lang.Double class in java

java.lang.Double

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

Creating Double Objects

Using the Double constructor:

double pi = 3.14159;
Double piObject = new Double(pi);

Using the valueOf method:

String piString = "3.14159";
 Double piObject = Double.valueOf(piString);

The valueOf method is a static method that parses a String representation of a double value and returns a corresponding Double object. This is useful for converting user input or data from files into double values.

Double Class Methods

The Double class offers various methods for working with double values. Here are some commonly used ones:

doubleValue():

Returns the primitive double value stored in the Double object.

System.out.println(piObject.doubleValue());
 // Output: 3.14159

toString():

Converts the Double object to its String representation.

String piString = piObject.toString();
System.out.println(piString);
 // Output: 3.14159
isNaN() and isInfinite(): Check if the value is Not-a-Number (NaN) or positive/negative infinity, respectively.
Double nanValue = Double.valueOf("abc");
if (nanValue.isNaN()) {
  System.out.println("The value is NaN");
}

Fields: MAX_VALUE and MIN_VALUE:

These are static final fields representing the largest and smallest representable finite double values, respectively.

System.out.println(Double.MAX_VALUE);
// Output: 1.7976931348623157E308

Example: Calculating Area of a Circle

public class CircleArea {

  public static void main(String[] args) {
    double radius = 5.0;
    Double radiusObject = new Double(radius);

    double area = Math.PI * radiusObject.doubleValue() * radiusObject.doubleValue();

    System.out.println("Area of the circle: " + area);
  }
}