InterviewSolution
| 1. |
Local and Instance Variable in Java |
|
Answer» Local Variable in Java is a variable declared in a method body or a constructor or a block (for example for loop) and its scope lies within the method or constructor or the block. The scope of the local variables starts from its declaration and ENDS when the block or method body or the constructor ends by the closing curly brace. Access specifiers like public, private, PROTECTED can’t be used for declaring local variables. They are implemented at the stack level internally. Instance Variables in Java is a data member of a class and is DEFINED in a class. Each object can create its own COPY of the instance variable and access it separately. The instance variables are visible for all methods, constructors and block in the class. They can be accessed directly by calling the variable NAME inside the class. Any changes made to the instance variables in the methods reflect in the state or value of the variable outside the scope of the method for a particular object. The scope of the instance variable is created and destroyed when the objects are created and destroyed respectively. Default values are given to instance variables. The default value is 0 for integers, floats, doubles and bytes, it is false for Boolean and null for object references. They cannot be declared as static otherwise they’ll be classified as static variables. If instance and local variables have the same name then ‘this’ keyword is used to differentiate among them. An example program to illustrate the use of Local as well as Instance variables is given as follows. public class Example { int a=5; // a is an instance variable public void add(int n) { int sum = a + n; // sum is a local variable System.out.println(sum); //accessing local variable } public static void main(String[] args) { int k=11; Example obj= new Example(); // creating object for Example class System.out.println(obj.a); // accessing instance variable obj.add(k); } }The given program produces the following output: $javac Example.java $java Example 5 16Here, a is the instance variable while sum is the local variable. |
|