Write a program to check if the program has received command line arguments or not in Java
Write a program to check if the program has received command line arguments or not in Java

Write a program to check if the program has received command line arguments or not in Java

Posted on

In Java, the main method is the entry point for a Java program. It is a static method that is called by the Java Virtual Machine (JVM) when the program is executed. The main method has the following signature

public static void main(String[] args)

The 'args parameter is an array of String objects that represents the command line arguments passed to the program.

To check if the program has received command line arguments, you can use the length property of the args array. Thelength property is an integer that represents the number of elements in the array. If the 'length is 0, then no command line arguments were received. If the length is greater than 0, then command line arguments were received.

Here is an example of how to check if the program has received command line arguments in Java:

public class Main {
  public static void main(String[] args) {
    if (args.length == 0) {
      // No command line arguments were received
      System.out.println("No command line arguments received");
    } else {
      // Command line arguments were received
      System.out.println("Command line arguments received: " + Arrays.toString(args));
    }
  }
}

This code first checks the length' of the args array. If it is 0, then the if block is executed and a message is printed out indicating that no command line arguments were received. If the 'length' is greater than 0, then the else block is executed and a message is printed out indicating that command line arguments were received, along with the list of arguments using the Arrays.toString method.

To run this program from the command line and pass in command line arguments, you can use the following syntax:

java Main arg1 arg2 arg3

This will call the 'main' method with an 'args array that contains the following elements: ["arg1", "arg2", "arg3"]. The program will then print out the following output:

Command line arguments received: [arg1, arg2, arg3]

You can pass in any number of arguments, separated by spaces. If you don’t pass in any arguments, then the args array will have a 'length' of 0 and the if' block will be executed.

Leave a Reply