what are command line arguments in java
Command line arguments in Java are inputs you pass to a program when you
start it from the terminal or command prompt. They are received by the main
method as a String[] args array, so each argument is available as a separate
string.
Quick Scoop
If you run a Java program like this:
bash
java MyApp hello 10 world
then hello, 10, and world are the command line arguments. Inside the
program, you can read them with args[0], args[1], and args[2].
How They Work
- The JVM puts everything after the class name into the
argsarray.
- You can check how many arguments were passed with
args.length.
- Arguments are separated by spaces, and quoted text counts as one argument.
Example
java
class Main {
public static void main(String[] args) {
System.out.println("First arg: " + args[0]);
System.out.println("Total args: " + args.length);
}
}
If you run:
bash
java Main Java Rocks
the output would be:
bash
First arg: Java
Total args: 2
Important Note
All command line arguments arrive as strings, even if they look like numbers. If you need an integer or double, you must convert it in your code.
If you want, I can also show you how to use command line arguments in a complete Java program.