0

I have this code here:

try {
    System.out.print("There are args!: " + args[0]);
} catch (Exception e) {
    System.out.print("No args");
}

I am checking if arguments were passed when I executed the program. If no arguments are passed, and I try to print the first index of arguments, an Exception is thrown. I can use a Try-Catch block to catch the Exception, and declare there is no arguments.

How could I do this with an 'If Statement'?

I tried:

if (args[0] == null)

//And

if (args[0] == '')

And still got an Exception. What is "args[0]" equal to if no arguments are passed?

....................

STC2
  • 23
  • 4

1 Answers1

3

args is a normal array. If you try to access an item beyond the last index (args[0] when args is empty, for example), then you'll always get an exception.

To avoid it, you can test its length before accessing the element:

if (args.length > 0) {
    System.out.println("We have one or more arguments.");
    // You can safely use `args[0]` here.
}
BoppreH
  • 8,014
  • 4
  • 34
  • 71