The double Data Type - Java Language Basics

Java examples for Language Basics:double

Introduction

Java double data type uses 64 bits to store a floating-point number in the IEEE 754 format.

A double literal may optionally end with d or D, for example, 12.12d.

The suffix d or D is optional in double literals.

both 12.12 and 12.12d represent the same double literal.

A double literal can be expressed in the following two formats:

  • Decimal number format
  • Scientific notation
double d1 = 8D 
double d2 = 8.; 
double d3 = 8.0; 
double d4 = 8.D; 
double d5 = 7128.981267; 
double d6 = 45.12;  

You can also use scientific notation to express double literals.

double d1 = 32.5E-1; 
double d2 = 0.325E+1; 
double d3 = 0.325E1; 
double d4 = 0.0325E2; 
double d5 = 0.0325e2; 
double d6 = 32.5E-1D; 
double d7 = 0.325E+1d; 
double d8 = 0.325E1d; 
double d9 = 0.0325E2d; 
  

The following table lists these constants and their meanings.

double Constants Meaning
Double.POSITIVE_INFINITY Positive infinity of type double
Double.NEGATIVE_INFINITY Negative infinity of type double
Double.NaN Not a Number of type double
Double.MAX_VALUE The largest positive value that can be represented in a double variable.
Double.MIN_VALUE The smallest positive value greater than zero that can be represented in a double variable.

The value of all integral types (int, long, byte, short, char) and float can be assigned to a variable of the double data type without using an explicit cast.

int num1 = 15000; 
double salary = num1;             // Ok. int to double assignment 
salary = 12455;                   // Ok. int literal to double 
double bigNum = Double.MAX_VALUE; // Assigns the maximum double value 
bigNum = 1226L;                   // Ok, long literal to double 
double justAChar = 'A';           // Ok. Assigns 65.0 to justAChar 
double dInf = Double.POSITIVE_INFINITY;  // Ok. Assigns positive infinity to dInf variable 
double dNan = Double.NaN;  // Ok. Assigns Not-a-Number to dNan variable 
double dTooBig = 1.8E308;  // A compile-time error. to large
double dTooSmall = 4.9E-325;  // A compile-time error. too small
  

A double value must be cast to the integral type (int, long, byte, short, or char) when assigning.

int num1 = 10; 
double salary = 10.0; 
num1 = salary;      // A compile-time error. Cannot assign double to int 
num1 = (int)salary; // Now Ok.

Related Tutorials