12

For example

public static void main(String[] args) {
            int count = 0;
        for (String s: args) {
            System.out.println(s);
                count++;

        }

    }

is there some way of doing something like

int count = args.length()? or args.size()?

user1464251
  • 333
  • 1
  • 2
  • 16
  • As everyone else has said, args.length is better. This is because the method of counting, while 100% valid, takes `n` loops, where `n` is the length of the array, whereas accessing args.length takes `1` loop, making it far faster. You can't change the `length` field, but you can still access it (we call this "final"). – Ryan Amos Jul 25 '12 at 14:21
  • So many duplicate answers. Do we really need 6 answers for using array's `length` field? – Steve Kuo Jul 25 '12 at 16:20

6 Answers6

18

It would be:

int count = args.length;
jrad
  • 3,172
  • 3
  • 22
  • 24
  • Thanks, I was getting errors using args.length() with the brackets. I didn't see any reason why I should be able to do that. Silly mistake, thanks. – user1464251 Jul 25 '12 at 14:24
  • Arrays are special in Java, and carry `length` as a member field rather than a method call, so no parentheses. When using the [Java Collections](https://en.wikipedia.org/wiki/Java_collections_framework), such as `ArrayList`, you would be calling the [`size()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#size()) method, and parentheses are required. Now that I think about it, it would be worth filing a feature-request to ask that a `size()` method be added to arrays, as syntactic sugar, just for the sake of consistency and convenience. – Basil Bourque Feb 26 '19 at 20:16
4

is there some way of doing something like

int count = args.length()? or args.size()?

Yes, args.length.

There is nothing special about args; it is a regular array of String objects and may be treated as such.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
2

All arrays have a "field" called length

int count = args.length;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2
public static void main(String[] args) {
    System.out.println(args.length);
}
Devin Hurd
  • 318
  • 2
  • 6
2

"args" is just an array, so you can use it's length property.

Like this:

System.out.println(args.length);

and you are good to go.

Cristiano Fontes
  • 4,920
  • 6
  • 43
  • 76
1

Simply use
int length=args.length

args is simply an array and you can use it's length property.

Sumit Desai
  • 1,542
  • 9
  • 22