Command line argument in JAVA
Table of Contents
Command line argument in JAVA
Java Command line argument
An argument is passed to a program runtime as part of the command line argument in Java. This is how the main method in Java is passed arguments. The main method’s args parameter, which is of the String type, stores these arguments. Since args is an array of type String, you can simply use the args parameter’s loop traversal or use the direct index value to access these arguments.
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
So 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. So 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.
Command line argument 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]);
}
}
}