CSS font stacks, media style sheets & web standards

Your banner ad here

WestNIC provides reliable web hosting services

25% off cpanel web hosting and reseller hosting deals. Promo: codestyle25off

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQs, or choose the single FAQ by email option for premium answers.

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
How can I write a program that takes command line input?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
What does public static void main(String[]) mean?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can you give an example of overriding 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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
Can you give an example of overriding the main()?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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

A: Command line arguments are passed to the application's 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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
How can I print the main method arguments in reverse order?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Main method modifiers

Q: Can the main method be declared final?

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

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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 NoSuchMethodException.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
How many arguments can be passed on the command line?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
How can I make an interactive command line interface?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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();
  }
}
          

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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);
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log