In the previous lesson, we compiled a small program and in return got the MySolution.class file, which contains our program as bytecode. The source code was this:


class MySolution {
   public static void main(String[] args) {
      System.out.println("Hi, command line!");
   }
}

Now let's pass this .class file to the JVM to execute it. To do this, we'll use the java command, specifying the name of the class that contains the main method:


D:\temp>java MySolution

We see "Hi, command line!" on the console.

Note that here you need to specify not the file name (MySolution.class), but the class name (MySolution).

Let's try running another program from the console. This time we'll use the args array, the main method's input parameter:


public class MyArgs {
    public static void main(String[] args) {
        if (args.length == 3) {
            System.out.println(args[0].toLowerCase());
            System.out.println(args[1].toUpperCase());
            System.out.println(args[2].length());
        } else {
            System.out.println("Three parameters are expected.");
        }
    }
}

Let's compile...


D:\temp>javac MyArgs.java

And run:


D:\temp>java MyArgs

Here's the output: Three parameters are expected.

In the most recent command, after the class name, you can specify arguments that will end up in the args string array. For example, if you pass the following arguments:


D:\temp>java MyArgs One Two Three

Then the args array will be ["One", "Two", "Three"]

And the screen output will be:

one
TWO
5

If you want an argument to contain spaces, then you need to wrap it in double quotes:


D:\temp>java MyArgs "One Two" Three "Four Five Six"

Output:

one two
THREE
13

If your program consists of a single file, there is a simple way for you to run it without explicitly compiling it. Just tell the java utility the name of your file (including the .java extension) and any arguments:


D:\temp>java MyArgs.java param1 param2

This feature was added in Java 11 to make life easier for folks who are just starting to learn the programming language.

For more detailed information:
The java command has built-in help. To display it, run the following on the command line:
  • java --help