Command line arguments

Command-Line Arguments in Java

Command-line arguments are values provided to a program when it is run from the command line or terminal. They allow you to pass inputs to your program without modifying the source code. In Java, you can access these command-line arguments through the String[] args parameter of the main method. Each argument is separated by spaces.

Here's how you can use command-line arguments in Java:

  1. Open a command-line interface or terminal.
  2. Navigate to the directory containing the compiled Java class files.
  3. Run the Java program using the java command followed by the class name and command-line arguments. For example:
            
              java MyProgram arg1 arg2 arg3
            
          

Inside the Java program, you can access the command-line arguments through the args parameter of the main method. The arguments are stored as an array of strings, with each argument accessible by its index.

Here's an example that demonstrates the usage of command-line arguments in Java:

    
      public class CommandLineExample {
        public static void main(String[] args) {
          System.out.println("Number of arguments: " + args.length);
          System.out.println("Arguments:");

          for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + ": " + args[i]);
          }
        }
      }
    
  

In this example, the program prints the number of command-line arguments provided and displays each argument individually. You can run this program from the command line and pass different arguments to observe the output.

Prev‹

Post a Comment

Previous Post Next Post