Introduction
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
Code snip
The code snippet shows the switch method working through command line arguments.
Example: we write on CLA 5 so case number 5 will activate and output: Friday.
StringCLA.java displays each of its command line arguments on a line by itself.
Switch.java
public class Switch
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
switch(x){
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
case 7: System.out.println("Sunday");
break;
default :System.out.println("Invalid Number of Day");
}
}
}
Compiling Switch.java
StringCLA.java
class StringCLA {
public static void main(String[] str) {
int length = str.length;
if (length <= 0) {
System.out.println("Enter Some String");
}
for (int i = 0; i < length; i++) {
System.out.println(str[i]);
}
}
}
Compiling StringCLA.java
Note
The application displays each word — Its, Work, and !!! — on a line by itself. This is because the space character separates command-line arguments.
To have Its, Work, and !!! interpreted as a single argument, the user would join them by enclosing them within quotation marks.
java StringCLA "Its Work !!!"
Its Work !!!
Working with eclipse
Passing arguments in Eclipse IDE is done using a tool called Run configurations, present in
the RUN menu. Go to RUN -> Run Configerations. Now in Run Configerations go to (x)= Arguments. Give
argument value in Program arguments.
E.g.: 5.
Click on Run.
For more tips, visit Javablog.