i

JAVA Complete Course

Variables

In Java variable is a container which holds a concrete value of data type during program execution. We have different types of variables, like: local, instance and static. Generally, variable is a name of reserved area which is allocated in memory. We can call it, name of memory location.

As we already mentioned, we have three types of variables:

Local is a variable which is declared inside the method body. In that case, the concrete variable can be used only in that method, after the declaration and other methods in the class doesn’t have any knowledge about this local variable. Local variables in the method cannot be declared as static.

Instance variables are declared inside the class, but outside of any method. They are not declared as static. The reason they are called instance variables is that their values are instance specific and not shared among other instances.

Variable which is declared as a static is static variable. As mentioned earlier, it cannot be a local variable. There is always one single copy of static variable and shared among all instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

Let’s see some examples of different variables;

In Java, there is terminologies like widening and narrowing of variables. Widening of variable is when we assign lower type of variable to higher type of variable in terms of memory. For example, if we have variable short a = 2, and then write int b = a;

This is example of widening of variable and output will be following:

Narrowing of variable is known also as type casting. For example, if we have float variable

float a = 10.5 and then assign it to int b = f; in that case we  will get compilation error and to avoid it we need to cast float to int.

Output of this code will be:

And regarding variables there is case, which is called overflow. It happens when we assign value to the variable which is higher than maximum value of it can hold. For example, we already know that byte can have maximum value 127, let’s see what happens when we assign it more that 127;

Output of it will be: