Like it on Facebook, Tweet it or share this topic on other bookmarking websites.
can anyone tell me that when we have static block in java then why do we need main function.


Let me try to find an answer Devan....years have passed since i closed my books :P :P :P
Now also your question is not much clear to me. :blink: Yet, I will try. You can ask me, if still doubts exist.

main() itself is a static block.
Hoping you know it, without which we can't run a OOPS language. Also, all static blocks and variables are executed first before any other objects. Obviously that's why main() runs first while we run a program.

When we declare a variable or method as 'static', it can be accessed before any objects of its class are created and without reference to any object. That's its advantage.

Also all variables declared as static will be global variables too.

Your question is "when we have static block in java then why do we need main function"

So your answer is....main itself is a static block which runs first.
So, obviously a static block is running!!!!

Is your doubt cleared?
If not ask me. I will try to help you. :) :)


Sandhya im not talking about static method here..im talking about static blocks...yes main is a static but static blocks are different...let me show with an example:

public class staticEx {
static {
System.out.println("Inside Static Block ");
}
}

this is a program without main in it but it still works with the help of an self executable block namely 'static block'....SO my ques was that if we have static block then why use main..and fyi static blocks are as equally efficient as main.

Also hoping you know this that the static block compiles before main
I will try later

Yes, static blocks, if exist in a pgm will compile before main.
I think, I have noted it here :dry:

Meera sandhu
Devan...
I have given this thread link to my friends and waiting for its reply. Hoping I can give it to you very soon

Meera sandhu
You do not have permissions to reply to this topic.