A float represents decimal (floating-point) numbers in Java
- It uses 32 bits (4 bytes) of memory
- It can store values approximately in the range: 1.4E-45 to 3.4028235E38
This makes float useful when you need decimal numbers but want to save memory.
Declaring and using float
By default, Java treats decimal numbers as double. Adding F (or f) tells Java: “This number is a float.”
float count = 20.1F; // Must end with F or f
float temperature = -9.5F;
float vs double
Java has two decimal types:
| Type | Size | Precision | Common use |
| float | 4 bytes | Less precise | Graphics, sensors, games, low-memory systems |
| double | 8 bytes | More precise | Default choice for most calculations |
Note: Use double unless you specifically need float
Primitive type
float is a primitive data type.
- It stores its actual value directly in memory
- It does not store a reference to an object
- It has no methods
Changing float values
Primitive types have no internal state. Primitive types have no internal state.
float a = 15.2F;
a = 20.7F; // 15.2F is replaced by 20.7F
Wrapper class: Float
Even though float itself has no methods, Java provides the Float wrapper class. This allows you to:
- Convert values
- Compare floats safely
- Access constants like max/min values
Useful Float constants
| Constant | Example | Result |
| MAX_VALUE | Float.MAX_VALUE | Returns largest possible float value (≈ 3.4028235E38) |
| MIN_VALUE | Float.MIN_VALUE | Returns Smallest positive float value (≈ 1.4E-45) |
| SIZE | Float.SIZE | Returns size of a float in bits (32) |
| BYTES | Float.BYTES | Returns size of a float in bytes (4) |
Converting values
Converting numeric String to float. If the string is not numeric (e.g. "hello"), Java throws aNumberFormatException.
float num = Float.parseFloat("123.5"); // Returns 123.5
Converting a float to a String
String text = Float.toString(42.5F); // Returns "42.5"
Comparing Float values
compare(float a, float b)
int result = Float.compare(1.5F, 2.5F);
compareTo(Float other)
Float x = 10.0F;
Float y = 12.2F;
x.compareTo(y);
Both compare and compareTo return these values:
0→ if values are equal-1→ if first is less than second1→ first is greater than second
equals(Object obj)
Float x = 10.0F;
Float y = 10.0F;
x.equals(y); // true
Math helper methods
| Method | Example | Result |
| max(float a, float b) | Float.max(1F, 2F) | Returns the larger value |
| min(float a, float b) | Float.min(1F, 2F) | Returns the smaller value |
| sum(float a, float b) | Float.sum(1F, 2F) | Returns the sum of the two values |
Summary
floatstores decimal numbers using 4 bytes- Must use
Fwhen assigning values - It’s a primitive type
- Use
Floatwrapper class methods for conversions, comparisons, and constants - Prefer
doubleunless you needfloat
Leave a Reply