How a Java Code Runs

Internal Working of a Java Code

As we have read earlier, Java is a platform independent language. Hence instead of a one- step compilation it follows a two-step execution of a program.

  • Compile time.
  • Run time.

1. Compile Time

  • This step is handled by the JDK that contains the OS- dependent compiler.
  • Initially, the source ‘.java’ file is passed through the compiler, which then encodes the source code into a machine independent encoding, known as Bytecode.
  • The content of each class contained in the source file is stored in a separate ‘.class’ file.

2. Run Time

  • The bytecode generated by the compiler will be executed by Java Virtual Machine (JVM).
  • To run, the main class file (the class that contains the method main) is passed to the JVM, and then goes through three main stages before the final machine code is executed. 
2.1 Classloader
  • Java class loader is an abstract class which loads classes from various sources.
  • It is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of class loaders.
  • Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically.
2.2 Bytecode Verifier
  • A JVM Bytecode Verifier acts a gatekeeper of sorts whose  main task is to check if the loaded bytecode are valid and do not violate any rules of security.
  • it ensures that code passed to the Java interpreter is in a fit state to be executed and can run without fear of breaking the Java interpreter.
  • The following are some of the checks carried out:
    • Variables are initialized before they are used.
    • Method calls match the types of object references.
    • Rules for accessing private data and methods are not violated.
    • The run time stack does not overflow.
    • It doesn’t forge pointers.
    • It doesn’t violate access restrictions.
    • It accesses objects as what they are.

    If any of the above checks fails, the verifier doesn’t allow the class to be loaded.

2.3 Just-in-Time Compiler
  • This step involves reading the bytecode stream and carrying out the execution of the program which is done by the conversion of byte code into machine code.
  • A JVM is, in effect, a bytecode interpreting machine running on a hardware machine. This interpreting stage has an overhead and slows the program execution performance of Java applications. Java bytecode is extremely compact, allowing it to be easily delivered over a network.