Home » Java programming language

Command Line Arguments in Java with Example

Learn: What is Command Line Arguments in Java with examples, how it works?

In java, we can also provide values (arguments) while calling the program through command line. These arguments are known as Command Line Arguments.

The type of arguments are strings, we can pass multiple arguments (as strings) with the command name. Thus, we can say that it’s (command arguments) an Array of Strings.

Note: All values passed through command line are considered as strings.

Have a look of main() method’s syntax in java

public static void main(String args[])

Here, String is class and args[] is array of Strings.

Java - Command Line Arguments Example

This program will print all the given arguments passed through command prompt while executing the program through java executable command.

class CLA_Example{
	public static void main(String args[]){
		System.out.println("Arguments are:");
		
		//printing all arguments
		for(int i=0; i<args.length; i++){
			System.out.println("args[" + i +"]: " + args[i]);
		}
	}
}

Compile

javac CLA_Example.java 

Execute/Run

java CLA_Example Hello world "Hi, there how are you?" 28 
Arguments are:
args[0]: Hello
args[1]: world
args[2]: Hi, there how are you? 
args[3]: 28 

Count total number of command line arguments in Java

args.length returns the total number of arguments.

class CLA_Example{
	public static void main(String args[]){
		System.out.println("Total arguments are: " + args.length);
	}
}

Compile

javac CLA_Example.java 

Execute/Run

java CLA_Example Hello world "Hi, there how are you?" 28 
Total arguments are: 4


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.