Declaring and Initializing int Variables
What you'll learn: How to create int variables in your Java programs and give them values.
What Is a Variable Declaration?
Think of a variable as a labeled box in your computer's memory. Declaring a variable means telling Java "I need a box to store an integer, and I'm going to call it this name." You've already learned that int is Java's type for whole numbers—now it's time to actually create and use them.
The Basic Syntax
To declare an int variable, you write the type first, then the name:
int myNumber;
This creates a space in memory for an integer called myNumber. However, it doesn't have a useful value yet—Java automatically sets it to 0 (called default initialization).
Initializing with a Value
Initialization means giving your variable its first real value. You can do this when you declare it:
int myNumber = 42;
Or in two separate steps:
int myNumber;
myNumber = 42;
Both approaches work, but combining declaration and initialization on one line is more common and clearer.
Multiple Variables at Once
You can declare several int variables in one statement:
int x = 10, y = 20, z = 30;
Why Default to Zero?
Java's decision to initialize int variables to 0 prevents accidental use of garbage data. Unlike some languages, you won't mysteriously get random numbers if you forget to assign a value.
Key Takeaway: Declare int variables with int variableName;, initialize them with = value;, and remember that unassigned integers default to 0.