Exploring Command Line Arguments in Java

Updated on July 31, 2024

Article Outline

A Java command-line parameter is a value supplied to the Java application when it is executed. In Java, command line arguments sent via the console can be accepted and utilised as input.

 

Users can pass parameters during execution, bypassing command-line arguments within the main() function. They provide flexibility and enable programs to handle different inputs without changing the source code.

 

In this article, we will learn about the practical use of command-line arguments in Java.

What are Command Line Arguments?

Command line arguments are inputs provided to a program when It is executed. These inputs can customise the program’s execution by specifying different options, configurations, or data. In Java, command line arguments are passed to the ‘main’ method as an array of ‘String’ Objects.

 

Program

class Main{ public static void main(String args[]){ System.out.println("Hello, I am Java ") ; } }

Output

Hello, I am Java

Also Read: Java Tutorial

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

How to Pass Command Line Arguments in Java 

To pass command line arguments to a Java program. If you are a Windows user, specify them after the class name in the command line or terminal window.

 

Example:

java CommandLineExample arg1 arg2 arg3

Here, ‘arg1’, ‘arg2’ and ‘arg3’ are command line arguments that will be passed to the ‘main’ method.

Accessing Command Line Arguments

In Java, we can access the command line arguments using the main method using the ‘args’ array. The ‘args’ array contains the arguments as strings; you can access each argument by index.

 

The following program demonstrates “how to read the command  line arguments in Java”

 

Program

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

Output

Argument 0: Harry Argument 1: Potter Argument 2: Voldemort Argument 3: Computer Argument 4: System Argument 5: RajKumar

Using Command Line Arguments in Programs

 

Here, we will see some programs in command line arguments in Java programs.

 

Example: Sum of Integers

 

The following program calculates the sum of integers passed as command-line arguments.

 

Program

public class SumIntegers { public static void main(String[] args) { int sum = 0; for (String arg : args) { try { sum += Integer.parseInt(arg); } catch (NumberFormatException e) { System.out.println(arg + " is not an integer."); } } System.out.println("Sum: " + sum); } }

Output

java SumIntegers 30 40 50 60 70 80 90 100 Sum: 520

 

Example: File Reader

Here, we describe the command-line arguments used to specify a file name to be read by the program.   import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReaderExample { public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java FileReaderExample <filename>"); return; } String filename = args[0]; try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }

 

Output

java FileReaderExample work.txt Harry Potter Computer Working Water Bottle Ninja Hattori Singhaniya Raj Kumar Rao Singhaniya

Best Practices for Using Command Line Arguments

Let’s examine the best practice for using command-line arguments in Java.

 

  • Validate Input: Always validate the command line arguments to ensure they meet the expected format and constraints.

 

  • Provide Help: Provide a way for users to get help or usage information, typically through the’ a –help’ or ‘-h’ argument.

 

  • Handling Error Gracefully:  Provide meaningful error messages and handle exceptions gracefully to improve user experience.

 

  • Document Arguments: Document the expected arguments and their usage in the program’s documentation.

 

Conclusion

Command line arguments provide a powerful way to pass information into a Java program from the outside, enabling flexible and dynamic execution. By understanding how to handle these arguments, developers can create a versatile application that responds to user input without requiring code changes. Key points include the structure of the ‘main’ method, parsing and using arguments, handling various data types, and managing errors. Mastery of command-line arguments enhances the robustness and user-friendliness of Java applications.

FAQs
Command line arguments are inputs passed to a Java program during execution. They allow users to influence the program's behaviour without changing its source code.
Command line arguments are accessed through the ‘main’ method’s parameter, an array of ‘String called ‘args’, for example, ‘public static void main(String args[]).
Yes, command-line arguments can contain spaces if they are enclosed in quotes. For example, the “java Program_Name” “argument with spaces” treats the entire quoted string as a single argument.
Yes, most IDEs, such as Eclipse or IntelliJ IDEA, allow you to specify command-line arguments in the run configuration settings for your Java program.
Arguments are the values passed in when the method is invoked. When you invoke a method, the arguments match the declaration’s parameters in type and order.

Updated on July 31, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved