Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 101, how do I count the number of arguments passed into main?

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()?

like image 366
user1464251 Avatar asked Jul 25 '12 14:07

user1464251


People also ask

How do you count the number of arguments in Java?

java Class_Name “Statement “ It will give us the number of arguments in the double quotes.

How many number of arguments can be passed to main () in Java?

3. Number of arguments can be passed to main() is? Explanation: Infinite number of arguments can be passed to main().

What is the method used by JVM to count the number of arguments passed in command line?

Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass into the main() function. We can check these arguments using args. length method. JVM stores the first command-line argument at args[0], the second at args[1], the third at args[2], and so on.

Can we pass arguments in main () in Java?

Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.


2 Answers

All arrays have a "field" called length

int count = args.length;
like image 86
Peter Lawrey Avatar answered Oct 24 '22 00:10

Peter Lawrey


public static void main(String[] args) {
    System.out.println(args.length);
}
like image 41
Devin Hurd Avatar answered Oct 23 '22 22:10

Devin Hurd