Creating a Class that Can Run as a Program

Contact Us or call 1-877-932-8228
Creating a Class that Can Run as a Program

Creating a Class that Can Run as a Program

The main() Method

In order to run as a program, a class must contain a method named main, with a particular argument list. This is similar to the C and C++ languages.

The definition goes inside your class definition, and looks like:

public static void main(String[] args) {
	(code goes here)
  • It must be public, because it will be called from outside your class (by the JVM).
  • The static keyword defines an element (could be data or functional) that will exist regardless of whether an object of a class has been instantiated. In other words, declaring main as static allows the JVM to call the method and therefore execute the program. That doesn't mean that an object of that class cannot be instantiated, it is just not required.
  • The String[] args parameter list states that there will be an array of String objects given to the method - these are the command line arguments.
  • To run the program, use the following from the command line if you are running it from the console:
    java <em>ClassName</em>
    For example, if we had an executable class called Hello, in a file called that compiled to Hello.class, you could run it with:
    java Hello