Compiling and running programs in Java

Introduction

Java is a compiled language. For a beginner programmer this means doing one more action: first run the command to compile into bytecode, and only then run from the file produced by the compilation.

In this Java is similar to C and C++ and differs from, for example, Python and PHP

Compilation

In short

javac Class.java
java Class

Go to the C:\Users\Username folder

create there a hello_java directory

and change into this directory

mkdir hello_java
cd hello_java

Create an empty file in Notepad and save it in hello_java under the name Hello.java

Copy the following code into this file

In Java the file name must match the class name. We named the file Hello.java, so the class must be called Hello

public class Hello { public static void main(String[] args) { System.out.println("Hello Java!"); } }

In the command line, execute

javac Hello.java

Hello.java will be compiled into Hello.class

Make sure that the file has appeared in the hello_java directory Hello.class by running

dir

Volume in drive C is C Volume Serial Number is FCB7-BB1E Directory of C:\Users\Andrei\hello_java 07/21/2020 04:18 PM <DIR> . 07/21/2020 04:18 PM <DIR> .. 07/21/2020 04:18 PM 422 Hello.class 07/21/2020 04:18 PM 145 Hello.java 2 File(s) 567 bytes 2 Dir(s) 81,734,488,064 bytes free

Even in such a simple program we have already managed to use the Java Standard Edition (SE) APIs by calling System

There are also Java Enterprise Edition (EE) APIs, but they are no longer supported by Oracle: they have been handed over to the Eclipse Foundation and are available at the link jakarta.ee

The next step is executing the code.

Execute

In the command line, execute

java Hello

Hello Java!

By calling java we addressed the Java Virtual Machine (JVM)

Java Standard Edition (SE) APIs + Java Virtual Machine (JVM) = Java Development Kit (JDK)

java + javac = JDK

Compilation with an explicit encoding

To specify the utf8 encoding explicitly

javac -encoding utf8 Hello.java

Article author: Andrei Olegovich