
Float and double are two data types you can use when working with decimal numbers in Java.
Float:
It's a single-precision 32-bit IEEE 754 floating-point.
It's more about saving memory in large arrays of floating-point numbers.
When you need a large array of decimal numbers and precision is less critical,
floatis the right choice.
Example of declaring a float:
float number = 5.75f; // note the 'f' at the endDouble:
It's a double-precision 64-bit IEEE 754 floating point.
It offers a large range and is more precise compared to
float.Most of the time, when you're dealing with decimal numbers, you'll use
doubleunless there's a specific need for afloat.
Example of declaring a double:
double anotherNumber = 5.75;Here's how you might see them used in a simple Java program:
public class Main {
public static void main(String[] args) {
float piPrecision = 3.14f;
double piMorePrecision = 3.141592653589793;
System.out.println("Float Value: " + piPrecision);
System.out.println("Double Value: " + piMorePrecision);
}
}Both types are vital as you explore how Java handles numbers with decimals.
Remember that double is the default for decimal numbers unless you specifically tell Java to use float.
Hope this helps! Feel free to ask more questions as you learn.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer