CodeNewbie Community 🌱

Cover image for Variables
Abhann
Abhann

Posted on

Variables

Let's talk variables, that is of course assuming you already have some knowledge and familiarity with data types and the different ways of specifying data types, if you haven’t, don’t worry, I cover that on "LITERALS".
Back to variables, shall we?, First of all, let’s define variables.

• What are variables?
In Java, variables are identifier types which are associated with a changeable value.
Ex; image

The variable above is “$_binaryNumber6”.

Java is generally considered a case sensitive programming language, and as such there are some rules that guide the naming of variables.

Rule 1: The only allowed characters when declaring variables are lowercase and uppercase alphabets (a - z, and A - Z), numbers (0 - 9), the dollar sign ($), and the underscore sign (_).

Rule 2: When declaring a Variable, it is good programming practice to start with a small letter, and in the case of lengthy variable names (i.e., more than one word), you start the next name with a capital letter and they must not contain white spaces.

Rule 3: Variable naming should never start with a digit else you get a compile error.

Rule 4: All predefined Java class names and interface names can be used for naming variables, although it is considered bad programming practice as it can reduce readability and create confusion.

Rule 5: You shouldn’t use reserved words in Java as variable names.

• Declaring and Assigning Variables.
Ex;image //Declaring a variable.

Ex;image //Assigning the variable.

Ex;image //Assigning and declaring in a single line.

It is generally considered a good programming practice to declare before assigning a variable.

There are two divisions based on type of variables, and they are;
• First Division – Based on the type of value represented by a variable, it is categorized into two types namely;
o Primitive Variables – To represent primitive values.
i.e., image
o Reference Variables – To refer objects.
i.e., image

• Second Division – Based on the position of declaration and behavior, it is categorized into three types namely;
o Instance Variables.
o Static Variables.
o Local variables.
The two divisions are equally important because they work hand in hand, and so that means, a variable can be primitive and instance, or static or local at the same time, and in the same vein, a reference variable can be static, local or instance.

Once again, understanding data types and its uses is very important to fully grasp the concept of variables.

• Static/Class variables
o If the value of a variable is not varied from object to object, then it is not recommended to declare the variable as an instance variable, instead, we will have to declare such types of variable at class level by using a static modifier.
That in essence means, in the case of instance variables, for every object, a separate copy will be created but in the case of static variables, a single copy will be created at class level and shared by every object of the class.

o Static variables should be declared within the class directly, but outside of any method or block or constructor, they can equally be called explicitly.

o Static variables will be created at the time of the class loading and destroyed at the time of class unloading, and because of this, the static variable is directly proportional to the scope of its class file.

o Static variables will be stored in the method area.

o We can access Static variables either by object reference or by class name, but it is recommended to use “class name”.
Now within the same class, it is not required or compulsory to use class name, because we can access the variable directly, as shown below;
image

o We can access static variables directly from both instance and static areas, as shown below;
image

o For static variables, JVM will provide default values and we are not required to perform initialization explicitly, as shown below;
image

In conclusion to the guidelines and examples provided above, static variables are also known as class level variables or fields.
Taking the examples provided above, I will briefly iterate the internal processes that occur within a Java’s “TestingStaticVariables” class.

  • Start JVM (JVM should be started).
  • Create and start main thread (this is done by JVM).
  • Locate TestingStaticVariables.class file (the main thread will check for this).
  • Load TestingStaticVariables.class (the main thread will load this (i.e. static variables creation)).
  • Execute main method.
  • Unload TestingStaticVariables.class file (the main thread does this too (i.e. static variables destruction)).
  • Terminate main thread.
  • Shutdown JVM.

That is, Static variables will be stored in the method area, and local variables will be stored in the stack.

The above might appear a bit more complex to make out, and as such, I will implore you to do a bit more study on “JVM – Java virtual machine”, on your own.

Let’s take a look at another example to further cement our understanding of the processes.
Observe;
image

Finally, the elementary way to describe a static/class variable is to say that it is associated with its class, and you can access them without having to create an object.

