Java Double Class

Introduction

The Double class in Java is a wrapper for the primitive type double. It provides methods for converting and manipulating double values and handling double precision arithmetic.

Table of Contents

  1. What is Double?
  2. Creating Double Instances
  3. Common Methods
  4. Examples of Double
  5. Conclusion

1. What is Double?

Double is a final class that wraps a double value in an object. It offers methods for converting between double and String, performing numerical operations, and handling special double values.

2. Creating Double Instances

You can create Double instances in several ways:

  • Using the Double constructor: new Double(double value) or new Double(String value)
  • Using the Double.valueOf(double value) or Double.valueOf(String value) methods

3. Common Methods

  • doubleValue(): Returns the value of this Double as a primitive double.
  • toString(): Returns a String representation of the double value.
  • parseDouble(String s): Parses a String to a primitive double.
  • isNaN(): Checks if the Double value is NaN (Not-a-Number).
  • isInfinite(): Checks if the Double value is infinite.
  • compare(Double d1, Double d2): Compares two Double objects.

4. Examples of Double

Example 1: Creating Double Instances

This example demonstrates how to create Double instances using constructors and valueOf methods.

public class DoubleInstanceExample {
    public static void main(String[] args) {
        Double d1 = new Double(10.5);
        Double d2 = Double.valueOf(20.5);
        Double d3 = Double.valueOf("30.5");

        System.out.println("d1: " + d1);
        System.out.println("d2: " + d2);
        System.out.println("d3: " + d3);
    }
}

Output:

d1: 10.5
d2: 20.5
d3: 30.5

Example 2: Parsing a String to double

This example shows how to parse a String to a primitive double using parseDouble.

public class ParseDoubleExample {
    public static void main(String[] args) {
        double d1 = Double.parseDouble("50.5");
        double d2 = Double.parseDouble("100.75");

        System.out.println("d1: " + d1);
        System.out.println("d2: " + d2);
    }
}

Output:

d1: 50.5
d2: 100.75

Example 3: Checking NaN and Infinity

In this example, we demonstrate how to check for NaN and infinity.

public class NaNInfinityExample {
    public static void main(String[] args) {
        Double d1 = Double.NaN;
        Double d2 = Double.POSITIVE_INFINITY;

        System.out.println("d1 is NaN: " + d1.isNaN());
        System.out.println("d2 is Infinite: " + d2.isInfinite());
    }
}

Output:

d1 is NaN: true
d2 is Infinite: true

Conclusion

The Double class in Java is a useful wrapper for the primitive double type. It provides methods for converting, manipulating, and handling double values.

Leave a Comment

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

Scroll to Top