CSS font stacks & developer FAQs with Web standards

WestNIC provides reliable web hosting services

Fastwebhost offers cheap web hosting & reseller hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

What if you were One Percent Better? Java ebooks for iPad, Kindle, Nook and Sony Reader

The static main method

Q: How can I write a program that takes command line input?

A: Java programs that take input from the command line declare a special static method called main, which takes a String array as an argument and returns void. The example program below loops through any arguments passed to the program on the command line and lists their values.

… full answer hidden

Premium members click below for full answer
How can I write a program that takes command line input?

Q: Why is the main method declared public static void?

A: The main method is declared public so that it is accessible as part of the public interface of the program. It is static because it must be called before the class that hosts the method is instantiated. It returns void because the Java interpreter does not expect to receive or process any output from the class; any output intended for end users will normally be sent to the system output and error streams, or via a graphical user interface or supplementary logging systems.

Q: What does public static void main(String[]) mean?

A: This is a special static method signature that is used to run Java programs from a command line interface (CLI). There is nothing special about the method itself, it is a standard Java method, but the Java interpreter is designed to call this method when a class reference is given on the command line, as below.

… full answer hidden

Premium members click below for full answer
What does public static void main(String[]) mean?

Q: In which class is the main() method declared?

A: The static void main(String[]) method can be declared in any Java class to create a running Java application. Where you choose to place the main method will depend on the nature and structure of your application. It is possible for numerous classes to have their own main entry point methods, but only one entry point can be used to start the program. An application will typically have a top level application class, an "Editor", "Viewer", "Server" or "Monitor" type that will be used to start and run the program, for example.

Q: Why do we only use the main() method to start a program?

A: The entry point method main() is used to the provide a standard convention for starting Java programs. The choice of the method name is somewhat arbitrary, but is partly designed to avoid clashes with the Thread start() and Runnable run() methods, for example.

Q: Why don't all classes need a main() method?

A: Java classes do not necessarily need a main() method because not all classes are used as the entry point to start a Java program, or the execution of the code is activated through a higher level service, like a servlet container. Java class code is usually executed in the context of a larger Java application composed of lots of classes that interact together to provide the overall functionality of the system. It is rare that a single class would comprise a stand-alone application, but of course this can be the case with small utilities, test programs and experimental work.

The main() method is used to start a Java program, so is only necessary where the host class serves that purpose in a Java application. Java developers sometimes include a main() method to run simple configuration or diagnostic tests on a class, where you might feed in arbitrary input parameters.

Overloading the main method

Q: Can the main() method be overloaded?

A: Yes, any Java method can be overloaded including the main() method. The Java interpreter will only invoke the standard entry point signature for the main() method, with a string array argument, but your application can call its own main() method as required.

Q: Can you give an example of overloading the main()?

A: To overload the main() method you would have the same public visibility modifier, static method type, void return type and main method name but the type or number of arguments must vary.

Overloaded methods can provide versatility in a class and group similar behaviour with a common name. You may want to chain the standard main() method with an overloaded version that takes a conditional variable, key value or reference to signal further processing. This approach breaks down the program logic and indicates the overloaded main() method is associated with the standard version. The example below passes the original String[] arguments to an overloaded main(String[], int) method where the int argument is a key value for further processing.

… full answer hidden

Premium members click below for full answer
Can you give an example of overloading the main()?

Q: How can the JVM identify the main() method when its overloaded?

A: An overloaded main() method must have a different number and type of arguments from the standard entry point method, otherwise it would be identical and the class would not compile. The standard public static void main() method has a single argument which is of type String array, written String[].

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

The main() method below is overloaded because it has the same method name and return type but two arguments. The first String[] argument is the same as the standard main() entry point method, but the second int argument makes it different.

public static void main(String[] args, int index) {}
    

The final example below has the same method name and return type with one argument, like the standard main() method. In this case the type of the argument is String rather than String[] which makes it different.

public static void main(String arg) {}
    

Main method arguments

Q: What do the arguments in the main() method mean?

A: You can think of the arguments in the main method as a special set of variables that are fed into the program at start-up. The main arguments can be used to pass runtime configuration values for the program, such as the path to a properties file, or input values for the program to process. The arguments may also serve as commands to the application that invoke different operations.

Q: Which is the right syntax for the main() method?

A: The way the Java compiler interprets the syntax for the main method is evidently quite loose. The main method takes a String array as an argument, which is written as String[]. The name of the argument is usually given as args, so the proper method declaration is:

public static void main(String[] args)
      

However, you will often see this method written with the square brackets next to the argument name main(String args[]) and this is also accepted by the compiler. And main(String []args) is also accepted by the Sun Java compiler, which has been written to be fault tolerant.

Q: Can I name the main() argument argf?

A: Yes, the variable name you give to the String[] parameter in the public static main() method is up to you, the class will compile and run provided it is a valid Java variable name. You must be careful to reference the variable correctly throughout the method though. Unless you have good reason to change, it is worth sticking to convention and name the parameter args to avoid confusion for yourself, and other people who may read your code.

Q: Why does the main() method take a String array argument?

