Variables and Identifier


Variable is the part of memory where we store any value. When we want to store any value then in spite of remembering that complex address where value is located, we give a name that address, that is variable. Variables store values temporary which is to be used in further program.

Syntax:
Data type variable = value;
Data type variable1, variable2;
Example:
int val1, val2, val3;
int val1 = 11, val2 = 22;

Naming Rules:

  • Variable name’s first character must be alpha.
  • Keywords are not allowed as variable name.
  • Special symbols are not allowed.
  • Variable names are case sensitive i.e. upper & small cases have different meaning.
  • Blank space is not allowed in a variable name.
  • Underscore can be used at the place of space.


Types of Variable:

  • Local Variable
  • Static Variable
  • Instance variable

Local Variable: Local variables are declared within the method or block. Variables are initialized when block is executed and destroyed with end of block or method. Access modifiers are can’t be used as Local Variable.

Static Variable: Static variables are also called Class Variables. These are declared with static keyword. Static variables are declared only once. Most Static variables are global. Class variables starts with class and destroyed when class in end. Static variables can be accessed with class name.

Instance Variable: Instance Variables are object variables that are declared within a class but outside any method or block. Instance variables are not declared as static.


Program: 
class Value{
                int val1 = 10;                        //instance variable
                static int val2 = 20;                   //static variable
               
                public void display(){
                                int val3 = 30;                 //local variable
                                val3 = val3 + 10;
                                System.out.println("Value3 = " + val3);
                                System.out.println("Value1 = " + val1);
                }
               
                public static void main(String[] args){
                                Value obj = new Value();
                                obj.show();
                                System.out.println("Value2 = " + val2);
                }
}

Identifier: Identifiers are used to define the name of class, package, method, variables etc. There are some that should be followed before naming any identifier:

  • Identifier name starts with any alpha character or underscore or dollar sign.
  • Specials symbols are not allowed .
  • Blank is not allowed. We can use underscore at place of space.
  • Identifiers are case sensitive.
  • Keywords can’t be used as identifier name.



Comments

Popular posts from this blog

Decision Making Statements

Data Types

What is JAVA?