Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't we use the .class extension with "java" command?

Tags:

java

Why don't we give the filename.class file after java command, instead of only filename?

Suppose we want to compile the test.java program, then we run javac test.java. It is ok!

After that it will produce test.class file but to run the program we run java test instead of java test.class. What is the reason for this?

like image 503
anirban karak Avatar asked Jul 17 '13 15:07

anirban karak


People also ask

Can Java run .class files?

If your class doesn't have any package name defined, simply run as: java App . If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp / -classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files.

For what is the Java name extension .class used?

A Java class file is a file (with the . class filename extension) containing Java bytecode that can be executed on the Java Virtual Machine (JVM).

Why do we need .class file in Java?

class files describes the instructions to the Java Virtual Machine. The . class file contains the bytecode that will translate by the JVM into platform-specific machine code.


2 Answers

Because you are not describing a file to run. You are telling Java which class contains the main method - and the class' name is (in your case) filename, not filename.class.

The fact that the bytecode is almost always contained in files on the filesystem is an implementation detail. The classpath you pass to the java command tells it where to look for classes, and then the main class argument tells it which class to use.

(It's different for javac, because this program specifically does take source files and compiles them into bytecode.)

like image 61
Andrzej Doyle Avatar answered Nov 15 '22 18:11

Andrzej Doyle


You don't pass a file name to the java command either. You pass it a fully qualified class name. Something like com.yourcompany.yourapp.Main. Java then finds the .class file for this class name, by looking into all the directories and jar files in the classpath.

like image 30
JB Nizet Avatar answered Nov 15 '22 19:11

JB Nizet