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.
Possibly related posts:
this is very informative. i have always wondered about that. thank you very much.