float
About
Definition: The
floatdata type is a primitive data type in Java used to represent a 32-bit single-precision floating-point number. It is mainly used for saving memory in large arrays of floating-point numbers where precision is not a critical concern.Size: Occupies 4 bytes (32 bits) in memory.
Value Range: Approximately
1.4E-45to3.4E+38for positive values (from-3.4E+38to3.4E+38for negative and positive values combined), with about 6-7 decimal digits of precision.Default Value: The default value of
floatis0.0f.Wrapper Class: The wrapper class for
floatisFloat, located injava.lang.
Characteristics of float
floatFloating-Point Representation:
floatis used to represent numbers that require fractional values but where memory efficiency is a concern.Memory Usage: It consumes 4 bytes (32 bits) of memory, which is smaller than
double, which uses 8 bytes (64 bits).Precision:
floathas a precision of about 6-7 decimal places, which is less thandouble, which can represent up to 15 decimal places. It is suitable when precise accuracy is not crucial.Scientific Notation:
floatvalues can be represented in scientific notation, such as3.14e2, which represents314.0.IEEE 754 Standard:
floatin Java follows the IEEE 754 standard for floating-point arithmetic. It includes special values likeNaN(Not-a-Number),Infinity, and-Infinity.Promotion in Expressions: If a
floatis mixed with adouble, thefloatis promoted to adoublein arithmetic expressions, asdoublehas a larger range and higher precision.Performance Considerations:
floatis generally faster and uses less memory compared todouble, but its lower precision may result in rounding errors in calculations.Avoiding Precision Loss: For calculations requiring higher precision,
doubleis often preferred overfloat. But for memory-constrained applications (e.g., graphics, scientific calculations),floatis useful.Memory Usage: A
floatoccupies 4 bytes (32 bits). This is smaller compared todouble's 8 bytes, makingfloatmore memory-efficient.
Operations with float
floatArithmetic and Logical Operations
Operation
Example
Description
Arithmetic Operations
float sum = a + b;
Addition, subtraction, multiplication, division.
Comparison Operations
a == b, a > b, etc.
Compares two float values.
Bitwise Operations
Not supported directly on float
float does not support bitwise operators like &, `
Conversion Methods
Conversion
Method
Example
float to String
String.valueOf(float)
String.valueOf(12.34f) → "12.34"
String to float
Float.parseFloat(String)
Float.parseFloat("12.34") → 12.34f
float to double
Implicit conversion
double result = 12.34f;
double to float
Explicit cast (float)
(float) 12.34 → 12.34f
Wrapper Class Example (Float)
Float)Method
Description
Float.valueOf(float f)
Returns a Float object for the given float value.
Float.parseFloat(String s)
Parses the string argument as a float.
Float.toString(float f)
Converts float to its String representation.
Float.isNaN(float f)
Checks if the float value is NaN.
Float.isInfinite(float f)
Checks if the float value is positive or negative infinity.
Common Mistakes
Loss of Precision: Since
floathas only about 6-7 decimal digits of precision, rounding errors can occur in calculations that require higher precision. For example:float num1 = 0.1f; float num2 = 0.2f; System.out.println(num1 + num2); // Output might not be exactly 0.3Mixing with
double:floatvalues are automatically promoted todoublein expressions that involve bothfloatanddouble. This could result in unnecessary memory usage or unexpected results if not carefully managed.Comparison with
NaN:NaN(Not a Number) is not equal to any number, including itself. So, comparingNaNto any value directly may not behave as expected:float nanValue = Float.NaN; System.out.println(nanValue == nanValue); // Output: false
Examples
Basic Example
public class FloatExample {
public static void main(String[] args) {
float num1 = 10.5f;
float num2 = 20.25f;
// Arithmetic operations
float sum = num1 + num2;
System.out.println("Sum: " + sum); // Sum: 30.75
// Comparing values
System.out.println("Is num1 greater than num2? " + (num1 > num2)); // Is num1 greater than num2? false
// Casting
int smallerValue = (int) num1; // Cast float to int
System.out.println("Casted Value: " + smallerValue); // Casted Value: 10
}
}Using float in Arrays
float in Arrayspublic class FloatArrayExample {
public static void main(String[] args) {
float[] floatArray = {10.5f, 20.25f, 30.75f};
for (float value : floatArray) {
System.out.println(value); // 10.5, 20.25, 30.75
}
}
}Converting float to String
float to Stringpublic class FloatConversion {
public static void main(String[] args) {
float num = 12.34f;
String str = Float.toString(num);
System.out.println("Float as String: " + str); // Float as String: 12.34
}
}Using float in Streams
float in Streamsimport java.util.stream.FloatStream;
public class FloatStreamExample {
public static void main(String[] args) {
float[] values = {1.2f, 3.4f, 5.6f, 7.8f};
float average = FloatStream.of(values)
.average()
.orElse(0.0f);
System.out.println("Average: " + average); // Average: 4.5
}
}Wrapper Class Example
public class FloatWrapperExample {
public static void main(String[] args) {
String strValue = "12.34";
float parsedValue = Float.parseFloat(strValue);
System.out.println("Parsed Value: " + parsedValue); // Parsed Value: 12.34
float minValue = Float.MIN_VALUE;
float maxValue = Float.MAX_VALUE;
System.out.println("Min Value: " + minValue); // Min Value: 1.4E-45
System.out.println("Max Value: " + maxValue); // Max Value: 3.4028235E38
}
}Last updated