Before, we talked briefly about Java variables. In this chapter, we examine them in more detail.
What is a Java variable?
A Java variable is a piece of memory that has a name and holds a value. Every Java variable has a name and data type that determines the type of information it can hold. The variable name is called the identifier. The identifier cannot be a reserved Java word and it has to follow Java variable naming conventions.
Whether a class or method can access a variable is called the visibility of a Java variable. For example, an protected instance variable of a class is visible to the other classes in the same package but not visible to classes in other packages. Similarly, a private instance variable is visible to only the methods declared in the class itself.
Variable naming conventions
In addition to naming rules, there are a number of general conventions the developers follow with variable names in Java. These conventions are not built into the Java language. Not following these rules will not cause an error but it is strongly encouraged to follow them as best practices and readability.
1- Variable name starts with a lower case letter.
String firstName = “James”;
2- If the variable name is one word, it is all lower case.
int age = 48;
3- If the variable name has more than one word in it, the first letters of the words other than the first one are capital case, following Lower CamelCase Notation.
int ageOfPerson = 48;
4- Using numeric characters in the variable name is discouraged. Only when multiple instances of the same class or multiple primitives of the same type are used in the same context, putting the number denoting the initialization order makes sense.
Person person1 = new Person();
Person person2 = new Person();
5- Even though it is allowed, it is discouraged to use _ and $ signs inside a variable name.
Java Variable Types
Java language has three types of variables.
1- Member variables or fields
Member variables are variables that are declared outside of methods of a class. They determine the properties of a Java class.They have access modifiers (public, private or protected) preceding them. If no access modifier is declared, the access modifier of a member variable is default. The visibility of a member variable is determined by its access modifier.
2- Static variables
Static variables of a class are also called Class variables. All instances of a class share the same copy of a static variable. Therefore, once it is changed, it is changed for all the existing instances of the class in the same JVM. Static variables are defined as
<access modifier> static <type> <variable name> = <value>
It is considered a good coding practice to name static variables in all capital letters, with words separated by underscore character, _. An example might be
public static int NUMBER_OF_THREADS = 3;
As a good practice, static variables are referred to using the class’ name. Referring to them using an instance does not cause an error but is not recommended.
3- Local variables
Local variables are declared inside a method’s body and their visibility is limited to within the scope of the method they are defined in. Once the execution gets out of the method, they are not accessible. They do not have access modifiers preceding them.
Let’s see Java variables in an example. Let’s first create a class that will hold the variables.
public class JavaVariables {
public int x = 1; //Instance variable
public static String STATIC_STRING = “good”; //Static variable
public void printLocalVariable() {
int y = 5;//Local variable
System.out.println(“y: “ + y);
}
}
public class TryJavaVariables {
public static void main(String [] args) {
JavaVariables j = new JavaVariables();
System.out.println(“x : “ + j.x);
j.x = 2; //Change the value of the instance variable.
System.out.println(“x changed to: “ + j.x);
j.printLocalVariable();
System.out.println(“Static string: “ + JavaVariables.STATIC_STRING);
JavaVariables.STATIC_STRING = “nice”;
JavaVariables secondInstance = new JavaVariables();
System.out.println(“New value for static string: “ + secondInstance.STATIC_STRING);//Calling a static variable through an instance is not recommended, this is only for demonstration.
}
}
Compile the examples and run TryJavaVariables class. The output should be
x : 1
x changed to: 2
5
Static string: good
New value for static string: nice
The value of the static variable STATIC_STRING was changed from “good” to “nice” in a static way (using the class name instead of the instance). Following that, a new instance of JavaVariables class was created. The value of STATIC_STRING for the new instance is not “good” but “nice” because when the value was changed from “good” to “nice”, it automatically applied to all the instances of JavaVariables class in the same JVM.
Final variables
In Java, final variables can be declared only once and then their values cannot be changed over the course of the program. This is accomplished using the final keyword. Let’s declare and initialize an int with the final keyword.
final int x = 2;
If we later try to assign a new value to x, this will cause a compilation error.
Let’s see this with an example.
public class Example {
public static void main(String [] args) {
final int x = 2;
x= 3;
}
}
Compiling this class would give us the following error.
Example.java:4: cannot assign a value to final variable x
x= 3;
^
1 error
Similarly, Java allows initializing a final object only once. Trying to assign a new object to a final object variable causes a compilation error.
public class Person
{
public String firstName;
public String lastName;
public int age;
public void sayName(){
System.out.println(“My name is + firstName + “ “ + lastName);
}
public void sayAge(){
System.out.println(“I am “ + age + “ years old.”);
}
public void sayFavoriteFood(String favoriteFood) {
System.out.println(“My favorite food is “ + favoriteFood”);
}
public int getAge() {
return age;
}
public static void main(String [] args) {
final Person p ;
p = new Person();
p = new Person();
}
}
Compiling this class gives the following compilation error.
Person.java:25: cannot assign a value to final variable p
p = new Person();
^
1 error
Even though a final object cannot be assigned a new value, it is alowed to set new values to its instance variables. Now, let’s modify the main method of Person class a little bit.
public class Person
{
public String firstName;
public String lastName;
public int age;
public void sayName(){
System.out.println(“My name is + firstName + “ “ + lastName);
}
public void sayAge(){
System.out.println(“I am “ + age + “ years old.”);
}
public void sayFavoriteFood(String favoriteFood) {
System.out.println(“My favorite food is “ + favoriteFood”);
}
public int getAge() {
return age;
}
public static void main(String [] args) {
final Person p ;
p = new Person();
System.out.println(“age: “ + age);
p.age = 48;
System.out.println(“age was changed to: “ + age);
}
}
Now the class compiles fine and running this class gives the output
age: 0
age was changed to: 48