Monday, April 11, 2011

JAVA Programming : Variables and Scope of Variables

JAVA Variables 



A variable in Java is like place holder that can store a value that once declared can be used through out the program according to scope of that variable(discussed below). Datatypes specifies what kind of data each variables will store for example a variable declared as int cannot have char values. 


public class DeclareVariables {

    public static void main(String args[]){  
          int a=7;
          int b=9;
          int sum;
          sum = a+b;
          System.out.println("sum = "+sum);

    }
}



In DeclareVariable class, inside the main method we declared three int variables a, b and sum. Here a and b variables has some value stored and variable sum will have their addition stored in it. Output of this Java program is:


Scope of Variables: Scope of variables is the portion of program where a declared variable can be used. Scope of Variable differ according to the place where the variable is declared. A variable can be declared in various places in a Java Class.
  1. Class Body
  2. Method Body
  3. With in Statement Block
  4. As Parameter or in for loops
First three declared variables will have there scope with in the block (curly brackets) they are declared. The variable declared as parameter or in for loops are declared with in Parentheses and can be used with in the followed statement block. 


public class ScopeOfVariables {

        public static void main(String args[]){           
               for(int a=1; a<=5; a++){
                    System.out.println(a);
               }
        }
}



In above example we have a variable declared in for loop that can used only with in the statement block of that for loop. 

No comments:

Post a Comment