Learning Java, How A Java Code Is Compiled And Interpreted

Today, I have started my morning with learning Java programming language. The first thing that arose my interest in Java is the way a Java code is compiled and interpreted. The process of running Java code is Hybrid-Compiler-Interpreter where Javac works as hybrid compiler which is included in JDK/Java Development Kit and JVM/Java Virtual Machine works as interpreter. mbuf helped me to make my concept clear on how it works.

In Java, all code must reside inside a class and the class name should match with the file name that holds the code. I will give a simple example of a java program that prints Hello World.

public class A  //Defines a class called A
    public static void main(String args[]) //Calls the main() method
        System.out.println("Hello world");//Prints Hello world to the console

Here we need to give the name of the file as A.java since the name of the class is A. To run this java code do the following in terminal.

javac A.java compiles the code A and creates a file named A.class that contains the bytecode version of the program which makes the code platform independent. This is an intermediate representation of the code that contains instructions the JVM will execute on next step.

Now java A actually runs the program. Here JVM works as interpreter. When Java source code is compiled, a file is created using .class extension with the name of the class used in the code. This is why Java file name and class name must be same. When we do java A we actually specify the name of the class that we want to execute. java A searches for a file by that name that has .class extension. If it find the file, it executes the code contained in the class.

The way a java code is compiled and interpreted is so interesting that I couldn’t stop myself sharing this blog post with you 🙂