Course contentsShow
← Java
Lesson 39 of 2,8702. Variables and Primitive TypesFree lesson

Declaring and Initializing float and double Variables

Master the syntax for declaring float and double variables, including default values and proper initialization.

Declaring and Initializing float and double Variables

What you'll learn: How to properly declare and initialize Java's two floating-point types using correct syntax and literal notation.

The Core Idea

Just like you learned to declare int and long variables for whole numbers, you declare float and double variables for numbers with decimal points. The syntax follows the same pattern: type + name + optional initialization.

Declaring float Variables

The float type requires a special f or F suffix on decimal literals (similar to how long uses L):

float temperature;              // declared, default value is 0.0
float price = 19.99f;          // initialized with f suffix
float distance = 42.5F;        // uppercase F also works

Without the f suffix, Java treats the decimal as a double by default, which will cause a compilation error when assigning to float.

Declaring double Variables

The double type is Java's default floating-point type, so no suffix is needed (though you can use d or D if you want):

double balance;                 // declared, default value is 0.0
double pi = 3.14159;           // no suffix needed
double weight = 75.8d;         // optional d suffix

Default Values

Both float and double have a default value of 0.0 when declared as class-level variables (you'll learn about this distinction later). For now, always initialize your variables when you declare them.

Common Mistake

Forgetting the f suffix for float literals:

float rate = 5.5;   // ERROR: won't compile
float rate = 5.5f;  // CORRECT

Key Takeaway: Declare float with an f suffix on literals (float x = 1.5f;) and double without a suffix (double y = 1.5;). Both default to 0.0 when uninitialized.