Variable in Java



Variable is a named storage location for storing values. Before using any variable first it need to be declared. Variable declaration specify type of data going to be stored in variable. For example if we need to store numeric value, variable can be declared of int data type.


Declaration of variable

<Data Type> var1 ;

Variable can be assigned value at the time of declaration as well. Multiple declaration of same data type can be done in java.

	 // Multiple declaration
	 int a,b,c;
	 int x=3,y=5;
	 

Above example shows how multiple variable can be declared at a time. Second line showing multiple declaration with initialisation.




Naming Rules

  • Variables in java are case sensitive. Variable can be any sequence of letters, digits. Variable name can start from any letter, '$' and _ (underscore).


  • White spaces in variable name is not allowed.

    		    int old age; // Error illegal variable name
    		  

  • Variable name can't be keyword or reserved word

    .

  • Use variable name that can give quick understanding about purpose of variable. Instead of using letter a, x etc, use proper name i.e. address, contact.


  • If variable is made of two or more words, just make second letter capital. It is not necessary. This convention has been followed while developing java library.

Types of Variable

Type 1Local Variable

Any variable declared in method or block is known as local variable. Local variable has to be initialised. Local variable get memory when method or block, in which local variable declared is executed. When execution of method or block is over, local variable is destroyed. There is no concept of garbage value like c.

Note Compiler won't allow execution of program having uninitialised local variable in use. There is no default values for local variable, so local variable has to assigned value explicitly.

No access specifier is used with local variable. Local variable can only be accessed in method or block, in which they are declared.


Example:

	   //file : local.java 
	   // www.jgyan.com 
	   
	    class local 
		 { 
		  public static void main(String arg[]) 
		   { 
		     int a ; // local variable declared in method 
			 
			 // Error : local variable a not initialised
			 int c=a+5;
		   }
		 }
		

Above program having a local variable declared in main method. That variable is used in addition. On the compilation of above program following error reported by compiler.

Error : local.java:6: error: variable a might not have been initialized
int c =a+8;
^
1 error

	// file: block.java 
	// www.jgyan.com 
	 class block
		 {
		  public static void main(String arg[])
		   {
		     for(int i=0;i<5;i++)
			  System.out.println("i:"+i);
 
            // Error: variable i can only be accessible in body of for loop. 
			 System.out.println(i);
		   }
		 }
		

Above program seems correct, but one error will be reported by compiler on compilation. Variable 'i' is declared in for loop, it become a local variable only be accessible for loop's body. Outside of for block it can't be accesses.

Error block.java:8: error: cannot find symbol
System.out.println(i);// error variable can only be accessible in body of for.
^
symbol: variable i
location: class block
1 error

Type 2Instance Variable(Non-static variable)

Variable declared inside a class, but not inside class's methods or constructor is known as instance variable. Instance variable can have access specifier i.e. public, private or protected. When object of a class is created using new keyword, instance variable got memory from heap. Instance variable are initialised to default value. Every object has it's own copy of instance variable.



Data type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0
char \u0000
boolean false


Example:

 // file:defaultone.java 
 // www.jgyan.com 
   class defautOne
    { 
	  byte b;
	  short s; 
	  int i; 
	  long l; 
	  float f;
	  double d;
	  char c;
	  boolean b;
	  void show()
	   {
	     System.out.println("byte:"+b);
		 System.out.println("short:"+s);
		 System.out.println("int:"+i);
		 System.out.println("long:"+l);
		 System.out.println("float:"+f);
		 System.out.println("double:"+d);
		 System.out.println("char:"+c);
		 System.out.println("boolean:"+b);
	   }
	}
	
	class one
	 {
	   public static void main(String arg[])
	    { 
		  defaultOne ob=new defaultOne();
		  ob.show();
		}
	 }
 
/*output:
byte:0
short:0
int:0
long:0
float:0.0
double:0.0
char: 
boolean:false
*/

Instance variables are declared without static keyword that's why also known as non-static variable.



Type 3Static Variable

Static variable declared with static keyword in class definition. Static variable is shared among all object of that class. Unlike instance variable, static variable initialised only once. Static variable also initialised automatically by default values.


Example :

  // file: stat.java
  // www.jgyan.com 
	  class stat
	   {
	    int a;
		static int b;
		stat()
		 {
		   a=10;
		 }
		void show() 
         {
		   System.out.println("data member:"+a);
		   System.out.println("Static member:"+b);
		 }
		void change(int m, int n)
         {
		   a=m;
		   b=n;
		 }		
	   }
	  class tw
       {
	    public static void main(String arg[])
		 {
		   stat s=new stat();
		   stat k=new stat();
		   
		   s.show();
		   k.show();
		   s.change(20,30);
		   s.show();
		   k.show();
		   // Static variable can be accessed using class name.
		 System.out.println("static:"+stat.b); 
		 }
	   }
/*Output:
data member:10  --+
Static member:0   |----> Object s data 10 and 0
data member:10  ----+
Static member:0		|-----> Object k data 10 and 0
data member:20    ----+
Static member:30      |----> Object s data after changing value 20 and 30
data member:10       ----+
Static member:30         |----> Object k data static variable changed to 30. 
static:30
*/