Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

main method declaration doubt!

 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't I declare main as


NetBeans says:



I know it works only when either it is written as



OR as



But why? Suppose I do not want to pass any arguments? Why shouldn't the ARGUEMENT-LESS main() work?
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you do not pass arguments the args variable will be null. No problems
 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but why cant I declare it like this:



What is wrong with this?
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM does not recognize that signature as the main method that it should trigger. The main method always takes a String... args argument
 
vikky agrawal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akash
static public void main(){ }


jvm reconizes the main method with the syntax
public static void main(String[] args)

if you don`t pass any argument in that main method jvm will
not recognize that main method and can`t start execution.

you can declare main method as:

 
Kevin Kilbane
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aakash Goel wrote:but why cant I declare it like this:



What is wrong with this?


Nothing.

This is a valid signature for a method.

However, to run your program you will need a main method with the (String[] args) parameter as this is the specific method signature that the JVM looks for when running your program. This is how Java itself is written, you can't change it.

You can call your main() method from your main(String[] args) method (if you really want to).
 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone. Got the point.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to add that if you don't pass any arguments to main, args won't become null. Instead, it will have zero elements.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic