Using Command-line Arguments

Many programs accept inputs while executing along with the program name. These inputs are called command-line arguments. Now we understood strings in Java, we can look into String args[] in the main function. Where args is an array of strings. This holds inputs we passed with the program name. The below program demonstrates this.

Program:

/*
This is a simple Java program about strings in Java.
Call this file CommandLineArguments.java.
*/

public class CommandLineArguments {
 // A Java program begins with a call to main().
 public static void main(String args[]) 
 {
  System.out.println("Total arguments passed are " + args.length);
  
  for(int i = 0; i < args.length; i++)
   System.out.println("Input " + (i+1) + ": " + args[i]);
 }
}

Java takes all input as String so, we need to change the data type of the value using some pre-defined function in java like:
Integer.parseInt();
and other functions that change a string into an integer or other datatypes.

we need to compile the file with the command:
javac CommandLineArguments.java

after complied we got a byte code that is CommandLineArguments.class
then we need to run that class file with the interpreter command and provide some name or parameter or argument that is the command-line argument, this argument store into String args[]  and then use in the program.
java CommandLineArguments C C++ Java Python

then the output will be:

Input 1: C
Input 2: C++
Input 3: Java
Input 4: Python



If have any query then you can mention it in the comment section our team will try to help you.

Thank You

Post a Comment

أحدث أقدم