• Post Reply Bookmark Topic Watch Topic
  • New Topic

execution is not starting from main()..it is starting from constructor()...Y??explain  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test{


public static void main(String[] args){

System.out.println("start---1");

Test t=new Test();

System.out.println("end main");


}


int y=m3();
int m3(){
System.out.println("inside int");
return y;
}

{
System.out.println("nsb");

}

Test()
{
System.out.println("inside cnstrct--- ");
Test t=new Test();

System.out.println("constructor end---");
}


}
 
lowercase baba
Bartender
Posts: 12613
50
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What makes you think it starts inside the constructor? I assure you, it does not.
 
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you know that it doesn't start from the main method?

There is infinite recursion with the Test constructor which is probably making you miss the first lines that are printed.
 
Marshal
Posts: 58295
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I would have added code tags to yoru post, which make it look much better, but you didn't indent the code.
 
Greenhorn
Posts: 8
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its always start from main, only static block executes before main. and constructor is called when object is created which is normally created in main.
 
author
Marshal
Posts: 23435
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think what is happening is ... there is a recursive call in the constructor. The OP is probably not seeing the output from the main, since it scrolled off too fast. Instead, there is an endless stream of messages from the constructor, followed by eventually, an out of memory error.


[EDIT: it looks like E Armitage caught this, but I missed the response... earned a cow]

Henry
 
Campbell Ritchie
Marshal
Posts: 58295
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a StackOverflowError when I tried it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!