Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

Compiling your first Java program

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


After writing your first Java application it's now time to compile your program. We will see in this tutorial how to compile your first application.

Contents

the article

Basics

Java is a compiled language, this means that the code cannot be executed directly from the text files that we write, but they must be compiled.

The compilation is the process of translating the human readable software into something that is easier to read for the computer.

A compiler is a program that reads the human written source code and translates it into the compiled version, which, in Java, is called bytecode.

The most used compiler in Java is the official one distributed from Sun, called javac.

javac in its first versions was developed in C++ while now it's entirely developed in Java, and it can even be called from within a Java program.

javac accepts for input Java source code conforming to the Java Language Specification (JLS) and produces bytecode that conforms to the Java Virtual Machine Specification (JVMS).

How to compile

The JVMS says, among the rest, that the bytecode must be contained in files having the same structure as the source code, but the '.java' files will have extension '.class'. This means that if we use as input our "HelloWorld.java" file produced in our first Java application, it's compiled version will be in a file called "HelloWorld.class".

To produce this file the procedure is very simple (given that you have the JDK properly installed)

To compile the only thing you need to do is:

1: Open a command prompt

2: change to the directory that contains your "HelloWorld.java" file. For example 'c:\javaPrograms'.

3: execute the command

javac HelloWorld.java -verbose

Note: the '-verbose' option is not strictly needed but it will make javac print some information about what it is doing, it could be interesting to see it.

At the end of the compilation in your directory javac will have created a new file "HelloWorld.class". This file contains the bytecode of your application and it is ready to be executed.

"HelloWorld.class" contains now your program. See the next tutorial Executing your first program to learn how to execute your program.

See Also

Java Virtual Machine Specification, Java Language Specification

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.