Understanding Java Hello World: Compilation and Runtime Explained

Discover the journey of a Java Hello World program from compilation to execution. Learn what happens during compile time when Java code is transformed into bytecode and explore key concepts that enhance your understanding of Java programming.



We have created a Java Hello World program and learned how to compile and run a Java program. In this section, we will learn what happens during compilation and runtime, and answer some questions based on the first program.

What Happens at Compile Time?

At compile time, the Java file is compiled by the Java Compiler (which does not interact with the OS) and converts the Java code into bytecode.

What Happens at Runtime?

At runtime, the following steps are performed:

  1. Classloader: It is the subsystem of JVM that is used to load class files.
  2. Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to objects.
  3. Interpreter: Reads the bytecode stream and executes the instructions.

FAQ

Can you save a Java source file with a name other than the class name?

Yes, if the class is not public. For example:

Code

// File: Hard.java
class Simple {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

To compile: javac Hard.java
To execute: java Simple

Observe that we compiled the code with the file name but ran the program with the class name. Therefore, we can save a Java program with a name other than the class name.

Can you have multiple classes in a Java source file?

Yes, you can have multiple classes in a Java source file. For example:

Code

class FirstClass {
public static void main(String[] args) {
System.out.println("This is the first class");
}
}

class SecondClass {
public static void main(String[] args) {
System.out.println("This is the second class");
}
}