Aishu Aishu - 5 months ago 16
Java Question

Java - Passing arguments to the Main method

I'm just a beginner to write programs in Java. How to pass the arguments

(Array of strings)
to the main method? I'm using Eclipse as an IDE

public static void main(String[] args) {
// TODO Auto-generated method stub
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");

// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);

System.out.println("!");
}

Answer

Run > Run Configurations > Java Application > Arguments > Program arguments

Arguments Result


Also, make sure your code works when no arguments are passed, don't just directly pick values from array.

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if (args != null && args.length > 0) {
            if (args[0].equals("-h"))
                System.out.print("Hello,");
            else if (args[0].equals("-g"))
                System.out.print("Goodbye,");

            // print the other command-line arguments
            for (int i = 1; i < args.length; i++)
                System.out.print(" " + args[i]);

        } else{
            System.out.print("No Arguments passed");
        }
        System.out.println("!");
    }
Comments