Command line arguments and Variable length arguments
✅ 1. Command-Line Arguments in Java
Command-line arguments allow you to pass information to a Java program when it starts from the terminal or command prompt.
🔹 Syntax:
-
args
is an array ofString
that holds the arguments. -
Arguments are space-separated words passed when running the program.
🔸 Example: Program to Print Command-Line Arguments
✅ How to Run:
Output:
✅ 2. Variable-Length Arguments (Varargs) in Java
Java allows you to define methods that accept variable numbers of arguments using ...
.
🔹 Syntax:
-
Treated as an array inside the method.
-
Only one vararg is allowed per method, and it must be last in the parameter list.
🔸 Example: Method to Add Numbers
✅ Differences Between Command-Line Arguments and Varargs
Feature | Command-Line Arguments | Varargs |
---|---|---|
Where used | In main(String[] args) | In any user-defined method |
Source of data | From user via terminal/command | From method call inside program |
Type | Always String[] | Any type (e.g., int... , String... ) |
Example Input | java Program 1 2 3 | method(1, 2, 3) |
Comments
Post a Comment