- 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
Explain Java command line arguments.
You can pass n number of arguments from the command line while executing the program, separating them with spaces.
java ClassName 10 20 30 . . . . .
The main method accepts/reads the values you have passed into an array of the type String.
public class public static void main(String[] args){ }
These arguments are known as command line arguments.
Using command line arguments
After writing a Java program we will compile it using the command javac and run it using the command javas. Consider the following code −
Example
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); } }
We would compile and run it from command line as shown below −
Output
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 user using classes from I/O package or Scanner.
Another way is to use command line arguments.
Example
In the following example we are rewriting the above program, by accepting the (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 command line arguments
- Command line arguments in Java
- Command Line arguments in Java programming\n
- Command Line Arguments in Python
- Command Line arguments in C#
- Command Line arguments in Lua
- Command line arguments in C/C++
- Command line arguments example in C
- Command Line and Variable Arguments in Python?
- How to Parse Command Line Arguments in C++?
- How to add command line arguments in Python?
- Parse Command Line Arguments in Bash on Linux
- getopt() function in C to parse command line arguments
- How do we access command line arguments in Python?
- How command line arguments are passed in main method in C#?
