Java Variables

In java a variable which holds the value. While execution of any java program these variables will be used in a task execution and which can be assigned with a data type.

Types of variables

There are three types of variables in Java

  1. 1. local variable
  2. 2. instance variable
  3. 3. static variable


1. Local Variable

A variable declared inside the body of the method is called local variable, local variable can not be able to access outside of the method.

2. Instance Variable

Declaration of an instance variables should be inside a class but outside a method. These variables can be acessed within the class. If we need to access these variables into another class then we need to create a object through that we can access it.

3. Static variable

If a variable declared as static then we can call it as static variable. It cannot be local. Per calss a single copy of static vatiable is allowed and it will be shared among all the instances of the same class or different classes.

Variable declaration Syntax:

    type variableReference = value;

Here, type is one of the java data type and variableReference is the name which used to declare a variable. Equal operator is used to assign the value.

Example1: Create a variable called myNum of type int and assign it the value 15

    int myNum = 15;
    System.out.println(myNum);
Example2: You can also declare a variable without assigning the value, and assign the value later

    int myNum;
    myNum = 15;
    System.out.println(myNum);

Example to understand the types of variables in java


    public class A  
    {  
        static int m=100;//static variable  
        void method()  
        {    
            int n=90;//local variable    
        }  
        public static void main(String args[])  
        {  
            int data=50;//instance variable    
        }  
    }//end of class   

Java Variable Example: Add Two Numbers


    public class Simple{    
        public static void main(String[] args) {    
            int a=10;    
            int b=10;    
            int c=a+b;    
            System.out.println(c);    
            }  
        }