Signup/Sign In

Java Command line argument

The command line argument is the argument that passed to a program during runtime. It is the way to pass argument to the main method in Java. These arguments store into the String type args parameter which is main method parameter.

To access these arguments, you can simply traverse the args parameter in the loop or use direct index value because args is an array of type String.

For example, if we run a HelloWorld class that contains main method and we provide argument to it during runtime, then the syntax would be like.

java HelloWorld arg1 arg2 ...

We can pass any number of arguments because argument type is an array. Lets see an example.

Example

In this example, we created a class HelloWorld and during running the program we are providing command-line argument.

class cmd
{
    public static void main(String[] args)
    {
        for(int i=0;i< args.length;i++)
        {
            System.out.println(args[i]);
        }
    }
}

Execute this program as java cmd 10 20 30

10 20 30

To terminate the program in between based on some condition or program logic, Java provides exit() that can be used to terminate the program at any point. Here we are discussing about the exit() method with the example.

Java System.exit() Method

In Java, exit() method is in the java.lang.System class. This method is used to take an exit or terminating from a running program. It can take either zero or non-zero value. exit(0) is used for successful termination and exit(1) or exit(-1) is used for unsuccessful termination. The exit() method does not return any value.

Example:

In this program, we are terminating the program based on a condition and using exit() method.

	
import java.util.*; 
import java.lang.*; 

class ExitDemo1
{ 
    public static void main(String[] args) 
    { 
        intx[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; 

        for (inti = 0; i<x.length; i++) 
        { 
            if (x[i] >= 40) 
            { 
                System.out.println("Program is Terminated..."); 
                System.exit(0); 
            } 
            else
                System.out.println("x["+i+"] = " + x[i]); 
        } 
    } 
}
	

system-exit-program