Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java Command-Line Arguments: How to Pass and Parse Parameters

Java Command-Line Arguments

Discover how to pass and parse command‑line arguments in Java, with practical examples that cover string and numeric inputs.

Command‑line arguments let you supply data to a Java program at runtime. They are entered directly after the class name when launching the application from a terminal.


Example: Command‑Line Arguments

class Main {
    public static void main(String[] args) {
        System.out.println("Command‑Line arguments are:");
        for (String str : args) {
            System.out.println(str);
        }
    }
}

Compile and run the program from the command line:

javac Main.java
java Main apple ball cat

The output will be:

Command‑Line arguments are:
apple
ball
cat

In the main() method, String[] args holds every argument passed from the terminal. Arguments are always stored as strings and separated by whitespace.

Tip: Even if you intend to use numeric values, they arrive as strings. You can convert them later.


Passing Numeric Command-Line Arguments

Although main() only accepts String parameters, you can transform those strings into numeric types using parsing methods.

Example: Numeric Command-Line Arguments

class Main {
    public static void main(String[] args) {
        for (String str : args) {
            int value = Integer.parseInt(str);
            System.out.println("Argument as integer: " + value);
        }
    }
}

Compile and execute with numeric arguments:

javac Main.java
java Main 11 23

The output will be:

Argument as integer: 11
Argument as integer: 23

The key line is:

int value = Integer.parseInt(str);

Here Integer.parseInt() converts the string to an int. You can also use Double.parseDouble() or Float.parseFloat() for other numeric types.

Warning: If a string cannot be parsed, Java throws a NumberFormatException. Always validate input before parsing.

Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Java Comments: Types, Usage, and Best Practices
  3. Mastering Java if…else: Control Flow Explained
  4. Master Java Constructors: Types, Usage, and Practical Examples
  5. Java this Keyword Explained: Practical Uses, Constructors, and More
  6. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  7. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  8. Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
  9. Java Annotations Explained: Types, Placement, and Practical Examples
  10. Command‑Line Arguments in Java: A Practical Guide with Code Examples