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

Declaration and Initialization in One Statement

Combining declaration and initialization for cleaner code and immediate usability of variables.

Declaration and Initialization in One Statement

What you'll learn: How to combine variable declaration and initialization into a single, cleaner line of code.

The Core Idea

So far, you've seen that you can declare a variable on one line and initialize it on another:

int age;
age = 25;

But Java allows you to combine both steps into one statement, making your code more concise and immediately giving your variable a usable value:

int age = 25;

This does exactly the same thing—it creates the variable and assigns it a value—but in a single, readable line.

Why This Matters

When you declare and initialize together, you:

  • Avoid uninitialized variable errors (the compiler knows your variable has a value from the start)
  • Write cleaner, more readable code (less clutter, clearer intent)
  • Make variables immediately usable (no need to remember to initialize later)

Works with All Types

You can use this approach with any primitive type you've learned:

double price = 19.99;
char initial = 'A';
boolean isReady = true;
long distance = 1500000L;

Each of these statements creates the variable and gives it its starting value in one go.

When to Use It

If you know the initial value when you create the variable, combine declaration and initialization. It's the standard, preferred style in Java. You'll only declare without initializing when the value must be calculated or determined later in your code.

Key Takeaway: Combining declaration and initialization (int x = 5;) is cleaner, safer, and makes your variables ready to use immediately—use it whenever you know the starting value.