Skip to content Skip to sidebar Skip to footer

Write Program That Continues Taking Command line Arguments Java

Command line arguments in java

Updated - 11 Feb 2022 7 mins read Published : 31 Aug 2021

Published : 31 Aug 2021

Every program deals with some type of data. This data can be either provided to it by the user or the programmer. The user hardly provides a big input to process. Whereas the programmer needs to provide various different types of data inputs for efficient testing. Now, this process may end up eating a lot of time on either manually entering inputs or hard coding data variables. We need to come up with a solution where we can do efficient testing with minimum effort and time.

There are various ways to provide input to our program. One of these ways is to provide input through the command line through which we also compile and run our program. These inputs are passed to the main function at runtime even before our main() begins to execute. The image below represents the two ways by which we can write our main function in Java. The argument String[] args or String… args can be broken down as follows.

String : It denotes that the main function is inputting an array of data type string. Here string is used because Java always uses string data type whenever it performs any input or output operations.args : this is the local name of the passed array variable with which we can access and modify the values stored in it.

              
                                      public                                                            static                                                            void                                                            main                    (String[] args)                    {                                                                                // Statements                                                            }                                        public                                                            static                                                            void                                                            main                    (String... args)                    {                                                                                // Statements                                                            }                                  

The command line inputs that are given to the program are stored in these main function parameters.

Java programs are compiled and run by

Compile > javac filename.java

Run > java filename

How are Command Line Inputs Processed?

In order to execute our program, we need to compile the .java file using the above-stated command. This converts our .java file to .class file. This class file is in a machine-readable language. Later we execute this file using the run command.

If we provide inputs following this command the JVM (Java Virtual Machine) wraps all these inputs together. It then supplies it to the main function parameter String[] args or String… args. This process takes place even before our main() is even invoked. These inputs are called command line arguments. Since these inputs are passed to our application before its execution, they provide us a way to configure our application with different parameters. This helps us in doing efficient testing of our application.

How to Pass Command Line Arguments In Java?

In order to pass command line arguments in Java, we need to follow the following steps.

  1. Write your java program and save it with .java extension in your local system
  2. Open your cmd(command prompt) and navigate to the directory where you saved your program
  3. Compile your program using command 'javac filename.java'. This will convert the .java file to .class file
  4. Write the run command 'java filename' and continue the command with all the inputs you want to give to your code
  5. After writing all your inputs, run your command

How to Access Java Command Line Arguments?

The command line inputs given to the program are bundled and supplied to the main function parameter even before the invoking of the main function. These inputs are stored in a string array since Java deals with strings whenever it performs I/O operations.

Since the inputs are distinguished from one another by the blank space ' ' between them. The command line reads one character at a time and stores it. When it encounters a space it saves the already collected text as an input value and repeats the process until all characters are read.

Code:

              
                                      public                                                            class                                                            cmdArgs                    {                                                                                public                                                            static                                                            void                                                            main                    (String[] args)                    {                                                              System.out.println(                    "The number of command line inputs entered are "                    +args.length);                                                                                for                    (                    int                                          i=                    0                    ;i<args.length;i++)                                                              System.out.println(                    "input "                    +i+                    " is "                    +args[i]);                                        }                     }                                  

Output after our execution command the following text is given

              
                                      PS C:\MinGW\bin> Java cmdArgs.java                    PS C:\MinGW\bin> Java cmdArgs apple banana mango graes orange                    The number of command line inputs entered are                                        5                                                            input                                        1                                          is apple                                        input                                        2                                          is banana                                        input                                        3                                          is mango                                        input                                        4                                          is grapes                                        input                                        5                                          is orange                    PS C:\MinGW\bin>                                  

The figure below gives a step by step walkthrough of how the command line inputs are read.

As soon as the run command gets executed, the inputs following it are read as strings into the main function parameter.

This is done in such a way that the JVM reads every string individually when it encounters a character. As it reads a space character it saves the string and starts with another string. This restricts the user to enter sentences as a command line input.

Command line arguments in java

How to Modify Command Line Arguments in Java?

The command line inputs are read as strings by the compiler and stored in an array. We can modify them by using the reference operator'[]'. The following program shows an example where we read the command line arguments and later modify them.

Here the input is accessed using the '[]' operator and then we assign a new value to it. This assigned value overwrites the previous input.

Code:

              
                                      public                                                            class                                                            cmdArgs                    {                                                                                public                                                            static                                                            void                                                            main                    (String[] args)                    {                                                              System.out.println(                    "The number of command line inputs entered are "                    +args.length);                                                              System.out.println(                    "The inputs are as follows"                    );                                                                                for                    (                    int                                          i=                    0                    ;i<args.length;i++)                                                              System.out.println(                    "input "                    +(i+                    1                    )+                    " is "                    +args[i]);                                                              args[                    1                    ]=                    "this input was changed"                    ;                                                              System.out.println(                    "Inputs after modification are"                    );                                                                                for                    (                    int                                          i=                    0                    ;i<args.length;i++)                                                              System.out.println(                    "input "                    +(i+                    1                    )+                    " is "                    +args[i]);                                        }                     }                                  

Output:

              
                                      PS C:\MinGW\bin> Java cmdArgs                                        1                                          a black                                        98765                                          $%^ !@                                        The number of command line inputs entered are                                        6                                                            input                                        1                                          is                                        1                                                            input                                        2                                          is a                                        input                                        3                                          is black                                        input                                        4                                          is                                        98765                                                            input                                        5                                          is $%^                                        input                                        6                                          is !@                    Inputs after modification are                    input                                        1                                          is                                        1                                                            input                                        2                                          is                                        this                                          input was changes                                        input                                        3                                          is black                                        input                                        4                                          is                                        98765                                                            input                                        5                                          is $%^                                        input                                        6                                          is !@                    PS C:\MinGW\bin>                                  

Important Points about Command Line Inputs in Java

  • Command line inputs need to follow the java filename in the command that executes our code
  • Almost all data types are read as string but '#', '%', '&' throw an error when entered through the cmd
  • Command line inputs provide users an alternative way to give inputs
  • They are easy to access and we can operate on them just like normal arrays
  • For entering large inputs we have third party libraries like Picocli and Spring Shell
  • These are libraries which are smaller in size and help us to create java command line applications. They are memory efficient and faster than other libraries
  • A Java application can accept any number of arguments from the command line.There is no restriction on the number of inputs entered through command line into the main function parameter
  • For example: If we are developing an application that deals with millions of customer's data at once it would be challenging every time to test our application for such a huge data set. This task can be simplified if we use command line inputs with 3rd party libraries
  • Command line inputs are passed as strings to the main function parameter
  • For example: 123 abc @@@ if supplied as java command line arguments they are read as strings "123", "abc" and "@@@"
  • Command line inputs can be very useful in testing and running our applications
  • Initialisation Since these inputs are provided before execution they provide us with a method to initialise our application with data values of our choice, otherwise the same work would have been done by the code after it begins its execution For example we need to test our program for real life conditions with a huge data set. Now entering these inputs one by one will be impractical. In these cases if we use command line inputs we could just copy our data with the execute command and provide a huge input easily and quickly to our program
  • Application Testing Providing different input values helps us to test our programs working. This task can be difficult if we are made to provide test values manually again and again. Command line inputs enable us to reduce our effort and run multiple test values and test our program.This enables us to create different real life situations for our code to test and debug. For example: Rather than providing every test input separately we could supply complete test data by command line inputs at once and test the program in less time.

Conclusion

Hence we can conclude that command line inputs in java are a great alternative way to provide input to our applications and also they are easy to learn and implement. This method uses a conventional array where inputs are stored as strings and this makes its modification easy.

Challenge Time!

quiz

quiz

Time to test your skills and win rewards!

Note: Rewards will be credited after the next product update.

martineztogirtanot.blogspot.com

Source: https://www.scaler.com/topics/command-line-arguments-in-java/

Post a Comment for "Write Program That Continues Taking Command line Arguments Java"