0% completed
In this lesson, we learn how to declare and initialize variables in Java. A variable is like a container that stores data.
Each section below includes its own complete code example that you can run to see the concepts in action.
A variable is a named space in memory used to store a value that may change during program execution.
Note: In this lesson, we explain the idea of a variable. Code examples in later sections will show how to declare and initialize them. We will learn about variable data types in the next lesson.
Declaring a variable tells Java that a variable exists with a given name and data type.
type variableName;
int
, String
).When declaring variables in Java, it's essential to follow specific naming conventions and rules to ensure your code is readable, maintainable, and free from errors. Below are the key rules and best practices for naming variables in Java:
Start with a Letter, Underscore (_), or Dollar Sign ($):
A
-Z
or a
-z
), an underscore (_
), or a dollar sign ($
).int age;
, double _salary;
, String $name;
Subsequent Characters Can Include Letters, Digits, Underscores, or Dollar Signs:
0
-9
), underscores, or dollar signs.int count1;
, double total_amount;
, String user$Name;
Case-Sensitive:
myVariable
, MyVariable
, and MYVARIABLE
are considered distinct.Cannot Use Reserved Keywords:
int
, class
, public
, static
, void
, etc.int class = 5; // Error
int myClass = 5;
No Spaces Allowed:
int my variable; // Error
int myVariable;
, int my_variable;
Should Not Start with a Digit:
0
-9
). However, digits can be used after the first character.int 1stPlace; // Error
int firstPlace;
, int place1;
Avoid Using Special Characters Except _ and $:
_
) and dollar signs ($
) are permitted as special characters in variable names. Avoid using other special characters like @
, #
, %
, etc.int total@Amount; // Error
int total_Amount;
, int total$Amount;
Explanation:
number
is declared as an integer.Initializing a variable means giving it an initial value at the time of declaration.
type variableName = value;
Here, value
is assigned to the variableName
variable.
Explanation:
number
is initialized with 10
.message
is initialized with "Hello, Java!"
.You can declare several variables of the same type on one line, and you can initialize them together or separately.
Explanation:
a
, b
, and c
are declared and initialized in one line.In our next lesson, we will cover Data Types in Java. Data types determine the kind of values a variable can store, such as numbers, characters, and text.
.....
.....
.....