How to Find the Number of Arguments Provided at Runtime in Java?
Last Updated :
11 Nov, 2020
The Java command-line argument is an argument that is passed at the time of running of a program. i.e. in order to make a program dynamic, there may be cases where we pass the arguments at runtime. Usually, via command-line arguments, they get passed and there are ways to find the number of arguments provided and also get the value of each argument.
Each Java program gets initiated via the main method which is static that means no instantiation is required for the main method. Directly we can call. Hence, a java file name is called, the first method to get started is main() method and it has an input argument which is of String[] (String array datatype)
Syntax :
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
}
}
|
When java code is run, we can pass arguments at runtime as
command prompt > java <filename> argument1 arguement2 ……..
or inside any favorite IDE like Eclipse also we can pass arguments at runtime as attached in screenshots
Example 1:
Java
public class GFG {
public static void main(String[] arguments) {
String wordToFind = "GFG." ;
System.out.println( "Arguments passed at runtime. " +
"We can get that by using args.length and it is " +
arguments.length + " here " );
for ( int i = 0 ; i < arguments.length; i++) {
if (arguments[i].equalsIgnoreCase(wordToFind)) {
System.out.println( "Provided word " +
wordToFind + " is present " +
"and it is at location " + (i+ 1 ));
}
}
}
}
|
In Eclipse, we can provide arguments in the mentioned way :
Screen 1
Screen 2
Under Java Application –> Click on Arguments. Under Program Arguments, provide the required arguments as specified in the below screen
On running the code, we can see below output
Example 2: Find out whether “GFG” is provided in the command line arguments
Java
public class GFG {
public static void main(String[] arguments) {
System.out.println( "Arguments passed at runtime. " +
"We can get that by using args.length and it is = " +
arguments.length + " here " );
for ( int i = 0 ; i < arguments.length; i++) {
System.out.println( "Argument " + i + " = "
+ arguments[i]);
}
}
}
|
Using the command prompt, we can find the arguments as shown in the image below:
We can run the Java program using cmd prompt and the command line to find the number of arguments is:
java Class_Name “Statement “
It will give us the number of arguments in the double quotes.
Share your thoughts in the comments
Please Login to comment...