- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you pass a command line argument in Java program?
After writing a Java program you need to compile it using the command javac and run it using the command java. Consider the following code −
public class Sample{ public static void main(String[] args){ int a = 20; int b = 30; int c = a+b; System.out.println("Sum of the two numbers is "+c); } }
You can compile and run it from the command line as shown below −
Here, we are hard coding (fixing to a specific value) the values of a and b which is not recommendable. To handle this, you can accept parameters from the user using classes from I/O package or Scanner.
Another way is to use command line arguments.
Command line arguments
The main method accepts an array of values of the type String Java from the user.
public class{ public static void main(String[] args){ } }
You can pass them at the time of execution right after the class name separated with spaces as −
java ClassName 10 20 30
Example
In the following Java program, we are accepting two integer values from the command line. And, we are extracting these two from the String array in the main method and converting them to integer −
public class Sample{ public static void main(String[] args){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a+b; System.out.println("Sum of the two numbers is "+c); } }
Output
You can compile and, run the program by passing the values at execution line through command prompt as shown below −
- Related Articles
- Java Program to pass lambda expression as a method argument
- What is a command line argument in C language?
- Java Program to Pass ArrayList as the function argument
- How to Pass Command Line Arguments to Bash Script
- How to pass command line arguments to a python Docker container?
- Pass the Output of a Command as an Argument for Another on Linux
- Can we pass objects as an argument in Java?
- How to pass a dictionary as argument in Python function?
- How do we access command line arguments in Python?
- Command line arguments in Java
- How to pass Python function as a function argument?
- Swift Program to Pass Dictionary as the function argument
- How to do Python math at command line?
- Java command line arguments
- How to pass argument to an Exception in Python?
