The signature of main method is:
public static void main(String[] args) { which means that it takes a string array as the input argument. How can those be passed while running as a standalone class with in the Eclipse IDE? How can we use those input parameters with in a program? These are the some of the questions discussed here.
To execute a class having the main method with arguments follow the steps below.
- Click from menu bar.
- “ Run ” - > “ Run ” and now select “ Arguments tab ”. Text area against “ Program Arguments ” is available to enter arguments. You can add any number of arguments but each parameter should be separated by a space. Space is the delimiter here.
[IMG]http://www.eclipse-blog.org/wp-content/uploads/2007/05/arguments-********PNG[/IMG]
For instance, if we give following text in the “ Program Arguments ” window,
hello world, hi hallo
then we will have 4 arguments namely.
- arg 1: hello.
- arg 2: world.
- arg 3: hi.
- arg 4: hallo.
Many people think that comma (,) or semi colon (
is delimiter but it just a misconception. Delimiter is “ space ”.
Consider the following program arguments:
In the main method, we will print the size of the input array and also will print each argument.
كود:
public class MainClass {
public static void main(String[] args) {
System.out.println("No. of argumetns are: " + args.length);
for(int i= 0;i < args.length;i++)
System.out.println("Argument " + i + " is : " + args[i]);
}
}
Output:
No. of argumetns are: 4
Argument 0 is : hello
Argument 1 is : world,
Argument 2 is : football
Argument 3 is : match We can cast and use the input parameters incase you want something other than String as shown below.
كود:
public class MainClass {
public static void main(String[] args) {
double dd = new Double(args[0]).doubleValue();
}
}
مواقع النشر (المفضلة)