Wednesday, 16 July 2014

Java Command-Line Arguments Simple Example.

Command-Line Arguments:

  • Many times we use command prompt (i.e. "cmd" in Windows) to compile and run our java program.
  • If we want to get any input from user at runtime / specifying configuration details when the application is launched we use "Command-Line Arguments".
  • Now,let's see an Example for that,


   —————————————————ArgsEx1.java—————————————————

public class ArgsEx1{                                          ——Line 1——
    public static void main (String[] args) {                  ——Line 2——               
        for(String input:args){                                ——Line 3——

                System.out.println(input);                     ——Line 4——

            }
      }
 }



Output:


ArgsEx1Output


Explanation:

  • In this example Simple Java Pro are called command-line arguments as shown in image.
  • When you run the program with values as input (Here: Simple Java Pro),It will print word line by line.Because the space character separates command-line arguments.
  • You can use any number of command-line arguments.
  • The Line 3 will first store value:"Simple" in variable "input" and prints it,then "Java" and prints it,then "Pro" and prints it.

Note:

  • If you want to use a string contains space in command line arguments then use double quotes for that,
          Example:  "Simple Java Pro"

          —It will tell JRE to see whole String as a single command,try this.

Download ArgsEx1.java
Download ArgsEx1.java

No comments:

Post a Comment