In Java, how to assign the variable number=Integer.parseInt(args[0]) a value if no argument is passed?

You could assign value of n as 0 or any other value by default and use if(args.length > 0) { to check whether any arguments is given. Below is full example with comments:

public class Infinity {
    public static void main(String args[]) {

        /*
        Start by assigning your default value to n, here it is 0
        If valid argument is not given, your program runs 
        starting from this value
        */
        int n = 0;

        // If any arguments given, we try to parse it
        if(args.length > 0) {

            try {
                n = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.err.println("Argument" + args[0] + " must be an integer.");

                // Program ends
                System.exit(1);
            }

        }

        // All good, n is either default (0) or user entered value
        while(true) {
            System.out.println(n);
            n++;
        }
    }
}

Note: Users which are not so familiar with java, this program can be run by:

  1. Saving it to Infinity.java
  2. Compiling it with cmd or terminal by writing: javac Infinity.java
  3. Executing it with: java Infinity or java Infinity 1000 (or any other value)

Cheers.

Leave a Comment