Arrays and Strings · Introduction to Java Programming

Float Class

Watch lectures

Float Class

1. Float vs Double (beginner)

float = 4-byte decimal (needs f!). double = 8-byte default (prefer it!). Float = wrapper. Use float for memory-huge arrays/GPU; double for marks/money-maths (or BigDecimal for exact money!).

2. Code — Suffix + Parse Proof

// float f = 3.14; // ERROR! (3.14 is double!)
float f = 3.14f; // f forces float (correct!)
Float obj = Float.valueOf("3.14"); // parse
System.out.println(obj + " max=" + Float.MAX_VALUE);
System.out.println(0.1f + 0.2f); // 0.30000004 (binary float error — NOT 0.3!)
System.out.println(Float.isNaN(0.0f / 0.0f)); // true (0/0 = NaN!)
System.out.println(Float.isInfinite(1.0f / 0.0f)); // true (+Infinity!)

3. Special Values (exam loves!)

Expression Result
1.0f/0 Infinity (NOT crash! integer 1/0 crashes!)
0.0f/0 NaN (not a number!)
NaN == NaN false (nothing equals NaN — use isNaN!)

4. Traps

  • Missing f: float x = 2.5; fails!
  • == on floats unreliable (0.1+0.2 != 0.3 binary!). Compare with epsilon: Math.abs(a-b) < 0.001.
  • Money? Use int paise or BigDecimal (never float!).

5. Exam Points

  • f suffix + NaN/Infinity + epsilon compare — 5 marks, frequent.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules