Concept

What is the purpose of the main() method in a Java program?

ComputerScienceOne / Comments

"Every executable program has to have a beginning: a point at which the program starts to execute. In Java, a class may contain many variables and methods, but a class is only executable if it contains a main() method. When a Java class is compiled and the JVM is started, the JVM loads the class into memory and starts executing code contained in the main() method. In addition, our main() method takes an array of String types which serve to communicate any command line arguments provided to the program (review Section 2.4.4 for details). The array, args stores the arguments as strings. The number of arguments provided can be determined using the length property of the array. Specifically, args.length is an integer indicating how many arguments were provided. This does not include the name of the program (class) itself as that is already be known to the programmer. To access any one argument, it will be necessary to index the array. The index for the first argument is zero, thus the first argument is args[0] , the second is args[1] , etc. The last one would be at args[args.length-1] . If a user is expected to provide numbers as input, they’ll need to be converted as the args array are only String types. To convert the arguments you can use parsing methods provided by the Integer and Double classes. An example: 1 //converts the \"first\" command line argument to an integer 2 int x = Integer.parseInt(args[0]); 3 //converts the \"third\" command line argument to a double: 4 double y = Double.parseDouble(args[1]);"

Related Ideas

What is the purpose of the main() method in a Java program? | ComputerScienceOne | Bifalgorithm | Bifalgorithm