What is a variable in Java? With the Java programming language, the terms variable and field are both used synonymously. This sometimes produces some confusion for the new Java developer because they are both talking about the same thing.
The below two variables are defined as integers. Remember that an integer in Java is defined as int.
int widgetCounter = 0;
int widgetMaxLenth = 100;
What types of variables are used in Java?
- Instance Variables (Non-Static Fields) – Non-static fields are known as instance variables because their values are unique to each instance of a class.
- Class Variables (Static Fields) – Class variables is any field declared with the static modifier. The keyword static tells the Java compiler there is only one copy of this variable in existence, even if the class has been instantiated multiple times.
- Local Variables – The syntax for declaring a local variable is similar to declaring a field (see sample int’s above). There is no special keyword designating a variable as local. A method will often store its temporary state in local variables.
- Parameters – A parameter is referring to the variables that are passed into class methods. The important thing to remember is that parameters are always classified as “variables” not “fields”.
Let’s touch on naming conventions of variables in Java. Every programming language has different rules for naming variable, which includes Java. Please note the following rules and suggestions:
- Variable names are case sensitive (java and JAVA are different)
- Variable names can be unlimited length
- Variable names must begin with a letter (preferred method), $ sign, or number
- Variable names must not have white space
- Variable names after first letter may be letters, digits, dollar signs, or underscore characters
- Variable names must not use a Java Reserved Keyword
Now that your done with lesson 3, be sure to move onto the next lesson.