Command Line Arguments in Java

In Java programming language, we can pass arguments while running the program using the command line. These arguments can be used as input values in the program. To pass arguments, we need to type them as space-separated values after the program name in the command line. These arguments can be strings or primitive data types like int, double, float, and char.

When we run the program with command-line arguments, the Java Virtual Machine (JVM) wraps up these arguments into an array called "args[]" and passes it to the main() function. We can access and use these arguments in the program using the "args[]" array. We can check the number of arguments passed by using the "args.length" method.

To illustrate this, let's consider an example program where we print the first command-line argument:

Java Program:

class Example { public static void main(String[] args) { System.out.println(args[0]); } }

If we run this program with the command "java Example Hello World", it will print "Hello" because "Hello" is the first command-line argument.

Command Line Arguments in Java


We can also check for the number of command-line arguments using "args.length". In the following example, we print all the command-line arguments passed to the program:

Java Program:

class Example { public static void main(String[] args) { if(args.length > 0) { System.out.println("The command line arguments are:"); for(String val : args) System.out.println(val); } else { System.out.println("No command line arguments found."); } } }

In this program, we first check if any command-line arguments are passed using "args.length". If there are arguments, we print all the arguments using a for-each loop. If there are no arguments, we print "No command line arguments found."

To run this program, we need to save it with a ".java" extension and compile it using the "javac" command. After successful compilation, we can run the program with the command "java Example" followed by the command-line arguments. For example, "java Example Hello World" will print "Hello" and "World" as command-line arguments.

By understanding the concept of command-line arguments, we can make our Java programs more versatile and user-friendly.

Previous Post Next Post