How to change Java command line arguments

How do you check that your code does not contain errors, that it works in all situations and handles all borderline cases?

The easiest option is to test the code on all possible test cases. But there can be a lot of them, which makes the testing process itself difficult and costly. We need another way — which can solve the problem easily, and which can be automated for large input data. Command line arguments in Java are one of those.

In this article we will briefly discuss what command line arguments are, how they are passed and how they work, but our main focus will be on how to modify Java command line arguments.

What are Java command line arguments?

Java command line arguments allow you to pass arguments during program execution directly from the console, which will be accessed by the main() method. It also allows you to use them as input data or bypass command-line arguments by passing values directly to the main() method.

Code snippet:

// здесь args будет содержать аргументы командной строки
    public static void main(String[] args) {
        System.out.println("Привет, мир!");
        // оставшийся код будет здесь
    }

How do command line arguments work?

Command line arguments that are provided at runtime are packaged and passed to args[].

Args[], in fact, is a String array that contains all the arguments passed to it. Each of them will be stored by index, starting with args[0] and ending with args[n].

How do I pass command line arguments?

Command line arguments are passed through command lines or terminals. All arguments passed through them will be converted to an array of args[] inside the JVM.

Examples

Suppose we have a file with some Java code.

How to pass command line arguments in java:

  1. Save the Java program with the extension .java (for example, Arguments.java ).
  2. Open a terminal/command prompt in the directory where the program is stored locally.
  3. Compile a Java program to convert the file.java in .class;
    Command: javac filename.java (here javac Arguments.java ).
  4. Run the program and pass arguments after the file name, separated by spaces;
    Command: java file name argument1 argument2 …. argumentsN (here java Arguments).

How do I access the command line arguments?

Now let’s try now to access all the passed command line arguments in JAVA.

Since these arguments are stored in the args array[], we can access them using args[i], where i is the index, which can range from 0 to n (the total number of arguments passed).

Code:

Аргументы класса {
    public static void main( String[] args ) {
        System.out.println("Привет, мир!");
        // args.length используется для получения длины массива args

        System.out.println(" Общее количество аргументов: " + args.length);
        // итерация по массиву args для вывода аргументов, если они доступны

        for (int i = 0; i < args.length; i++) {
            System.out.println("Аргумент" + i + ": " + args[i]);
        }
    }
}

Exit:

Привет мир!
 Общее количество аргументов: 7
 Аргумент 0: Добро пожаловать
 Аргумент 1: в
 Аргумент 2: это
 Аргумент 3: блог
 Аргумент 4: и
 Аргумент 5: Счастливый
 Аргумент 6: Обучение

How do I change the command line arguments?

We can use args[i] to get the value by the i-th index. And then, using the assignment operator (=), change the argument by the i-th index.

The code below will change some of the arguments passed through the command line in Java.

args[1] = "Измененный аргумент командной строки 1";
args[3] = "Измененный аргумент командной строки 2";
args[5] = "Измененный аргумент командной строки 3";

Updated output:

Привет мир!
 Общее количество аргументов: 7
 Аргумент 0: Добро пожаловать
 Arg 1: измененный аргумент командной строки 1
 Аргумент 2: это
 Arg 3: измененный аргумент командной строки 2
 Аргумент 4: и
 Arg 5: измененный аргумент командной строки 3
 Аргумент 6: Обучение

In a nutshell

  • Java command line arguments are a way of entering data into a program via the command line.
  • The command line arguments are passed when executing the startup command immediately after the file name and are separated by spaces.
  • Command line arguments are accepted by an array of strings ( args[] ) in the main function.
  • We can access the command line arguments or change them using args[i] and assignment operators.

Tech Outsourcing | Dedicated Software Team

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png