Language Fundamentals - main()
Syntax
public static void main(String[] args) {
// method body
}
- entry point for a Java application
- required by all Java applications (not required in Applets)
- must be declared public static void
- void must appear before main()
Example:
static public void main(String[] args){} // legal
public static void main(String[] args){} // legal
public void static main(String[] args){} // illegal
- can also be declared final
- main() has only one argument: a String array
- the argument can be declared in many ways and the variable name does not have to be args
Example:
main( String args[] )
main( String [] args )
main( String[] params )
main( String[] args ) // standard convention
- the args array is used to access command line arguments
Example:
java MyApp test this out
- the args array uses a zero based index therefore args[0] would return "test" in the above example
- an application can have more than one main() method as every class can have a main() method
- which main() is used by an application depends on the class started at runtime
- advantage is that each class can use it's own main() as a testing structure for the class
- main() is inherited and can be overridden if not declared final
Code compiled with JDK 1.3 will work ok even it is declared private, protected or has no access modifier; however, for the purpose of the certification exam the correct method declaration is
public static void main(String[] varname)
(see discussion at JavaRanch)
Code Examples
Tips
- main() can be declared final
- main() is inherited and can be overridden if not declared as final
- args[0] references first command line argument after the application name ( arrays in Java are zero-based)
- main() can be declared public static void ... or static public void ...
- the variable name does not have to be args; can be anything as long as the type is String[]
Traps
- main() declared other than according to the standard convention
|