Java Double – Tutorial With Programming Examples

This tutorial will explain primitive data type Java Double. We will also discuss related classes like Java BigDecimal and DecimalFormat Class with examples:

In this tutorial, we will explore the double data type with the help of syntax and programming examples.

Java decimal format and big decimal classes are explained here with some frequently asked questions that will help you in understanding the double data type clearly.

=> Take A Look At The Java Beginners Guide Here.

Java double

Java Primitive Types

As we all know, Java has eight primitive types i.e. int, short, long, byte, float, double, char, and boolean. The Java double is one of the primitive data types whose width and range is more than float.

Primitive TypesWidth (bits)Range
double644.9e-324 to 1.8e+308

Java Double

Java double is used to represent floating-point numbers. It uses 64 bits to store a variable value and has a range greater than float type.

Syntax:

// square root variable is declared with a double type.
double sqrt;

Java Double Example

In this example, we are calculating the square root of the area of a rectangle. We have taken length and breadth as integer and calculated the area which is of type integer.

As the square root is most likely to give you decimal value, we declared the variable Area_sqrt as double and calculated the square root.

public class doubleExample {

	public static void main(String[] args) {
		int length=15, breadth=25;
		int area;
		area = length*breadth;
		
		// calculating area of the rectangle
		System.out.println("Area of rectangle is " + area);
		
		// declared a varibale which will store the square root
		double Area_sqrt;
		
		// calculating square root of Area of the rectangle
		Area_sqrt = Math.sqrt(area);
		System.out.println("Square root of area is " +Area_sqrt);
		
	}
}

Output

Java double example

Java DecimalFormat

Java has a special class called DecimalFormat that is used to format the numbers. This formatting is customizable.

In the below example, we have defined a pattern delimited by comma ‘,’ and a decimal number of type double. Using this pattern or format, we are going to display our input number.

We have passed the pattern into the Decimal format class and we have formatted the output using the reference ‘df’.

import java.text.DecimalFormat;

public class ExampleFormat {
   public static void main(String[] args) {
	   	
	  // defining a format in which number will be displayed
      String formatter = "##,###,###.##";
      
      // initialized the decimal number
      double num = 12345678.12;
      
      // passed the pattern into the Decimal format class
      DecimalFormat df = new DecimalFormat(formatter);
      
      // printed the formatted number
      System.out.println("The formatted number is: " +df.format(num));
      
   }
}

Output

Java Decimal Format

Java BigDecimal

This is again a special Java class that provides simple arithmetic operations on the number (add, subtract, multiply and divide), rounding off the result, format conversion, and so on.

Let’s look at the below example to understand this better.

Rounding off the number

In the below example, we have demonstrated the difference between the simple subtraction of decimal and the subtraction through the Big-Decimal class.

We have initialized two double variables and calculated the difference between their values. Again we have initialized two variables using Big-Decimal class with the same value and calculated their difference.

Finally, we printed both the values and you can see the difference between them. The calculated value of Big Decimal was automatically rounded-off.

import java.math.BigDecimal;

public class example {

	public static void main(String[] args) {
		
		// Initialized two double numbers
		
		double length1 = 1.06;
		double breadth1 = 1.07;
		
		// Subtracting length and breadth
		double sub = breadth1-length1;
		System.out.println("Simple Subtraction = " +sub);
		
		// Initialized two big decimal numbers with same value
		BigDecimal length2 = new BigDecimal("1.06");
		BigDecimal breadth2 = new BigDecimal("1.07");		

// Subtracting length and breadth
		length2 = breadth2.subtract(length2); 
        System.out.println("Big Decimal Subtraction = " + length2); 
		
	}
}

Output

Java Big Decimal

Frequently Asked Questions

Q #1) How many bytes does a double type take?

Answer: 8 bytes.

Q #2) What is MathContext in Java?

Answer: The MathContext is a class in Java that specifies the rounding-off number mode and precision. It provides immutable objects and is also responsible for imposing certain rules for the operators that are implemented by Big Decimal class.

The rules are:

RoundingMode.CEILING,
RoundingMode.DOWN,
RoundingMode.FLOOR,
RoundingMode.UP

In the below example, we have initialized a double variable and set different rules of rounding the digits. This works in accordance with the output specifier that we have passed.

For example,  In the first print statement, we are calculating the ceiling function where we have passed ‘3’ as an output specifier. This means that the output will have three digits. Likewise, in the last statement, we have passed ‘1’ so the output will contain 1 digit.

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class example {
	public static void main(String[] args) {
		
		double d = 3.14;		

                // Rounded off to the upper limit, the output will contain 3 digit
		System.out.println(new BigDecimal(d, new MathContext(3,
 RoundingMode.CEILING)));
		
		// Rounded off to the lower limit, the output will contain 3 digit
		System.out.println(new BigDecimal(d, new MathContext(3,
 RoundingMode.DOWN)));
		
		/*
		 *  Rounded off to the previous integer (discards the decimal
 value)
		 *  The output will contain 1 digit
		 */
		System.out.println(new BigDecimal(d, new MathContext(1,
 RoundingMode.FLOOR)));
		
		/*
		 *  Rounded off to the next integer (discards the decimal and 
increments integer)
		 *  The output will contain 1 digit
		 */
		System.out.println(new BigDecimal(d, new MathContext(1,
 RoundingMode.UP)));
	}
}

Output

MathContext - Java

Q #3) Is Java Big Decimal immutable?

Answer: Yes. Every time when we do a certain operation in Big Decimal, they return a new object instead of modifying the already created objects.

Q #4) What is the difference between float and double?

Answer: Enlisted below are the differences between float and double.

FloatDouble
It represents single-precision numbers.It represents double-precision numbers.
Width is 32 bits and the range is 1.4e–045 to 3.4e+038Width is 64 bits and the range is 4.9e–324 to 1.8e+308
It contains 7 digits.It contains between 15-16 digits.
Useful in currency conversion operations.Useful in sin(), cos(), sqrt() as the return type is double.
Slower than double precision.On modern processor which are built to perform long mathematical operations, double precision is way faster.

Q #5) What is a Math class?

Answer: A Math class is a class in Java that contains all the methods that are used in mathematical operations. It has two double constants i.e. E (2.72) and pi(3.14).

For example, sin(), cos(), tan() methods of trigonometry. sqrt(), log(), pow() methods of exponential. A programming example on pow() is already covered above (Java double example).

Conclusion

In this tutorial, we have explained the double primitive type with an appropriate example. We have also included DecimalFormat and BigDecimal Java with programs.

Frequently-asked questions are also included in various areas of the double type such as range, width, size, Math class, etc.

Upon going through this tutorial, you will be able to understand the double type in detail and you will be able to use these concepts in writing your own logic on arithmetic operations.

=> Read Through The Easy Java Training Series.