what is the difference between static block and static
method

Answer Posted / dharmendra

static block in the block that is used to initiate the class
members such as static int a;

This static block executed when the class loads first time
in memory and and thus it implicitly called by the compiler
not by the help of any one of the object.

class A
{
public A()
{
System.out.println("INSIDE THE CONSTRUCTOR OF THE A");
}

static
{
System.out.println("This is the static block");
}
}

class B
{
public static void main(String arr[])
{
A a = new A();
A b = new A();
}
}



the output of this program can be shown by the use of the
javac B.java
java B

the output generated is:

this is static block
INSIDE THE CONSTRUCTOR OF THE A
INSIDE THE CONSTRUCTOR OF THE A

this shows that the static block executed only ones as the
class loaded. and not at the time of the object created.



static method:

method is declared as static so that they can be called by
the name of the class.methodname();
these method usually not required any instance variable but
they can be use also with the objects.


and its loaded as many times as the object of the class is
created.


class A
{
static
{
System.out.println("This the static block");
}
static void print()
{
System.out.println("This is the class A static method");
}
}

class B
{
public satic void main(String arr[])
{
A a = new A();
A a1 = new A();
a.print(); // A.print();
a1.print(); // A.print();
}
}

the output of this method is :

this is the static block
This is the class A static method
This is the class A static method

Is This Answer Correct ?    22 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Given a singly linked list, how will you print out its contents in the reverse order? Can you do it with consuming any extra space?

616


What is static data type in java?

558


Explain a few methods of overloading best practices in java?

521


Does java arraylist maintain insertion order?

557


Explain about oops concepts.

644






What do negative exponents mean?

554


Explain wait(), notify() and notifyall() methods of object class ?

614


What is a locale?

711


List out five keywords related to exception handling ?

608


How do you remove duplicates from an array in java?

538


In java, what is the difference between method overloading and method overriding?

591


Explain the Propertie sof class?

599


What is java dot?

503


Can we declare the static variables and methods in an abstract class?

554


Can we have any other return type than void for main method?

546