Java programming language

Basic elements of a Java program

Structure of a Java program

  

Java is an object-oriented programming language, and this implies that we need to work with classes and objects. We’ll see later what a class is, but, for now, we only need to know that every piece of code in Java needs to be placed inside a class clause.

1. Our first Java program

Let’s see how to start with Java, by creating a simple Java program that prints “Hello” in the screen.

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

Let’s explain this code:

2. More about this example

The structure of this program is very similar to the same program written in C#: we always need to define a class, even if we only need a main block. This main block is written in lower case in Java.

Besides, every public class must have the same name as the source file that contains it, so we need to store the source code of the example above in a file called MyClass.java (Java source files have .java extension). If we want to compile this code, we use javac tool from our JDK installation. We can do it through any IDE, such as Geany, or IntelliJ, as long as we have Java JDK properly installed.

javac MyClass.java

Then, a new file called MyClass.class will be generated. This is the compiled file that can be run under the Java Virtual Machine (JVM), using the java command. This last step can also be done under any IDE.

java MyClass

After running this program, we will see a “Hello” message in the screen.