Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
Now Reading
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Java command line arguments serve as a powerful tool for enhancing the functionality and versatility of your Java applications. By allowing users to pass inputs through the command line, developers can create more interactive and adaptable programs. In this comprehensive guide, we will explore the practical usage of command line arguments in Java, covering everything from passing arguments to retrieving and parsing them. Whether you are a beginner or an experienced Java developer, this guide will equip you with the knowledge to effectively utilize command line arguments in your projects.
To pass command line arguments in Java, you need to follow a specific syntax. The general one is as follows:
The program name should be the name of your compiled Java class file without the ".class" extension. The arguments can be any number of strings separated by spaces.
Let's explore a few examples of passing arguments in Java
Suppose we want to create a program that accepts two numbers as command line arguments and calculates their sum. Here's how you can pass the arguments:
In this example, the program expects two command line arguments to be provided as numbers.
It checks if exactly two arguments are passed; otherwise, it displays an error message. Then, it parses the arguments into integers using Integer.parseInt() and calculates their sum.
Finally, it displays the result on the console.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
ii). This will output:
You can replace 10 and 20 with any two numbers of your choice to perform the addition.
If you want to write a program that accepts two strings as command line arguments in Java, you can pass them like this:
In this example, the program expects two command line arguments to be provided as strings.
It checks if exactly two arguments are passed; otherwise, it displays an error message.
Then, it retrieves the arguments from the args array and displays them on the console.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments
iii). The output will be:
Argument 1: Hello, World!
Argument 2: Java is awesome
You can replace "Hello, World!" and "Java is awesome" with any two strings of your choice to see them being displayed by the program.
You can use the args parameter in the main method to retrieve command line arguments in a Java program. It is an array of strings that stores the command line arguments passed during program execution. Here's an example of how to retrieve command line arguments in a Java program using the args parameter in the main method:
In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given.
Otherwise, it iterates through the args array using a loop and displays each argument along with its corresponding index.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
Replace arg1, arg2, and arg3 with any values or strings of your choice. The program will display the provided command line arguments with their corresponding indices.
For example, if you run the program with the command line arguments Hello, Java, and World, it will output:
You can modify the program as needed to perform specific operations or validations on the retrieved command line arguments.
Once you have retrieved the command line arguments, you may need to parse them into appropriate data types for further processing. Java provides various methods for parsing strings into integers, floats, or other data types based on your requirements.
In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given.
Otherwise, it iterates through the args array using a loop and attempts to parse each argument into an integer using Integer.parseInt(). If the parsing is successful, it displays the parsed integer.
If an argument cannot be parsed as an integer, it displays a message indicating that it is not valid.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
The program will attempt to parse each argument into an integer. If an argument is a valid integer, it will display the parsed integer. If an argument cannot be parsed, it will display a message indicating that it is not a valid integer.
For example, if you run the program with the command line arguments 10, 20, abc, and 30, it will output:
To access individual command line arguments, you can use array indexing with the args parameter. For example, args[0] will give you the first command line argument, args[1] will give you the second one, and so on.
Here's an example that demonstrates accessing individual command line arguments in a Java program using array indexing:
In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given.
Otherwise, it iterates through the args array using a loop and attempts to parse each argument into an integer using Integer.parseInt(). If the parsing is successful, it displays the parsed integer.
If an argument cannot be parsed as an integer, it displays a message indicating that it is not valid.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
The program will attempt to parse each argument into an integer. If an argument is a valid integer, it will display the parsed integer. If an argument cannot be parsed, it will display a message indicating that it is not a valid integer.
For example, if you run the program with the command line arguments 10, 20, abc, and 30, it will output:
To access individual command line arguments, you can use array indexing with the args parameter. For example, args[0] will give you the first command line argument, args[1] will give you the second one, and so on.
Here's an example that demonstrates accessing individual command line arguments in a Java program using array indexing:
In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given. Otherwise, it accesses individual arguments using array indexing and displays them on the console.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
Replace arg1, arg2, and arg3 with the values or strings of your choice. The program will access and display the provided command line arguments individually.
For example, if you run the program with the command line arguments Hello, Java, and World, it will output:
You can access additional arguments by using additional indices, such as args[2], args[3], and so on.
When working with command line arguments in Java, it is essential to follow some best practices. These include validating user input, providing meaningful error messages for invalid arguments, and handling exceptions gracefully. Additionally, it's important to sanitize and secure any sensitive information passed as command line arguments.
1. Simple Calculator Application
Let's create a simple calculator application that accepts command line arguments for two numbers and performs basic arithmetic operations based on the user's choice.
In this example, the program expects three command line arguments: two numbers and an operator (+, -, *, or /). It checks if exactly three arguments are provided; otherwise, it displays an error message. Then, it retrieves the two numbers as double values and the operator as a char value.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line arguments:
Replace 10, 5, and + with the numbers and operators of your choice. The program will perform the arithmetic operation and display the result.
For example, if you run the program with the command line arguments 10, 5, and +, it will output:
Result: 15.0
In Java, you can pass multiple command line arguments to your program when executing it. They are passed as strings and can be accessed through the args parameter in the main method.
Here's an example of how you can handle multiple command line arguments in Java:
To run it:
Output:
To pass command line arguments in Java using Eclipse, you can follow these steps:
By providing the command line arguments in the "Program arguments" section, Eclipse will pass them to the program when it runs.
In this example, the program expects one command line argument, which is the name of the file to be read.
It checks if a file name is provided; otherwise, it displays an error message. Then, it reads the content of the file using a BufferedReader and displays each line on the console.
If an error occurs during file reading, it displays an error message.
i). Compile the Java file using the Java compiler:
ii). Run the compiled class file with the command line argument specifying the file name:
Replace input.txt with the actual file name you want to read. The program will read the content of the specified file and display it on the console.
For example, if you have a file named input.txt with the following content:
Running the program with the command line argument input.txt will output:
Command line arguments in Java offer a flexible and efficient way to customize program behavior and provide inputs during program execution. By understanding how to pass, retrieve, and parse command line arguments, you can create more interactive and adaptable Java applications. Remember to follow best practices, handle invalid arguments gracefully, and prioritize security when dealing with sensitive information. Start incorporating command line arguments in your Java projects, and harness their full potential for enhancing user experience and program functionality.
1. How can I pass command line arguments in Java?
Command line arguments can be passed when running a Java program from the command line. You can pass the arguments after the program name, separated by spaces.
2. How do I retrieve command line arguments in a Java program?
To retrieve command line arguments in a Java program, you can use the args parameter in the main method. You can access and process these arguments using array indexing.
3. How can I handle invalid command line arguments in Java?
To handle invalid command line arguments in Java, validate the input by checking the number of arguments and their values. Implement proper error handling to provide meaningful feedback to the user and ensure the program's stability. Remember to handle exceptions during argument validation.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...