Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Working with command line arguments in Java

3.50/5 (2 votes)
11 Jul 2012CPOL1 min read 98.8K   192  
A Java application that can accept any number of arguments directly from the command line.

CMD

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

Java
/**
 * Switch.java 
 * Integer passing in command-line arguments.
 */
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

CMD

StringCLA.java

Java
/**
 * StringCLA.java 
 * String passing in command-line arguments.
 */
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

CMD

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 !!!

CMD

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.

Eclipse IDE

Click on Run.

Eclipse IDE

For more tips, visit Javablog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)