what is the difference between static block and static
method

Answer Posted / mittan aich

static block:
It is the class level one time execution block.After the compilation of the program when we go for running by using the command java <class name> then only the corresponding class will loaded in to RAM and 1st of all the static block of that class will execute even it run before the main method run.
->We place the class level initialization logic here like initialization of static variable.

Ex:

class Alpha
{
static
{
System.out.println("Alpha:static");
}
public void show()
{
System.out.println("Alpha:Show()");
}
}
public class Bita
{
static
{
System.out.println("Bita:static");
}
public static void main(String args[])
{
Alpha a=new Alpha();
a.show();
}
}


OUTPUT:
Bita:static

Alpha:static

Alpha:Show()
.......................
STATIC METHOD:
static method is a method which can loaded into the RAM without any object only class name is enough.
->Actually what happen fnds??A function will execute whn ever it only loaded into the RAm through a object.But some times our requirement is like this ,we have to execute a function but at that time no object cant be created for that
class.at that moment static method is very necessary
(consider about main method of java).
->static method and static variable does not allocated memory in object.but it allocate memory in CONTEXT area of that class.
EX:
class Gamma
{
int count1;
static int count2;
static void show()
{
System.out.println("Gamma:show()");
count1++;//error bcz non static variable.
count2++;//ok
}
public static void main(String args[])
{
Gamma.show();
}
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain about fail safe iterators in java?

806


Why do we use variables?

737


Why convert an applet to an application?

879


Describe how to implement singleton design pattern in struts.

781


Add a value x to array from index l to r where 0 <= l <= r <= n-1

885


Can we have multiple classes in single file ?

834


Which variable is the independent variable?

780


What is an interface in java? Explain

832


What is main function purpose?

768


when a request is generated from apache tomcat 5.5 and goes to oracle 10g or mysql,,, how the oracle or mysql reads the request as apache is a web server and oracle 10g is application server? when the oracle 10g provides response, how the apche tomcat reads it???

1927


What are 5 boolean operators?

849


What does the “final” keyword mean in front of a variable? A method? A class?

789


why would you use a synchronized block vs. Synchronized method? : Java thread

758


What is the difference between delete and delete[]

968


Is string serializable in java?

776