How to compile a java code?

by Feb 3, 2022

Executable files are not compiled by programs so first, they are compiled into bytecodes which are then executed by JVM (Java Virtual Machine) during the runtime. When we use the javac compiler Java source code is compiled into bytecode. Later the bytecode gets saved on the disk under the name of <.class>. When the program needs to be run the bytecode is converted again using the JIT compiler.

Java code is compiled twice before execution:

  1. When java code needs to be compiled into bytecode 
  2. When it is time to run the bytecode, it is then compiled into machine code.

To execute your online java code compiler follow these steps:

  1. Firstly install and configure your system for Java.
  2. Open your text editor which you set while installing the Java platform.
  3. Write the following codes in a new document 

code listing 2.5: HelloWorld.java

public class HelloWorld {

  public static void main(String[] args) {

    System.out.println("Hello World!");

  }

}

  1. Save this file as HelloWorld.java. Your file name should be the same as the class definition name followed by .java.

      5.Open the command-line application.

  1. Navigate to your directory where you just created the file in the command-line application.
  2. Compile the java source file using the command

javac HelloWorld.java

If there's an error message, your file is not in the current folder or maybe you have misspelled it. 

error: cannot read: HelloWorld.java 1 error

Or if it shows 

1 error or … errors means there is a mistake in your code. 

  1. Run the application using the command if the compiler returns to the prompt

java HelloWorld

If there’s an error message, your file is not in the current folder or maybe you have misspelled it

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld

Or if it shows 

Exception in thread "main" java. lang.NoSuchMethodError: main it means the source file is misspelled 

  1. If everything is right there will be output in your command-line application showing 

Hello World! As an output