To compile Foo.java: javac Foo.java
To run the program : java Foo
Why compiler needs .java
suffix but interpreter doesn't need .class
suffix?
As a couple of other answers have explained, the Java compiler takes a file name as an argument, whereas the interpreter takes a class name. So you give the .java
extension to the compiler because it's part of the file name, but you don't give it to the interpreter because it's not part of the class name.
But then, you might wonder, why didn't they just design the Java interpreter differently so that it would take a file name? The answer to that is that classes are not always loaded from .class
files. Sometimes they come from JAR archives, sometimes they come from the internet, sometimes they are constructed on the fly by a program, and so on. A class could come from any source that can provide the binary data needed to define it. Perhaps the same class could have different implementations from different sources, for example a program might try to load the most up-to-date version of some class from a URL, but would fall back to a local file if that failed. The designers of Java thought it best that when you're trying to run a program, you don't have to worry about having to track down the source that defines the class you're running. You just give the fully qualified class name and let Java (or rather, its ClassLoader
s) do the hard work of finding it.
The Java compiler takes a filename as input, hence Foo.java.
the Java interpreter takes the fully qualified class name and searches the classpath and current directory for the class. If you use java Foo.class it would search for the class named "class" in the package "Foo", and return NoClassDefFoundError if the class is in the default package, as I understand from your example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With