Bifalgorithm post · Computer science one · Comments

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

What is the purpose of the main() method in a Java program? (Computer science one · Comments) — "Every executable program has to have a beginning: a point at w…

Ideas in this flowchart

  • Java program execution begins through the main() method and can receive command-line arguments.
  • Every executable program must have a beginning point where execution starts.
  • A Java class is executable only when it contains a main() method.
  • When the JVM starts, it loads the class and executes the code in main().
  • The main() method accepts an array of String values named args.
  • The args array stores command-line arguments as strings.
  • The args.length property gives the number of provided arguments as an integer.
  • The argument count excludes the program or class name.
  • Arguments are accessed by array index, beginning with zero.
  • Numeric command-line arguments must be converted because args contains only strings.
  • Integer.parseInt(args[0]) converts the first argument to an integer.
  • Double.parseDouble(args[1]) converts the second argument to a double.
Feed/

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

No cover

Channel

Computer science one

1 page

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

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.