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


        // All good, n is either default (0) or user entered value
        while(true) {

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

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


Leave a Comment