Program to print command line arguments in java

Taking Command Line Arguments in Java

The command line argument is the argument which is passed at the time of running a Java application. Java can take any number of arguments from the command-line, You could see that there will be String args[] used in the declaration of the main() method, which tells us that Java can takes all the argument which is passed in the command-line as String, but the question here is that how to pass the command-line argument to Java.

Usually we will be running a Java program like below

Command line argument will be passed as an additional parameter while running

If we wish to pass a String array then we need to include the array as a simple string beside the class name, you can optionally add quotes as well but it is not required as Java takes all inputs as String only. Each parameter has to separated with a space. Both below inputs which is given below is valid

java Test one two tree java Test "one" "two" "three"

The String arguments passed will be stored in the String args[] of the main() method, now args[] has three elements. These elements can be accessed in the normal way accessing a Java array.

Printing the command-line arguments

public class StringArrayExample < public static void main(String args[]) < for (int i =0;i> >

Upon execution we will be getting the below output

Parameter 1 : one Parameter 2 : two Parameter 3 : tree

Note : The program displays each parameter in separate line. This is because the space character separates arguments. In order to have all of them to be considered as a single argument then we need to enclose them with a quotation like below

java StringArrayExample "one two three"
Parameter 1 : one two three

Parsing Numeric Command-Line Arguments

Java program takes all the command line arguments as String by default but this will not help in all the cases. Suppose if your Java application needs to support numeric argument, then we need to parse the argument into integer.

public class Integer_Parse < public static void main(String args[]) < int value1,value2; if (args.length >0) < try < value1 = Integer.parseInt(args[0]); value2 = Integer.parseInt(args[1]); System.out.println("Sum of parameters is : "+(value1+value2)); >catch (NumberFormatException e) < System.err.println("Argument passed is not integer"); System.exit(1); >> > >
java Integer_Parse 12 13 Sum of parameters is : 25

parseInt() method will throw NumberFormatException when the argument passed is not a valid Number type (float,int,double…)

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?
Читайте также:  Php mysql timestamp to unix timestamp

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Overview

In this tutorial, we will write a simple Java program to print the command line argument passed to the Java program.

In Java, we have a special kind of array called args that holds the command line arguments passed to the Java program. args[0] holds the first command-line argument. args[1] holds the second command-line argument and so on.

Simple Java Program

An array stores a series of values. The values can be numbers, strings, objects, or just any other kind of Java data type. In Java, the first element of the array is at position 0, the second at position 1, and so on. This is illustrated in the below diagram.

Command Line Arguments in Java

To understand this better, Let’s see with the help of a simple example program called Greeting. You can pass the person’s name as a command line argument to the java program.

Program Output

Run the program by passing the name as an argument to the program.

The first argument is stored in args[0]. The program picks it up and displays the output as shown below.

Command line args

Exercise

As an exercise, you can improvise the above code snippet

Task1: To avoid the common exception, handle the exception using a try-catch block. ArrayIndexOutOfBoundsException while dealing with the command line.

Task2: This program only prints one command line argument. Using a loop, enhance the program to greet all the names provided in the command line.

For more information on Java, visit the official website :

Источник

Command Line Arguments in Java

Command Line Arguments in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument. The arguments have to be passed as space-separated values. We can pass strings and primitive data types as command-line arguments. The arguments will be converted to strings and passed into the main method string array argument.

Command Line Arguments in Java

package com.journaldev.examples; public class CommandLineArguments < public static void main(String[] args) < System.out.println("Number of Command Line Argument = "+args.length); for(int i = 0; i< args.length; i++) < System.out.println(String.format("Command Line Argument %d is %s", i, args[i])); >> > 
$ java com/journaldev/examples/CommandLineArguments.java Number of Command Line Argument = 0 

Now, let’s pass some arguments to the main class. We have to pass the arguments as space-separated values.

$ java com/journaldev/examples/CommandLineArguments.java "A" "B" "C" Number of Command Line Argument = 3 Command Line Argument 0 is A Command Line Argument 1 is B Command Line Argument 2 is C $ java com/journaldev/examples/CommandLineArguments.java 1 2 3 Number of Command Line Argument = 3 Command Line Argument 0 is 1 Command Line Argument 1 is 2 Command Line Argument 2 is 3 $ 

Note: If you are using Java 11 or higher, you don’t need to compile the java source file explicitly. The java command will compile and run the class simultaneously.

Читайте также:  Php not loading mysql

How to Pass Command Line Arguments in Eclipse

Step 1: Open the Class Run Configurations Settings

Eclipse Run Configurations

From the class editor, right click and chose “Run As” -> “Run Configurations…”.

Step 2: Specify the Program Arguments in the Arguments Tab

Eclipse Command Line Arguments

In the pop up window, click on the Arguments tab. Then provide the command line arguments value in the “Program Arguments” text box.

Step 3: Click on the Run button

Eclipse Command Line Arguments Example

When you will click on the Run button, the run configurations will be saved and the program will execute with the specified command-line arguments. If you run the class again, the saved run configuration will be used. So if you want to override the command-line arguments or remove them, you will have to open the run configurations window and make necessary changes.

Conclusion

The command-line arguments are used to provide values that are essential to run the program. For example, we can specify the database credentials to be used by the program. We can specify the configuration file location from where the program should pick the required values. Reference: Command-Line Arguments Oracle Docs

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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.

Читайте также:  How to get json data in php

Источник

Command-Line Arguments in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

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.

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.

Источник

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