How to run Java method with arguments from command line?

I am trying to run the following method in Loader.java from the command line:

public static void method(String path, String word)

As seen above, I must pass in the variables path and word, and I want the command line to display the System.out.println()‘s in the method.

What command can I run to do this?

Note: when I run the following commands,

javac *.java
jar -cvf Loader.jar Loader.class
java -cp ./Loader.jar Loader

I get the following error:

Caused by: java.lang.NoClassDefFoundError: path/to/Loader (wrong name: Loader)

What must I do to successfully run method from the command line?

Here is minimum reproducible version of Loader.java:

public class Loader {
     public static void main(String[] args) {
          method("my/path", "my_word");
     }
     public static void method(String path, String word) {
          System.out.println("Output after doing something");
     }
}

Answer

Just do the following:

javac Loader.java
java Loader

In fact, if you are you Java-11 or above, you don’t even need to use the first command i.e. you can directly use the following command:

java Loader.java

However, if you want to create a jar file and execute the class from it, execute the steps given below:

mkdir demo
cd demo

Now create/place Loader.java in this folder. Then,

javac *.java
jar -cvf loader.jar .
java -cp loader.jar Loader

Note that I’ve used a new directory, demo to make it clear but it is not necessary. Another thing you should notice is the . at the end of jar command which specifies the current directory.

How to process command-line arguments?

String[] args parameter in main stores all the parameters from the command-line e.g. if you run the following program as java Loader my/path my_word from the command-line,

public class Loader {
    public static void main(String[] args) {
        if (args.length >= 2) {
            method(args[0], args[1]);
        } else {
            System.out.println("Command line parameters are missing");
        }
    }

    public static void method(String path, String word) {
        System.out.println("Path: " + path);
        System.out.println("Word: " + word);
    }
}

the output will be

Path: my/path
Word: my_word

Leave a Reply

Your email address will not be published. Required fields are marked *