Want to level up your Java skills?
Subscribe to Ram N Java for simple, beginner-friendly programming lessons and clear code breakdowns.
Subscribe NowWhat Are Command Line Arguments in Java?
A command-line argument is information passed directly to a Java program when you run it from the console or terminal. Instead of hardcoding values inside your code or prompting the user while the program is running, you provide the inputs immediately alongside the launch command.
How Do Command Line Arguments Work?
Whenever you execute a Java program, the Java Virtual Machine (JVM) gathers any words or values you typed after the class name, packages them into an array of strings, and delivers them directly to the args parameter of your main method:
Key points to remember about these arguments:
- Always Strings: Every argument received through
argsis stored as aString, even if you pass numeric digits like10or25. - Zero-Indexed: The first argument is accessed at
args[0], the second atargs[1], and so on. - Separated by Spaces: Arguments are separated by whitespace when typed in the console.
Complete Example: Printing Supplied Arguments
Here is a simple example showing how to inspect and display the arguments passed into your application:
public class CommandLineDemo {
public static void main(String[] args) {
System.out.println("Total arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument at index " + i + ": " + args[i]);
}
}
}
Compiling and Passing Arguments in Terminal
Compile the file and supply your custom arguments directly after the class name:
java CommandLineDemo Apple Banana Orange
Your terminal will print the following output:
Argument at index 0: Apple
Argument at index 1: Banana
Argument at index 2: Orange
Recommended Java Tutorials From Our Channel
Explore these related tutorials from our channel to deepen your Java fundamentals:
Click here to watch in Youtube :
https://www.youtube.com/watch?v=pN8th2DKRjI&list=UUhwKlOVR041tngjerWxVccw
CommandLineArgExample.java







No comments:
Post a Comment