Ex:image

• Instance variables
o If the value of a variable is varied from object to object, such type of variables is called instance variables.
That is, for every object, a separate copy of instance variable will be created.

o Instance variables should be declared within the class directly, but outside of any method or block or constructor they can equally be called explicitly.

o Instance variables will be created at the time of object creation and destroyed at the time of object destruction; hence, the scope of instance variable is exactly the same as the scope of the object.

o Instance variables will be stored in the “heap” memory as a part of the object.

o We can access instance variables directly from an instance area, but from a static area, we can access by using object reference.

o For Instance variables, JVM will always provide default values and we are not required to perform initialization explicitly.
image

o Instance variables are also known as object level variables or attributes.

Now, Consider the example below, to further cement our understanding of Instance variables;
image
As seen above, for the sake of clarity, the code is invalid because an instance variable is only accessible by creating an object and hence it follows that it is always part of an object and so without having an object, the main method cannot be executed. Without this object, instance variable is rendered useless.

We get the error below, immediately on execution;image

Now to address the compile error, with the explanation above, we create a new object and use it to access the instance variable.

The code below fixes it;
image

Another approach would be to access the instance variable directly from an instance area with an object of course, as seen below;
image

In conclusion, we can describe an instance variable by its direct relationship to an object creation to be instantiated before it can be modified. We need the object to explicitly instantiate/access an instance variable.

Ex;image
Further-more, unlike static variables, instance variables have their own separate copies within the memory. In other words, you will need that exact created object to modify an instance variable, whereas for static variables, you can use any object to modify it.

• Local variables
o Sometimes, to meet temporary requirements of the programmer, we can declare variables inside a method or block or constructor, such type of variables are called “local variables” or “temporary variables” or “stack variables” or “automatic variables”.

o Local variables will be stored inside stack memory, in essence they will be created while executing the block in which we declared it, once block execution is completed, then automatically, the local variable gets destroyed.

Hence, the scope of the local variable is the block in which we declared it, observe below;image

o For local variables JVM won’t provide default values, and hence it is compulsory to perform initialization explicitly.
Before using that variable, that is, if we are not using the variable, then it is not required to perform initialization, observe below;
image

image

Note; about the three examples above, it is not recommended to perform initialization for local variables inside classical blocks, because there is no guarantee for the execution of these blocks at run time. It is highly recommended to perform initialization for local variables at the time of declaration, at least with default values.

o The only applicable modifier for local variables is “final”, if we are trying to apply any other modifier, then we will get a compile time error.
Ex;image

o If we are not declaring with any modifier, then by default, it is “default”, but this rule is applicable only for instance and static variables, and not for local variables.

In its simplest form, local variables are described by creating explicitly declared variables inside a method within a class, and their accessibility is limited to said method. In other words, you can neither access, nor can you modify them from outside the method, and also just like the instance variable, an object is required to call any action from the method.
Ex;image

Conclusions
(i.) For Instance and static variables, JVM will provide default values and we are not required to perform initialization explicitly.
But for local variables, JVM won’t provide default values, it’s compulsory to perform initialization explicitly before using that variable.

(ii.) Instance and static variables can be accessed by multiple threads simultaneously, and hence they are not thread-safe, but in the case of local variables, for every thread, a separate copy will be created, and hence local variables are thread safe.

(iii.) Every Variable in Java should be either instance, static or local.
Also every variable in java should be either primitive or reference, hence various possible combinations of variables in Java are;image
Observe the example below:
image

Finally, before we go, let’s take another look at Arrays.

• Uninitialized Arrays
We want to simply show and in essence, convey the behavior of variables with arrays in the expressions below, now considering Uninitialized arrays:
Consider;image

Now for the three variable levels, we can express Uninitialized arrays at:
I. Instance Level
image

II. Static Level
image

III. Local Level
image

Note; Once we create an array, every array element by default is initialized with default values, except at the local level of course, as shown.

Top comments (0)