⬅ Previous Topic
Java finally KeywordNext Topic ⮕
Java for Keyword⬅ Previous Topic
Java finally KeywordNext Topic ⮕
Java for Keywordfloat
Keyword in JavaThe 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.
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:
float variableName = value;
float
must end with f
or F
to indicate it’s a float literal.double
by default.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
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
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
float
in Arithmetic OperationsFloat 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
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
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;
⬅ Previous Topic
Java finally KeywordNext Topic ⮕
Java for KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.