Like the int
primitive data type, double
is also very commonly used. Most of the time, you will use int
for whole numbers and double
for numbers with decimal points (rational or irrational). Double is also known as double-precision floating point. This means it has twice as many bits as float
, meaning a double
is more accurate than a float
. Let's review the code below to see how double
variables are declared and used.
package exlcode;
public class DoubleDataTypeExample {
// double is any real number between -1.7E+308 and 1.7E+308
public static double exampleVariableOne = 3.1415;
public static double exampleVariableTwo = -0.002;
public static double exampleVariableThree = 1.7E+250;
public static void main(String[] args) {
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
System.out.println(exampleVariableThree);
}
}
As with floats, doubles may have the character 'd' or 'D' at the end of the number to tell the program that the number is a double
. Similar to a float
datatype, the default value for double
is "0.0". Doubles have one of the largest ranges of numbers compared to the other primitive data types.
Although a double
is more accurate than float
, it is still not recommended for currency as it is not precise enough to calculate strict numbers of this kind.