Using The Main(string[] args) Better

I have recently started a college class on Java. It haven’t worked with it in a while and thought maybe its a good choice as the last elective I have left to do. One thing I noticed is that a lot of the assignments and examples don’t mind if you cram your code into the


Main(string[] args) { [...] }

which is fine for those just beginning programming. For a lot of people just making code work is already a god send. However, I cannot help but point out that this is a fairly bad practice for a few reasons:

  • Any class scope variables have to be static
  • All functions have to be static
  • You have to initialize all your variables inside of the main function. Not a good practice.

This is not a very good thing because this is a pitfall for memory management. A program NEEDS to have a static entry point, but this does not mean that you need to wrap your code around it. If everything is static (which is something students LOVE to abuse), then the only time your memory gets cleared is when your function variables go out of scope and/or when the program exits. This is a bad coding practice which makes it very difficult to write optimized applications.

So what do I do?

You don’t have to do much. Simply create a non-static class and call it “Main” or any name you would like to give it. Then simply create a new instance of the variable inside the main and call a start function. Very simple! Let me show you an example:


     public class Main 
     {
          //Now your class variables don't have to be static
          int myInt;

          public Main()
          {
              myInt = 0;
              //Your variables initialization here
          }

          public void start()
          {
          //Put your code here!
          }
     }

and so your static main now looks like this!


public static void main(String[] args) {
      Main main = new Main();
      main.start();
 }

Should I Teach This?

I started Java a about 6 years ago and for a very long time I did not understand how to structure code in an easy way. This concept might be a little bit confusing for students, but it will clean up their code. Students starting Java without coding experience still don’t understand what static variables are (and why you should avoid them), so this will help them avoid the pitfalls of “Well everything is static ill just make mine static too!”. It removes an extra element for something that is already somewhat confusing for many!

Closing Notes

        This helps exit your application better

Its not quite faster or “better” in the sense of exiting, but it nests your code in such a way where you know when your application is exiting. The only time your code will go beyond the “main.start()” is when it is exiting or switching states. This is extremely useful if you want to do some processing right before exiting.

Leave a comment