Command Line Argument in Java
class Arguments
{
public static void main(String[] args)
{
for (String t: args)
{
System.out.println(t);
}
}
}
Let’s break down the program step by step.
Step-by-step explanation:
1. class Arguments
This is a class declared as Arguments. A class in Java is a blueprint to create objects. In this class, it holds the main method which is the entry point of the program.
2. public static void main(String[] args)
This is the main method where the Java programs start execution.
- public: The method is public that is, accessible from outside the class and the JVM may call it.
- static: A static method may be invoked using the name without having created an instance of the class at all.
- void: The return type of this method is void. It doesn’t return anything.
- String[] args: This is an array of strings passed as command-line arguments when you run the program. args[] will hold the values passed from the command line, and these values are accessed inside the program.
3. for (String t: args)
This is the enhanced for loop; it is called also the “for-each” loop as it iterates for each element from the array args[].
- String t: It declares a variable t of type String, holding each element- which in this case, for every iteration, is an argument that is present in the args[] array.
- args: It is the list in which arguments to the application during its execution come in.
- This is the syntax of the loop indicating that the program will loop through each element in args[] and assign them one by one to t.
4. System.out.println(t);
- Within the for loop, it prints the present value of t to the console.
- System.out.println(t);: prints the contents of the t – which is one of the command-line arguments – in the console after a new line.
5. Closing braces }
- The closing bracket } serves as a for-loop ending delimiter.
- The final closing brace } that indicates the main method end, and hence marks the Arguments class.
Program Behavior
- No fixed value inside the program.
- It relies entirely on command line arguments given in the system through which you’re running your program.
- All given arguments are printed line by line.
Example Run
Suppose the program is executed with the following command-line arguments:
java Arguments Hello World from TechSarvam
Here,
the args[] array will have four elements: [ "Hello", "World", "from", "TechSarvam"].
At runtime:
The for loop will iterate over these elements, and each element will be printed one by one.
Output:
Hello
World
from
TechSarvam
Each word (argument) passed on the command line is printed on a new line.