BM Balmiki Mandal 06 May 2023 11 views 0 comments Core Java

Check If Command-Line Arguments Are Null In 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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023