Running Java
javac + java, single-file source launch, and the jshell REPL.
java Hello.class, and Java says it can't find your class. It's right there! What went wrong?The classic two steps
Step one: javac compiles a file. Step two: java runs a class, given by its name, with no extension.
$ javac Hello.java # makes Hello.class
$ java Hello # runs class HelloThe .class trap
java Hello.class fails with Could not find or load main class Hello.class. java treats the whole thing as a class name, and no class is literally called Hello.class. Drop the extension: java Hello.
$ java Hello.class # error
$ java Hello # worksOne-step source mode
Since Java 11, java Hello.java compiles the file in memory and runs it straight away. Since Java 22 this also works for programs spread over several source files.
$ java Hello.javaYour turn
You run java Hello.java in an empty folder containing only Hello.java. Afterwards, what new file is in the folder?
Hello.classNone: it was compiled in memoryA hidden build folder
Show the answer
None. Source-file mode keeps the compiled classes in memory only. Perfect for scripts and experiments; real projects still use javac or a build tool.
jshell: try it live
jshell (Java 9+) is a REPL: Read, Evaluate, Print, Loop. Type a snippet and see the result immediately, with no class or main needed.
jshell> 2 + 3
$1 ==> 5
jshell> "hi".toUpperCase()
$2 ==> "HI"In real projects
Real projects use build tools like Maven or Gradle, which call javac and package everything for you. Developers still reach for jshell to check how an API behaves, and for java File.java to run quick scripts.
Key takeaways
- javac Hello.java → Hello.class
- java Hello runs a class by its name, not its file name
- java Hello.java compiles in memory and runs in one step
- jshell: type a line, see the result immediately
Source-file mode even supports scripts: on macOS or Linux, a file without the .java extension that starts with #!/path/to/java --source 25 can be made executable and run like a shell script.
Practice questions
You've just run javac Hello.java. Which command runs the program?
- java Hello.class
- java Hello
- javac Hello
- run Hello.java
Check your answer
java Hello. java expects a class name (Hello), not a file name. java Hello.class fails with "Could not find or load main class Hello.class".
When you run java Hello.java, where is the compiled bytecode stored?
- In Hello.class next to Hello.java
- In a hidden .java folder in your home directory
- In the JDK's lib folder
- Nowhere: it's compiled in memory and not saved to disk
Check your answer
Nowhere: it's compiled in memory and not saved to disk. Source-file mode keeps the compiled classes in memory only. That's why it's great for scripts and quick experiments, but you still use javac or a build tool for real projects.