4

I'm building a Java application that takes a varying number of command line options as input, with a file name consistently the last item. When I specify the argument index in the second line below (e.g. args[2], everything does of course work correctly when I know the index ahead of time, but I'm having trouble coming up with the correct syntax for accessing the final item in a String[] when dealing with a file or even just a string as the input vs. an array of integers or something simpler for when that index number varies.

public static void main(String[] args) {

    String inFile = args.length-1;
MarkCoder
  • 69
  • 5

3 Answers3

5

You have to use

String inFile = args[args.length-1];
//array name    ^^^
//last index value   ^^^^^^^^^^^^^^
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
4

Try:

String inFile = args[args.length - 1];
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
3

If you are often needing this functionality you can encapsulate it into a method:

public static <T> T last(T[] them) {
    return them != null && them.length > 0 ? them[them.length - 1] : null;
}

public void test(String[] args) throws Exception {
    String fileName = last(args);
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Fine but note that the null check is dead code as `String[] args` cannot be null in a main() method. – davidxxx Apr 06 '18 at 15:03
  • 1
    `null` can be an element in the array, so it shouldn't be returned as the "error" value. Better to throw `NullPointerException` if `them` is `null`, and `NoSuchElementException` if it is empty. – Andy Turner Apr 06 '18 at 15:05