dsa

Java Command-Line Arguments

Command Line Argument in Java is the information that is passed to the program when it is executed. The information passed is stored in the string array passed to the main() method and it is stored as a string. It is the information that directly follows the program’s name on the command line when it is running. 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.

Command Line Arguments in Java: Important Points

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.

class CommandLineExample{  
public static void main(String args[]){  
System.out.println("Your first argument is: "+args[0]);  
}  
} 
 
compile by > javac CommandLineExample.java  
run by > java CommandLineExample sonoo
       Output: Your first argument is: sonoo

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.

// A Java program to demonstrate working of exit() 
import java.util.*; 
import java.lang.*; 

class Codemistic 
{ 
	public static void main(String[] args) 
	{ 
		int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; 

		for (int i = 0; i < arr.length; i++) 
		{ 
			if (arr[i] >= 5) 
			{ 
				System.out.println("exit..."); 

				// Terminate JVM 
				System.exit(0); 
			} 
			else
				System.out.println("arr["+i+"] = " + 
								arr[i]); 
		} 
		System.out.println("End of Program"); 
	} 
} 
Output:
Output:

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
exit...