Variable In Java .

In this session i have discussed the variable in Java .


Variable is a temprary place holder in memory that can hold the value .

Variable is a named location in memory that can hold the value .

Variable hold the value according their data types .


Variable Syntax :

    Data-Type Variable-Name 
    
    Data-Type Variable-Name =Value

    

Java variable always defined with data type . You can assign the value at declaration time or later .

Variable Declaration :

    int x; // variable x declaration
   
    x=10;   // value assinged in x variable 
    ----------------------------------------------------------
    
    int y=20; // variable declared and assigned the value at same time 
    
    --------------------------------------------------------------------------- 

    int i , j  // Multiple line declaration of variable it is allowed in java
    
    ---------------------------------------------------------------------------

    int m=20;
    
    int n=m; // assign the value from m variable to n variable 
    

Types of variable in java

There are three types of variable in java as follows .

1-Local variables

2-Instance variables

3-Static variables


1-Local variables

Variables declared inside the method , constructor or block is called the local variabels .

 public class Hello{ 
        public void show(){
            int x=20;
            System.out.println("x : "+x);
        } 
    public static void main(String args[]){  
      Hello obj=new Hello();
      obj.show();  
    }  
 }  
    
    OUTPUT : x : 20
    

2-Instance variables

Variables declared inside the class but out side the method is called instance variables .

 public class Hello{ 
        
        int x,y; //instance variable
        public void get_data(int a,int b){
            x=a;
            y=b;
            System.out.println("x : "+x);
            System.out.println("y : "+y);
        }
        public void put_data(){
            System.out.println("x : "+x);
            System.out.println("y : "+y);
        } 
    public static void main(String args[]){  
      Hello obj=new Hello();
      obj.get_data(10,20);
      obj.put_data();  
    }  
 }  
    
    OUTPUT : x : 10
             y : 20
    

3-Static variables

Variable qualified with static keyword is called the static variable . It can not be local . It is always declared in class and out side of the method . The static variable created only one copy and shared with all instance of class .

 public class Hello{ 
        
       static int x=10; //static variable
        public void put_data(){
            System.out.println("x : "+x);
        } 
    public static void main(String args[]){  
      Hello obj=new Hello();
      obj.put_data();  
    }  
 }  
    
    OUTPUT : x : 10
    

Welcome to AndroidATPoint.

back image                     next image