Hi everyone, welcome to our next lesson in Java.
This lesson is about variables in Java. We will learn the following in this lesson:
- Naming convention of variables in Java
- How to declare a variable
- How to initialize and assign value to a variable
A variable is a storage location that has a value or content and may change the value during the execution of program.
Naming convention
Every programming language has its own rules on how to name your variable. Here’s the rule of Java for naming variables.
- Java is case sensitive (myAge is different from myage).
- Start your variable name with a letter, succeeding can be a combination of numbers and letters (e.g., m1Age2, myScore1 ).
- Spaces and other symbols or special characters are not allowed (e.g., ^,@,#).
- Keywords in java cannot be used as variable name. Visit our lesson about java keywords.
- Your variable in java must be readable, don’t use abbreviation a variable name must serve its purpose.
- Variable declaration is required.
Now that we know the rules on naming our variable let us proceed to one of those rules.
Variable declaration
In our previous lesson, we have enumerated the primitive data types in java. A data type is essential in declaring variable because it will signify what type of data can a variable store.
Example:
int myAge;
myAge is our variable name and it is an integer type that can only store numbers (−2,147,483,648 to 2,147,483,647) for int data type.
Note: semicolon (;) states that our variable declaration is complete.
Another example:
String myName;
int myAge;
Assigning value to a variable
After we have declared a variable it is up to the programmer to put an initial value or not, but if you want to know, here’s how.
Giving or putting a variable an initial value is what we called assignment statement.
Example:
String myName = “Piolo”;
int myAge = 6;
in the above example, Piolo is the assigned value to our myName variable and myAge stores the value of 6.
Note: assign an appropriate value to a variable depending on the data type of that variable.
Sample Java Program:
class VariableLesson {
public static void main(String[] args) {
//variable declaration
String myName = "Piolo";
int myAge = 6;
//print the value of the variables
System.out.println(myName);
System.out.println(myAge);
}
}