public static void main (String args[])

The signature of the Java main method perplexed me when I first started out programming.

Java was the first language I learned and I couldn’t wait for the day where I fully understood that signature.

By signature I mean the heading of the method:
public static void main (String args[])

I wrote a simple program that showcases how the String args[] input parameter works.

Screen Shot 2015-12-08 at 1.11.20 a.m.

First I will explain the other keywords.

public

Public simply means everybody has access to the method, which is needed for the main method since we need to run it.

static

Static means the method does not need to be instantiated into an object in order to use it. This is useful as the main method is always the starting point for the program and having it instantiated would be a waste of memory.

void

Void means it does not return anything.

main

Main is the name of the program, every program needs one main method (only one is allowed).

(String args[])

Inside the brackets is the input parameters, just like for any other method we would use. Here we are inputting a String array called args

Code Snippet

Here we have the program:

class Simple {
  public static void main (String args[]){
    System.out.println("Simple Argument Checker");

      for (int i = 0; i < args.length; i++) {
            System.out.println("arg " + (i+1) + ": " + args[i]);
      }
  }
}

Command Line

Compile

> javac Simple.java

Run

> java Simple arg1 arg2 cat dog

Conclusion

As you can see the four arguments passed in are printed out in your command line program.

Screen Shot 2015-12-08 at 1.11.58 a.m.

I hope this helped any confused developers out there.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s