Check If Command-Line Arguments Are Null In Java

06 May 2023 Balmiki Mandal 0 Core Java

Check if Command-Line Arguments Are Null in Java

The command-line argument is the argument passed to a program when it is invoked. It allows you to pass values to a program while it is running and it can be used to customize the behavior of the program. In Java, the command line arguments are stored in a string array that is passed to the main method when the program is executed.

When working with command-line arguments in Java, you might need to check if the argument supplied is null or not. This can be done using the length attribute of an array. The length attribute returns the number of elements stored inside the array. If the length of the array is zero, then it means that there are no command-line arguments supplied.

Here’s a simple example of how to check for null command-line arguments in Java:

public static void main(String[] args) {

  // Check if command-line argument is null
  if (args.length == 0) {
    System.out.println("No command-line arguments supplied!");
  }
}

In the code above, we are checking the length of the args array. If the length of the array is equal to zero, then it means that no command-line argument was supplied. You can also check for specific arguments instead of just checking for null. Here’s an example:

public static void main(String[] args) {

  // Check for specific argument
  if (args[0].equals("foo")) {
    System.out.println("foo found!");
  }
}

In the code above, we are checking the first element of the args array to see if it equals “foo”. If it does, then the statement will be printed.

In this tutorial, we have discussed how to check if command-line arguments are null in Java. We have seen two examples of how to do this - one using the length attribute of an array and the other using the equals() method of a string.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.