float Keyword in Java
The float keyword in Java is used to declare variables that hold single-precision 32-bit IEEE 754 floating point numbers. It's a primitive data type mainly used when memory savings are more critical than absolute precision.
Why Use float Instead of double?
While double is the default for floating point numbers due to its higher precision, float can be beneficial in scenarios like:
- Memory-constrained applications (e.g., mobile or embedded systems)
- Large arrays of decimal values where precision can be compromised
Syntax
float variableName = value;
Important Notes
- Values assigned to a
floatmust end withforFto indicate it’s a float literal. - Without the suffix, a decimal value is treated as a
doubleby default.
Example: Declaring a Float Variable
public class FloatExample {
public static void main(String[] args) {
float price = 19.99f;
System.out.println("The price is: " + price);
}
}
The price is: 19.99
Assigning Double to Float (with Casting)
Since double has higher precision, assigning it to a float without explicit casting will cause a compile-time error.
public class FloatCasting {
public static void main(String[] args) {
double d = 45.6789;
float f = (float) d;
System.out.println("Float value after casting: " + f);
}
}
Float value after casting: 45.6789
Default Value of float
When declared as an instance variable without initialization, the default value of a float is 0.0f.
public class DefaultFloatValue {
static float temperature;
public static void main(String[] args) {
System.out.println("Default float value: " + temperature);
}
}
Default float value: 0.0
Using float in Arithmetic Operations
Float values behave like you'd expect in arithmetic expressions. But remember, due to precision limits, some results may not be exact.
public class FloatMath {
public static void main(String[] args) {
float a = 10.5f;
float b = 4.2f;
float sum = a + b;
System.out.println("Sum: " + sum);
}
}
Sum: 14.7
Precision Limitations
Float values are less precise than double, often accurate up to 6-7 decimal digits. Let's look at a precision test:
public class FloatPrecision {
public static void main(String[] args) {
float f1 = 1.123456789f;
System.out.println("Float value: " + f1);
}
}
Float value: 1.1234568
Common Mistake: Missing 'f' Suffix
New learners often forget the 'f' suffix and get a compile-time error.
public class FloatError {
public static void main(String[] args) {
float value = 3.14; // Compile-time error
}
}
Fix: Use float value = 3.14f;
Comments
Loading comments...