Variables


Variables

At any point when we need to store any data, we store it in a location of the PC. Rather than recollecting the location where we have put away our data, we name that address. The naming of a location is known as variable. Variable is the name of memory area. All in all, variable is a name which is utilized to store a value of any kind during program execution.

Various types of variables in Java:

Local Variables

These variables are declared in method, constructor or block. They are initialized when method, constructor or block starts and will be destroyed once its end. Local variable reside in stack.

Local Variable is :5

Class Variables (Static Variables)

Static are class variables declared with static keyword. Static variables are initialized only once. Static variables can be used in declaring constant along with final keyword.

Instance Variables (Non-static Variables)

These variables are declared inside a class but outside any method, constructor or block. These variables are also variable of object commonly known as field or property. They are known as object variable. Every object has its own copy of every variable and hence it doesn't effect the instance variable if one object modifies the value of the variable.

Example No.1:

Com.knowledge2life public class Main{ public static void main(String[] args){ int a=10; float f=a; System.out.println(a); System.out.println(f); } }

OUTPUT:

10
10.0

Example No.2:

Com.knowledge2life public class Main { public static void main(String[] args) { final int myNum = 15; myNum = 20; // will generate an error System.out.println(myNum); } }

OUTPUT:

Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;