29

Can anyone tell me how I can convert a .java file into .class file with an executable bytecode?

8 Answers 8

60

A .java file is the code file. A .class file is the compiled file.

It's not exactly "conversion" - it's compilation. Suppose your file was called "herb.java", you would write (in the command prompt):

 javac herb.java

It will create a herb.class file in the current folder.

It is "executable" only if it contains a static void main(String[]) method inside it. If it does, you can execute it by running (again, command prompt:)

 java herb
2
  • 11
    Note. Javac expects a FILENAME (hence the herb.java) and Java expects a CLASSNAME (hence herb). That difference bites most beginners. Commented Aug 19, 2009 at 9:00
  • Not only that, java expects a fully qualified name and expects them to be in a directory structure based on the package structure, while javac can deal with files being anywhere. Commented Aug 19, 2009 at 17:36
16

From the command line, run

javac ClassName.java
8

I would suggest you read the appropriate sections in The Java Tutorial from Sun:

http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

4

Use the javac program that comes with the JDK (visit java.sun.com if you don't have it). The installer does not automatically add javac to your system path, so you'll need to add the bin directory of the installed path to your system path before you can use it easily.

2

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:

javac File.java
2

As the others stated : it's by compiling. You can use the javac command, but I'f you're new at java, I suggest you use a software for compiling your code (and IDE) such as Eclipse and it will do the job for you.

1

You can not compile any java file to class directly. It should have main method to compile it in class file

-4

After compiling it you can jar it.

java -jar AppName.jar

http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html

1
  • 3
    This command (java -jar AppName.jar) does not jar it up, it executes something that has already been jarred as an executable jar file. In order to put a .class file into a jar, you would use the jar command; as in "jar -cf myjar.jar classes/*" In order to create a jar that can be executed with the java -jar command you need to specify the main class in the manifest file. This is all well beyond the scope of the original question, so if you want to know more, google "create executable jar". Commented Aug 18, 2009 at 21:12