Local Variable
|
Instance Variable
|
|
01)
|
Local variables are the
variables which are declared “ inside a Method or a Block “ .
|
Instance variables are the
variables which are “ declared directly in a Class “.
|
02)
|
Local variables will not be
initialized by the JVM, we will have to initialize it.
|
Instance variables will be
initialized by the JVM, with their default values.
|
03)
|
Memory will be allocated for
local variables when the corresponding block or a method is executed.
|
Memory will be allocated for the instance variables when an object is
being created.
|
Example
Programs of Instance And Local Variable :
Program 1 :
package
org.javanoobs.variables;
public class Test {
static int a,b; // static variable
s
public Test ( int a1, int b1){
a = a1;
b = b1;
}
public void disp (){
System.out.println( " a = " +a);
System.out.println( " b = " +b);
}
public static void main(String args[]){
Test
t1,t2;
t1
= new Test(10,20);
t2
= new Test (30,40);
t1.disp();
t2.disp();
}
}
OUTPUT :
a = 30
b = 40
a = 30
b = 40
Program 2 :
package
org.javanoobs.variables;
public class Test2 {
int a,b; // Instance variables
static int c; //static variable.
// Instance block..
{
System.out.println(" Inside
Instance Block !!! ");
System.out.println(" C " +c);
System.out.println(" a " +a);
}
static {
System.out.println(" Static block
is called !! ");
System.out.println(" C " +c);
}
// Create a
method...
public void disp(){
int d = 1 ; // Local variable
and
d
= a+b+c;
System.out.println( " d after
addition " +d);
System.out.println(" Disp method
called... ");
}
public static void main(String args[]){
Test2
t; //
This is the reference variable.
t
= new Test2();
t.disp();
}
}
OUTPUT :
Static block is called !!
C 0
Inside Instance Block !!!
C 0
a 0
d after addition 0
Disp method
called...
No comments:
Post a Comment