A: The static main() method takes a String array as an argument to provide a best match with the way that command line arguments are fed into a Java program. A Java program may be started with no command line arguments, in which case the String array is zero length, or it may have one or more arguments. The Java runtime system passes an array that matches the number of command line arguments that are given, so there is a direct correspondence between the program input and the data received by the main method.

Each storage slot in the String array passed to the main() method contains the String value of the relevant command line argument, indexed from zero. The example program below repeats the command line arguments in the order they are given.

… full answer hidden

Premium members click below for full answer
Why does the main() method take a String array argument?

Q: Why are command line arguments passed as a String?

A: Command line arguments are passed to the application's public static void main() method by the Java runtime system before the application class or any supporting objects are instantiated. It would be much more complex to define and construct arbitrary object types to pass to the main() method, and primitive values alone are not versatile enough to provide the range of input data that strings can. String arguments can be parsed for primitive values and can also be used for arbitrary text input, file and URL references.

Q: Why doesn't the main() method throw an error with no arguments?

A: When you invoke the Java Virtual Machine on a class without any arguments, the class' main() method receives a String array of zero length. Thus, the method signature is fulfilled. Provided the main method does not make any reference to elements in the array, or checks the array length before doing so, no exception will occur.

Q: How can I print the main method arguments in reverse order?

A: Command line arguments are passed to the main method as a string array, each argument is an item in the array. To print the submitted arguments in reverse order, use a for loop but start from the highest index and decrement the index value, as below.

… full answer hidden

Premium members click below for full answer
How can I print the main method arguments in reverse order?

Main method modifiers

Q: Can the main() method be declared final?

A: Yes, the static void main(String[]) method can be declared final.

Q: I get an exception if I remove the static modifier from main()!

A: The static void main(String[]) method is a basic convention of the Java programming language that provides an entry point into the runtime system. The main() method must be declared static because no objects exist when you first invoke the Java Virtual Machine (JVM), so there are no references to instance methods. The JVM creates the initial runtime environment in which this static method can be called, if you remove the static modifier, it will throw a NoSuchMethodError.

Q: What happens when I remove the static modifier from main()?

A: If you remove the static modifier from the standard main() method it becomes an instance method. If you then try to execute class the Java runtime system will fail and report:

Exception in thread "main" java.lang.NoSuchMethodError: main.
    

If you restore the static modifier and change the return type to int, for example, you get the same error. The runtime system expects a static main() method with the void return type, if you change either of these properties you may create a valid method but it will not be executed by the java command.

Calling the main() method

Q: Can I call the main() method with a String argument?

A: It is possible to change the name of the argument in the public static void main(String[]) method, but the argument type must be a String array. If you declare a String argument, it will make a valid method, but it cannot not be used as the standard entry point for your program, the Java runtime system would report an error.

Q: How many arguments can be passed on the command line?

A: The number of arguments that may be passed to a Java program will vary from one interpreter to another and will also be affected by the operating system's command interpreter. In a simple test, 169 arguments were passed to the Sun Java interpreter via a Windows batch script before it reported "The input line is too long". If your program requires a great number of input parameters, it would be better to pass a reference to a Java properties file on the command line and extract the input from that, as below.

… full answer hidden

Premium members click below for full answer
How many arguments can be passed on the command line?

Q: When I pass *.java as an argument I get a list of all my source files!

A: The behaviour you are seeing is a consequence of the way the system shell interprets the asterisk as a so called "wildcard" operator that represents a set of files. This is intended as a convenience because it is an easy way to pass a series of file names as arguments to a program such as the Java interpreter. Putting a partial file path before the asterisk, or a file extension after it makes the file listing more specific, but you cannot alter the fundamental behaviour.

To limit this behaviour, enclose any argument that contains an asterisk in double quotes, to ensure it is not expanded to a series of file names. An alternative is to omit the asterisk in the command line and write your program in such a way that the asterisk is implicit and add it to the input arguments where applicable.

Q: How can I make an interactive command line interface?

A: The key to creating an interactive command line interface in Java is to set up a continuous loop that reads the system input one line at a time. The example below captures the system input stream in an InputStreamReader and wraps that in a BufferedReader to read the input lines. It uses System.out to create a prompt and watches for a "quit" message to exit the loop.

… full answer hidden

Premium members click below for full answer
How can I make an interactive command line interface?

Application start up

Q: How can the static main method use instance variables?

A: For very simple programs it is possible to write a main method that only uses static variables and methods. For more complex systems, the main method is used to create an instance of itself, or another primary class, as the basis of the application. The primary application object reference uses instance methods to create and interact with other objects, do the work and return when the application terminates.

public class SimpleClass {

  public void doSomething() {

    // Instance method statements
  }

  public static main(final String[] args) {

    SimpleClass instance = new SimpleClass();

    instance.doSomething();
  }
}
          
Q: Can I invoke the main method from another class?

A: Yes, the main method can be called from a separate class. First you must prepare the string array of arguments to pass to the method, then call the method through a static reference to the host class, MaxFactors in the example below.

String[] arguments = new String[] {"123"};

MaxFactors.main(arguments);
      
Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager