Command Line Arguments in Java: A Comprehensive Guide
Table of Content:
Command-Line Arguments
Sometimes we want to pass information into a program when we run it. This is accomplished by passing command-line arguments to main( ).
The main method can receive string arguments from the command line
Acommand-line argument is the information that directly follows the program’s name on the command line when it is executed.
To access the command-line arguments inside a Java program is quite easy— they are stored as strings in a String array passed to the args parameter of main( ). The first command-line argument is stored at args[0], the second at args[1], and so on.
Program
// Display all command-line arguments.
class CmdLine {
public static void main(String args[]) {
for(int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Output
Process of Compilation and Execution
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Users\Hello World>cd desktop
C:\Users\Hello World\Desktop>cd Java
C:\Users\Hello World\Desktop\JAVA>javac CmdLine.java
C:\Users\Hello World\Desktop\JAVA>java CmdLine This is Commend-Line Argument Example
args[0]: This
args[1]: is
args[2]: Commend-Line
args[3]: Argument
args[4]: Example
C:\Users\Hello World\Desktop\JAVA>
Process of Compilation and Execution
Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Users\Hello World>cd desktop C:\Users\Hello World\Desktop>cd Java C:\Users\Hello World\Desktop\JAVA>javac CmdLine.java C:\Users\Hello World\Desktop\JAVA>java CmdLine This is Commend-Line Argument Example args[0]: This args[1]: is args[2]: Commend-Line args[3]: Argument args[4]: Example C:\Users\Hello World\Desktop\JAVA>
Perhaps we have already noticed the unusual header for the main method, which has the parameter args of String[] type. It is clear that args are an array of strings. The main method is just like a regular method with a parameter. we can call a regular method bypass- ing actual parameters. Can we pass arguments to main? Yes, of course, we can. In the fol- lowing examples, the main method in class TestMain is invoked by a method in A
Program
Save as:ClassA.java
public class ClassA { public static void main(String[] args) { String[] strings = {"New York","Boston", "Atlanta"}; TestMain.main(strings); } } Save as:MainMethod.java
public class MainMethod { public static void main(String[] args){ for (int i = 0; i < args.length; i++) System.out.println(args[i]); } }
Output
Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Users\Hello World>cd desktop C:\Users\Hello World\Desktop>cd java C:\Users\Hello World\Desktop\JAVA>javac MainMethod.java C:\Users\Hello World\Desktop\JAVA>java MainMethod if you succeed in cheating someone, dont't think that the pe rson is a Fool if you succeed in cheating someone, dont't think that the person is a Fool