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);
Frank
  • 30,590
  • 58
  • 161
  • 244

3 Answers3

6

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

kg_sYy
  • 1,127
  • 9
  • 26
  • 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). – Johannes H. Feb 23 '14 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:

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
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);
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Johannes H.
  • 5,875
  • 1
  • 20
  • 40