Java is compiled language. But it is very different from traditional compiling in the way that after compilation source code is converted to byte code. Javac is the most popular Java compiler for this purpose. One of the key modules used for making Java applications is Java Development Kit or JDK, which is made available by Oracle and Javac is the key sub-module of this module. Javac is also written in Java.
Working of compiler in Java
When you write a program code, verification of method signatures and other variables is performed at compile-time. In general, a compiler converts the source code to target code. Usually this target code is machine language and it is dependent on the machine. Which means it differs from one machine to another. But Java compiler converts the source code to byte code, which acts as an intermediate code. This type of code is machine independent. Which means you can execute it on any platform provided a virtual machine for Java. Java has a virtual machine called JVM which then converts byte code to target code of machine on which it is run.
Here, JVM performs like an interpreter. It doesn’t do it alone, though. It has its own compiler to convert the byte code to machine code. This compiler is called Just In Time or JIT compiler.
Compiling a program using Javac:
To compile a program written Java, you need to run the compiler by typing name of the file with javac command on command prompt. Javac command comes with multiple options and cross-compilation is one of them. Default feature allows classes to be compiled in the similar implementation alongside bootstrap classes. Cross compilation allows compiling classes on different platform.
For example, let’s say you created a Java program file named ‘my_first_file.java’. You can compile it using Javac as follows:
If my_first_file refers to some other classes in another Java file but saved in the similar folder, javac would compile that file too. If you wish, you can list multiple file names explicitly. For example,
|javac my_first_file.java another_file.java oneMore_file.java|
To generate all the options available, you can use –help option with javac command.
To specify the directory of target class: For big projects, it is advised to maintain source and target files in different directories. For this purpose you can make use of option –d. For example,
|javac –d <target directory> my_first_file.java|
|javac –g my_first_file.java|
If you are not sure of the source where input files are placed, you can always find it using –sourcepath option.
If you are wondering how the compiler is processing files during compilation process, you can make use of –verbose option as follows:
|javac –verbose my_first_file.java|
There are many other compilers to compile Java program code. Some of these are mentioned below:
- GNU compiler
- Graal VM
- ECJ (Eclipse compiler) Etc.