• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why main method

 
vijay Thiru
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class sample1 {
int as;
static int s;
int c ;
static {
s = 3;
sample1 s = new sample1();

System.out.println(s.as);
System.out.println(s.c);
System.out.println(s.s);
}
{
as =23;
}
sample1() {
c =23;
}
public static void main(String[] args) {
/*sample1 s = new sample1();

System.out.println(s.as);
System.out.println(s.c);
System.out.println(s.s);*/
}
}
the above program, i just commented the main method defination.then i copied the main method defination into static block.
both the things give the same result.
then why we have main method.we start execution from static block itself.
what is difference between static block and static main method execution.
please expalin me reason for this.
 
vijay Thiru
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the above program itself,
i have constructor and instance initializer block.
both doing the same thing.
what is the difference between constructor initialization and instance initializer block.
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when u execute java sample1, it means u want to execute sample1.main(args)

Following are the steps of execution....

1. First ClassLoader loads the class.

2. Then after that class gets initialised means all the static blocks and static variables gets executed in their order of appearance in the code. Remember no static method is executed at this time.

3. After the initialisation of class, java interpreter runs ur class by calling

main method.

Program starts when main starts.
Ptogram ends when main ends.

I hope u got ur reply.

Thanks

Naseem
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic