1.
static variable
static variable is a java variable, it will
be recognized and initialized at the time of loading respective class byte code
to the memory.
static variable is a java variable, it will
share its last modification value to the future Objects and to the last
objects.
In java applications, static variable are
re accessed either by using reference variable (or) by using class Name
directly.
Note
1:-
In java applications, we can access static
variables by using reference variable contains null value, when JVM will not
rise an exception, but we access instance variables by using reference variable
contains null value then JVM will rise an exception like
“java.lang.NullPointerException”.
In java applications, we can “this” keyword
to access current class static variables.
In java applications, static variables never
be declared as local variable, static variable must be declare as class level
variables.
In java applications, static variables data
will be shared in “method area”.
Ex code:-
class A
{
static
int i=10;
int
j=20;
void
m1()
{
//static
int k=30;--->Error
System.out.println("m1-A");
System.out.println(this.i);
}
}
class Test
{
public
static void main(String[] args)
{
A
a=new A();
System.out.println(a.i);
System.out.println(A.i);
A
a1=null;
//System.out.println(a1.j);--->NullPointerException
System.out.println(a1.i);
a.m1();
}
}
Output:-
10
10
10
m1-A
10
Ex code 1:-
class A
{
int
i=10;
static
int j=10;
}
class Test
{
public
static void main(String[] args)
{
A
a1=new A();
System.out.println(a1.i+""+a1.j);
//10 10
a1.i=a1.i+1;
a1.j=a1.j+1;
System.out.println(a1.i+""+a1.j);
//11 11
A
a2=new A();
System.out.println(a2.i+""+a2.j);
//10 11
a2.i=a2.i+1;
a2.j=a2.j+1;
System.out.println(a1.i+""+a1.j);
//11 12
System.out.println(a2.i+""+a2.j);
//11 12
A
a3=new A();
System.out.println(a3.i+""+a3.j);
//10 12
a3.i=a3.i+1;
a3.j=a3.j+1;
System.out.println(a1.i+""+a1.j);
//11 13
System.out.println(a2.i+""+a2.j);
//11 13
System.out.println(a3.i+""+a3.j);
}
}
Output:-

No comments:
Post a Comment