Search code examples
javamenuargumentsargs

main method String[] args issue


I'm reading Sams Teach Yourself Java in 24 Hours and came across this code:

class NewRoot {

   public static void main(String[] args) {
      int number = 100;
      if (args.length > 0) {
         number = Integer.parseInt(args[0]);
      }
      System.out.println(“The square root of “
           + number
           + " is "
           + Math.sqrt(number));
   }
}

But in order for the code to be compiled, the writer enters 169 in the Arguments field in the

Run>Set Project Configuration>Customize

menu (in NetBeans IDE).

So my question is: what's the purpose of the specific field? Does 169 means something or is it just a random number? It's a pity the writer doesn't say anything about it!


Solution

  • The author is giving you an example of running a program with arguments given via the terminal. This is usually done in your terminal or command prompt by running the code as such

    javac ProgramName.java
    java ProgramName <arguments>
    

    Since you are writing and running your program in Netbeans, and wont be using the terminal, you can configure to run the project with a given command line argument. This is what you are doing in the netbeans menus.

    The String "169" only has meaning for the given program. The author is trying to demonstrate how the program will run given a command line argument, in this case he sets it to an arbitrary value "169." In your code you are taking this String and turning it into an int.