Java Variables
A variable is like a container that holds data values. In Java, every variable has a specific type (which determines what kind of data it can hold) and a name (how you refer to it). Understanding how to declare, initialize, and manage variables is the first step to becoming a Java developer.
Declaration & Initialization
To use a variable in Java, you must first declared it and then initialize it with a value.
// Syntax: Type variableName = value;
int age = 25;
There are three ways to do this:
- Declaration only:
int score;(Allocates memory) - Initialization:
score = 100;(Assigns value) - Both together:
int score = 100;(Most common)
Click Run to execute your code
Variable Naming Rules
Java enforces strict rules for naming variables (identifiers):
- Must start with a letter, underscore (
_), or dollar sign ($). - Cannot start with a digit.
- Case-sensitive (
ageandAgeare different). - Cannot use Java reserved keywords (like
int,class,public).
Examples:
userName, accountBalance,
isLoggedIn.
Variable Scope
The scope of a variable determines where it can be accessed within your code. Java has three main types of variables based on scope:
-
Local Variables: Declared inside a method or block.
Scope: Only inside that method/block. Recreated every time the method runs. -
Instance Variables: Declared inside a class but outside
methods.
Scope: Accessible by all methods in the class. Specific to an object instance. -
Static (Class) Variables: Declared with
statickeyword.
Scope: Global to the class. Shared by all instances.
Click Run to execute your code
Constants (final Keyword)
If you want a variable to be constant (meaning its value cannot be changed after
initialization), use the final keyword.
final float PI = 3.14f;
// PI = 3.15f; // Compilation Error!
Example:
MAX_USER_LIMIT, DEFAULT_TIMEOUT.
Summary
- Variables are containers for data with a specific Type and Name.
- Use camelCase for naming variables.
- Local variables exist only inside their block.
- Instance variables belong to an object.
- Static variables belong to the class.
- Use final to create constants that cannot change.
What's Next?
Sometimes you need to convert data from one type to anotherโlike turning an integer into a double. In the next lesson, we'll learn about Type Casting and how to handle data conversion safely.
Enjoying these tutorials?