Professional Documents
Culture Documents
Memory is allocated multiple time Memory is allocated only once at the time of class
2
whenever method is calling. loading.
It is specific to an object so that these are These are common to every object so that it is
3
also known as instance method. also known as member method or class method.
Note: In some cases static methods not only can access with class reference but also can access with
object reference.
Example
class Counter
count++;
System.out.println(count);
Output
As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.
Example
class Counter
Counter()
count++;
System.out.println(count);
Output
Example
class A
void fun1()
System.out.println("Hello I am Non-Static");
System.out.println("Hello I am Static");
class Person
{
A oa=new A();
class A
int y;
void f2()
System.out.println("Hello f2()");
class B
int z;
void f3()
System.out.println("Hello f3()");
A a1=new A();
a1.f2();
class Sdemo
static int x;
System.out.println("Hello f1()");
x=10;
System.out.println("x="+x);
f1();
System.out.println("Hello main");
B b1=new B();
b1.f3();
Static block:
class StaticDemo
static
static
}
public static void main(String args[])
System.out.println("This is main()");
Output:
This is main()
Note: "Here static block run according to there order (sequence by) from top to bottom.
A class has to be loaded in main memory before we start using it. Static block is executed during
class loading. This is the reason why a static block executes before the main method.