0

If I have the following Java class :

public class MyClass
{
  ...

  public static void main(String[] args) 
  {
   ...
  }
}

Is there any practical difference if I call it in the 2 different ways below ?

[1] new Stock_Image_Scanner().main(null);
[2] Stock_Image_Scanner.main(null);
2
  • 2
    Depends on what the constructor does... Feb 23, 2014 at 22:23
  • 1
    MyClass.main(null) is the proper way (static access)
    – user180100
    Feb 23, 2014 at 22:25

3 Answers 3

6

In the first one the constructor gets executed. In the second one it does not.

1
  • ANd in the first example an object is allocated (and gets available for garbage collection immediately if the constructor doesn'T save a reference to the object in any static property). Feb 23, 2014 at 22:24
4

main is a static function, and should not be called via an instance. It should only be called via the class name:

Stock_Image_Scanner.main(null);

In addition, null should really be changed to new String[]{}. And as stated @kg_sYy, the new way (via the instance) executes the classes constructor, which is generally unexpected and not recommended.

More info:

1
  • 2
    +1 calling a static method via an instance is just confusing. Feb 23, 2014 at 22:30
3

Just to say the same thing in yet another way:

new Stock_Image_Scanner().main(null);

Does the same thing as:

new Stock_Image_Scanner();
Stock_Image_Scanner.main(null);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.