Card 02/ 06

ExampleDifficulty: Beginner1 min

javac and java: Compiling and Running a Class

One command writes a file and says nothing; the other reads it and takes a class name, not a filename.

javac compiles a .java file into a .class file of bytecode (the compact instruction set the Java Virtual Machine runs), and java runs a compiled class, given its class name. A folder with one file in it, and the two commands that take it from text to output:

bash
ls
Hello.java

javac Hello.java

ls
Hello.class  Hello.java
javac said nothing, and left a second file behind

javac is the first translation. It read the text, checked it, and wrote Hello.class, the bytecode. Silence means it worked: a compiler that has nothing to complain about says nothing.

bash
java Hello
Hello

java is the second translation. Notice what it was given: Hello, with no extension and no .class on the end. It takes the name of a class, not the name of a file, and then goes looking for the bytecode that carries it.

Asking for java Hello.class fails for the same reason. The launcher treats the whole of Hello.class as a class name, finds no class by that name, and reports Could not find or load main class Hello.class.

That is the pair you will type for the rest of your life, under one build tool or another: one command that produces bytecode and one that runs it.