Variable Declaration
& Assignment
Learn how to declare variables with a type and assign values in Java: the fundamental building block of every program.
What Is a Variable?
A variable is a named container in your computer's memory that stores a single piece of data. Think of it as a labeled box: the label is the variable's name, and what you put inside is the value.
Why Variables Matter
Java is Statically Typed
In Java, every variable must be declared with a specific data type before it can be used. The compiler checks types at compile time, not at runtime.
The Declaration Rule
Every variable declaration in Java follows a strict two-part syntax: the type comes first, then the name.
Declaration vs Assignment
| Declaration | Assignment | |
|---|---|---|
| Purpose | Creates a new variable | Stores a value in an existing variable |
| Syntax | type name; | name = value; |
| Frequency | Once per variable (per scope) | As many times as needed |
| Example | int age; | age = 17; |
Primitive Data Types
| Type | Size | Range / Values | Example |
|---|---|---|---|
| int | 32 bits | \( -2^{31} \) to \( 2^{31}-1 \) | 42 |
| double | 64 bits | Decimal precision | 3.14 |
| boolean | JVM specific | true or false | true |
| char | 16 bits | Single character | 'A' |
Step-by-Step Approach
Variable Naming Rules
Example 1: Integers
Example 2: Doubles & Strings
Example 3: Booleans & Char
How Memory Works
Constants with final
Adding the keyword final before a declaration makes the variable a constant: once assigned, its value can never change.
Common Mistakes
Summary Cheat Sheet
| Action | Syntax | Example |
|---|---|---|
| Declare | type name; | int age; |
| Assign | name = value; | age = 17; |
| Initialize | type name = value; | int age = 17; |
| Reassign | name = newValue; | age = 18; |
| Constant | final type NAME = value; | final int MAX = 100; |
Question 1 of 5
Which of the following correctly declares and initializes an integer variable named count with the value 10?
Question 2 of 5
What happens when you try to compile this code?
double temperature;
System.out.println(temperature);
Question 3 of 5
Which variable name is valid in Java?
Question 4 of 5
What is the value of x after these lines run?
int x = 5;
x = x + 3;
x = 1;
Question 5 of 5
Which line will cause a compile error?
Line 1: final int SIZE = 10;
Line 2: String name = "Java";
Line 3: SIZE = 20;
Line 4: name = "Python";