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:


public static void main(String[] args)
  • args is an array of String that holds the arguments.

  • Arguments are space-separated words passed when running the program.


🔸 Example: Program to Print Command-Line Arguments


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

✅ How to Run:


javac CommandLineExample.java java CommandLineExample Hello World 123

Output:


You passed 3 arguments. Argument 0: Hello Argument 1: World Argument 2: 123

✅ 2. Variable-Length Arguments (Varargs) in Java

Java allows you to define methods that accept variable numbers of arguments using ....

🔹 Syntax:


methodName(datatype... varname)
  • 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


public class VarargsExample { static int add(int... numbers) { int sum = 0; for (int num : numbers) { sum += num; } return sum; } public static void main(String[] args) { System.out.println(add(10, 20)); // 30 System.out.println(add(5, 15, 25, 35)); // 80 System.out.println(add()); // 0 } }

✅ Differences Between Command-Line Arguments and Varargs

FeatureCommand-Line ArgumentsVarargs
Where usedIn main(String[] args)In any user-defined method
Source of dataFrom user via terminal/commandFrom method call inside program
TypeAlways String[]Any type (e.g., int..., String...)
Example Inputjava Program 1 2 3method(1, 2, 3)

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java