A typical java file starts with it’s class name and for beginner programmers, you’ll usually have a public static void main(String[] args) line a couple lines below that class name too.
Many beginner programmers aren’t taught what exactly the String[] args part means though. They’ll learn arrays eventually but they still won’t understand the point of it. It does have uses though and many of them can be useful and convenient.
Instead of explaining example uses and rambling about for a while, let’s just see the code and how one might use it.
public class App1 { public static void main(String[] args) { if ( args.length <= 1 ) { System.out.println("Enter your first and last name like so:\njava App1 ryan rampersad"); } else if ( args.length == 2 ) { System.out.println( "Hey, how's it going, " + args[0] + " " + args[1] ); } } }
In the console, command prompt or terminal, you can enter this to run the code:
java App1 your_first_name your_last_name
When I enter my name, it returns to me, Hey, how’s it going, ryan rampersad.
Basically, the program uses the space after the java filename as command-line arguments. These can be quite handy when you have an interface inside the program, but also want to provide a shortcut for power-users. For instance, lets say inside of the program, you provide a menu for a list of tasks, one of which could be opening a file and editing it in some way. You could provide a shortcut option, a command-line argument that accepts a string filename to initiate the editing method as soon as the program starts instead of forcing the user to go through all of your menus.
That’s the power of java command-line arguments. They’re helpful and pretty easy to use.
this is very informative. i have always wondered about that. thank you very much.
You are the man. It is great to see people helping us newbs. I am somewhere in my second year of an online BCS program, and contributions like this really help. Thanks again and keep it up.
can we pass int array in main() in place of String array.
I’m pretty sure the Java bootstrapper will insist upon a String array. That said, you can put numbers into the terminal arguments and parse them out from strings to ints, doubles, or whatever you like.
MyApp ryan rampersad 18 1992
, the arguments would in a String, [“ryan”, “rampersad”, “18”, “1992”]. To get them out, you might try, Integer.parseInt.Hi,
Please let me know what will be the default value of String args[] in main method.
Consider am not giving any argument for Main while running simply running as java
Since the main method should have a argument, what will be passed to it if user didnt specifically type any command line arguments.
Please help me to understand this.
I would test it myself, but I have no reason to believe the String args[] would be anything other than an empty array if the user supplied no arguments.
Thanks Ryan, you helped me a lot!