Tuesday 4 April 2017

String[ ] args parameter in java main()

In java when one supply parameter(s) from command line then this String[] args comes into play.

It holds the parameters passed from command line as an array of String objects.

Lets consider this example:

File: Example.java

class Example{
       public static void main(String[] args){
           for(int i=0; i<args.length; i++){
               System.out.println(args[i])
           }
       }
}

Compile this program: javac Example.java
Run this program by passing command line argument: java Example 12  13  14

Then args will contain array of String as ["12","13","14"]

And when you loop through the args, the output will be:
12
13
14

Getting printed on new line because of ln in println where ln indicates new line.


Note:

  • args is not necessarily bound to be named so. What I mean to say is you can give it any name(eg, a or abc or xyz).
  • It could also be written as String... args


Read more:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.