Command line argument programs in java

Command-Line Arguments

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:

When an application is launched, the runtime system passes the command-line arguments to the application’s main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : «friends.txt» .

Echoing Command-Line Arguments

The Echo example displays each of its command-line arguments on a line by itself:

The following example shows how a user might run Echo . User input is in italics.

java Echo Drink Hot Java Drink Hot Java

Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

java Echo "Drink Hot Java" Drink Hot Java

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as «34», to a numeric value. Here is a code snippet that converts a command-line argument to an int :

int firstArg; if (args.length > 0) < try < firstArg = Integer.parseInt(args[0]); >catch (NumberFormatException e) < System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); >>

parseInt throws a NumberFormatException if the format of args[0] isn’t valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.

Источник

Command-Line Arguments in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

Читайте также:  Calling interface method in java

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

It’s quite common to run applications from the command-line using arguments. Especially on the server-side. Usually, we don’t want the application to do the same thing on every run: we want to configure its behavior some way.

In this short tutorial, we’ll explore how can we handle command-line arguments in Java.

Читайте также:  Php генерация csv файла

2. Accessing Command-Line Arguments in Java

Since the main method is the entry point of a Java application, the JVM passes the command-line arguments through its arguments.

The traditional way is to use a String array:

public static void main(String[] args) < // handle arguments >

However, Java 5 introduced varargs, which are arrays in sheep’s clothing. Therefore, we can define our main with a String vararg:

public static void main(String. args) < // handle arguments >

They’re identical, therefore choosing between them is entirely up to personal taste and preference.

The method parameter of the main method contains the command-line arguments in the same order we passed at execution. If we want to access how much arguments did we get, we only have to check the length of the array.

For example, we can print the number of arguments and their value on the standard output:

public static void main(String[] args) < System.out.println("Argument count: " + args.length); for (int i = 0; i < args.length; i++) < System.out.println("Argument " + i + ": " + args[i]); >>

Note that in some languages, the first argument will be the name of the application. On the other hand, in Java, this array contains only the arguments.

3. How to Pass Command-Line Arguments

Now that we have an application that handles command-line arguments, we’re eager to try it. Let’s see what options we have.

3.1. Command Line

The most obvious way is the command-line. Let’s assume we already compiled the class com.baeldung.commandlinearguments.CliExample with our main method in it.

Then we can run it with the following command:

java com.baeldung.commandlinearguments.CliExample

It produces the following output:

Now, we can pass arguments after the class name:

java com.baeldung.commandlinearguments.CliExample Hello World!
Argument count: 2 Argument 0: Hello Argument 1: World!

Usually, we publish our application as a jar file, not as a bunch of .class files. Let’s say, we packaged it in the cli-example.jar, and we set com.baeldung.commandlinearguments.CliExample as the main class.

Now we can run it without arguments the following way:

java -jar cli-example.jar Hello World! Argument count: 2 Argument 0: Hello Argument 1: World!

Note, that Java will treat every argument we pass after the class name or the jar file name as the arguments of our application. Therefore, everything we pass before that are arguments for the JVM itself.

3.2. Eclipse

While we’re working on our application, we’ll want to check if it works the way we want.

In Eclipse, we can run applications with the help of run configurations. For example, a run configuration defines which JVM to use, what is the entry point, the classpath, and so on. And of course, we can specify command-line arguments.

The easiest way to create an appropriate run configuration is to right-click on our main method, then choose Run As > Java Application from the context menu:

eclipse run

With this, we instantly run our application with settings that honor our project settings.

Читайте также:  Как перезапустить браузер java

To provide arguments, we should then edit that run configuration. We can do it through the Run > Run Configurations… menu option. Here, we should click the Arguments tab and fill the Program arguments textbox:

eclipse configure

Hitting Run will run the application and pass the arguments we just entered.

3.3. IntelliJ

IntelliJ uses a similar process to run applications. It calls these options simply as configurations.

First, we need to right-click on the main method, then choose Run ‘CliExample.main()’:

intellij run

This will run our program, but it will also add it to the Run list for further configuration.

So, then to configure arguments, we should choose Run > Edit Configurations… and edit the Program arguments textbox:

intellij configure

After that, we should hit OK and rerun our application, for example with the run button in the toolbar.

3.4. NetBeans

NetBeans also falls into line with its running and configuration processes.

We should run our application first by right-clicking on the main method and choosing Run File:

netbeans run

Like before, this creates a run configuration and runs the program.

Next, we have to configure the arguments in that run configuration. We can do that by choosing Run > Set Project Configuration > Customize… Then we should Run on the left and fill the Arguments text field:

netbeans configure

After that, we should hit OK and start the application.

4. Third-Party Libraries

Manual handling of the command-line arguments is straightforward in simple scenarios. However, as our requirements become more and more complex, so does our code. Therefore, if we want to create an application with multiple command-line options, it would be easier to use a third-party library.

Fortunately, there’re a plethora of those libraries which support most use cases. Two popular examples are Picocli and Spring Shell.

5. Conclusion

It’s always a good idea to make your application’s behavior configurable. In this article, we saw how to do that using command-line arguments. Additionally, we covered various ways to pass those arguments.

As usual, the examples are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью