From the course: Java 11+ Essential Training

Pass arguments to a console application - Java Tutorial

From the course: Java 11+ Essential Training

Start my 1-month free trial

Pass arguments to a console application

- [Instructor] When you run a Java command-line application, you can pass in values. You have to declare those values within a function or a method as I've done here. In fact, the main method, which is executed automatically when you start up a command-line application, must have one and only one parameter, and it must be an array of Strings. In IntelliJ IDEA, the automatic name is args, but the name can really be anything you want. Now, I'm not receiving anything yet, but I might. So I'm going to add a little bit of code here. I'll change this code to look like this. I'll add a comma space at the end of this String that's still inside the quotes. Then I'll use the plus operator to concatenate Strings, that is, I'm appending another value. And I'll append the expression args zero, and that means the first value in the args array. And then I'll append another String, and I'll put the exclamation mark there. Next, I'll go to Terminal, and I'm going to recompile the code with javac and then the full name of the file. Then I'll try to run the code with java com.company.Main, and I get an exception. And that's because I'm referencing an item in an array that's empty. The exception is called an ArrayIndexOutOfBoundsException, and that's an example of a really long exception class name that Java really likes, but the important thing here is that the index zero is out of bounds for the array. So to fix that, I'll simply run the code again, but this time, I'll add an argument, my name. And this time, I get the expected output, "Hello from Java, David!" Now you can do the same thing using IntelliJ IDEA's build and run tools. As I mentioned previously, when you choose Build and then Build Project, you're creating files in this out directory over here. And if I try to run this code right now, I'll once again get the ArrayIndexOutOfBoundsException. To fix that, I'll go to the menu and choose Run, Edit Configurations. I only have one run configuration here. It's called Main, and it references this Main class. In our program arguments, I'll enter an argument of Mary. I'll click OK, and then I'll try to run the code again, and this time I get "Hello from Java, Mary!" So again, this is how you can process and test values passed into command-line applications. You'll sometimes hear the terms parameter and argument used interchangeably, but they do have different meanings. When you declare values, they are being passed into a method. Those are parameters. When you actually pass the values in from the command line or from IntelliJ IDEA's user interface, those are the arguments. So arguments get passed to parameters, and in Java, you have all the tools you need to receive and process those values.

Contents