A “Hello, World!” Program

A “Hello, World!” program is a common first program that programmers write when learning a new language. This is because it’s usually the simplest possible program you can write and it shows that everything is set up correctly.

The quintessential “Hello, World!” program simply outputs the text “Hello, World!” on the screen. But before we do that let’s click the run button at the top-right and see what happens. The Run window should appear with the program output that will look something like this:

"C:\Program Files\Java\jdk-13.0.1\bin\java.exe" "-javaagent:C:\Program Files…

Process finished with exit code 0

You can ignore these two lines. The actual output of the program appears between them. Except, there’s nothing there! This shouldn’t come as a surprise since the main method is empty and therefore there’s no instructions for Java to execute and no output to produce. The program starts, Java sees the method is empty, and the program immediately ends. So, let’s write some code. To output the text “Hello, World!”, type the following instruction in the main method:

System.out.print("Hello, World!");

It needs to be typed exactly like this otherwise the program may not run. For instance, the first word “System” needs a capital S but the words “out” and “print” need lowercase. These words are separated by full stops/periods which we call “dots” in the programming world, so you would read the above code as System-dot-out-dot-print. Following are two parentheses (round brackets) containing the text “Hello, World!”, which must go between double quotation marks. Finally, we end the line with a semicolon. Your program should look like this:

public class Main {

    public static void main(String[] args) {
        System.out.print("Hello, World!");
    }

}

Go ahead and run it. You should see the text “Hello, World!” appear in the Run window (also known as the console):

"C:\Program Files\Java\jdk-13.0.1\bin\java.exe" "-javaagent:C:\Program Files…
Hello, World!
Process finished with exit code 0

What we wrote is a print statement. In this context, print doesn’t mean it will be sent to a printer. It means it will output the text to some designated window or console. Most languages have their own version of a print statement that fulfils a similar purpose.

Note
Statement is basically another word for instruction or command. It’s code that states some kind of action to be performed.

Try changing the text between the double quotes and running the program again. Whatever you write will be outputted. After that, try copying and pasting the whole statement a few times and changing the text in each one. For example:

public class Main {

    public static void main(String[] args) {
        System.out.print("Cat");
        System.out.print("Dog");
        System.out.print("Rabbit");
    }

}

Running this program gives the output:

CatDogRabbit

The three print statements are executed from top to bottom, one at a time. The first one prints “Cat”, the second one “Dog”, and the third “Rabbit”. It looks as though the entire text appears on the screen all at once but make no mistake, the computer is still executing each statement sequentially. It does this so fast that you cannot see it happening. You may wonder why Cat, Dog, and Rabbit appear one after the other and not on separate lines. It’s simply because each print statement just outputs text to the Run window and does not specify how it should be formatted. For instance, if I said to you “type ‘Cat’, now type ‘Dog’, now type ‘Rabbit’” then you would end up with “CatDogRabbit” if you followed my instructions exactly.

Debugging

To “debug” a program means to remove bugs. Most IDEs comes with a debugger, which is a piece of software that helps us identify bugs in our programs. The debugger also has a neat feature that enables us to step through the program manually, following the program as it executes each line of code.

At the top-right, next to the Run button, is the Debug button. If you were to click it now, the program would run like normal. However, if you click just to the right of one of the line numbers, a red dot should appear. This is called a breakpoint (you can click it again to remove it). When you debug a program and it reaches a line with a breakpoint it will become suspended (paused) and wait for you to tell it when to continue.

To see this in action, put a breakpoint against the first print statement (by clicking next to the line number). A red dot should appear and line highlights red:

Now click the Debug button at the top-right (next to the Run button). At the bottom the Debug window should appear. Click the Console tab so we can still see the program output while debugging.

Since we clicked debug, the program started but is now suspended at the line with the breakpoint. This happened immediately due to it being the first line in the method. You should see that the line becomes highlighted in blue. If you look at the debug window again there a few icons with arrows. Click the Step Over button once. This causes the debugger to execute the current line and stop at the next one. If you look at the debug window you should see the text “Cat” from the first statement has been printed.

Keep clicking the step over button and follow the program as it executes each statement in order. You will see the text gradually appear in the Console window as the program progresses. After a few clicks the program will reach the end of the main method, denoted by the closing brace (curly bracket). The program will terminate (end) when it reaches this point as you will see.

Note
The way the computer moves through the program is called the control flow or flow of control. It is the sequence in which statements are executed.

Simple Formatting Using Escape Sequences

Let’s see how we can print each word on a separate line. For this we can use the newline escape sequence. It’s a lot easier than it sounds. Simply write \n (backslash-n) after each word.

public class Main {

    public static void main(String[] args) {
        System.out.print("Cat\n");
        System.out.print("Dog\n");
        System.out.print("Rabbit\n");
    }

}

Run the program and you’ll see that each word appears on its own line.

Cat
Dog
Rabbit

The reason this happens is because a \n is interpreted as a newline. So, the first print statement prints “Cat”, followed by a newline. This causes the output cursor to move down to the next line. The next statement then prints “Dog” and again moves the cursor onto a new line. The third print statement prints “Rabbit” and also moves the cursor onto a new line (which isn’t strictly necessary since there’s no words to follow this). Placing newlines at the end of a word or sentence is quite a common requirement, which is why Java provides a similar print instruction that does this automatically. It looks like this:

System.out.println

The only difference is in the third word (println instead of print). println stands for “print line”. This instruction will automatically put a newline at the end. So, let’s remove every \n and change each print to println:

public class Main {

    public static void main(String[] args) {
        System.out.println("Cat");
        System.out.println("Dog");
        System.out.println("Rabbit");
    }

}

If we run the program, we get the same output as before:

Cat
Dog
Rabbit

In fact, you can use as many newlines as you want, wherever you want. For example, the following program uses only one print statement and two newlines:

public class Main {

    public static void main(String[] args) {
        System.out.println("My cat\nthat sat\non the mat.");
    }

}

Run the program and it outputs:

My cat
that sat
on the mat.

About Print Statements

I want to give you a brief insight into the two print statements we’ve used. Don’t worry if this section isn’t totally clear, it’s not necessary to understand most of it at this time and we’ll go into more detail in later chapters.

So, why is System.out.print written the way it is? The statement System.out.print is a lot like a file path. On your computer, imagine you have a folder called “Documents” that contains another folder called “Work” that contains a file called “expenditures.pdf”. The file path is “Documents/Work/expenditures.pdf” (Documents contains Work contains expenditures.pdf). The dots in System.out.print are a lot like the forward slashes in the file path, so System contains out contains print. Specifically, System is a class. This System class is written with the same structure and principles that our Main class is based on, with curly brackets and everything! It’s one of the many thousands of classes that come pre-written with the Java platform. System contains out, which is a variable (covered in chapter 5). This variable contains something called an object. This object contains print, which is a method. So, just like our main method contains instructions, the print method contains its own instructions about printing to the console window. When we write System.out.print, the general programming term for this is a method call because we are calling upon it (the print method) to do some work i.e. print some text. This is also known as a method invocation. We will call many different methods throughout this book to help achieve our goals.

Let’s take a look at what’s inside the System class. If you type System. (that’s System followed by a dot), a menu will pop up that shows all the different elements inside System.

These are all members of the System class. A member is something that exists inside the class (among other things). For instance, our main method is a member of our Main class. Scroll to the bottom of this list and you can see the familiar out member. Now double-click it, and it will be written for you (you can also use the arrow keys and enter). Now type another dot, and another list will appear with all the members of out. You’ll see there are a lot of print methods in here.

The difference between them is that they all accept different types of data. We’ll look into this in chapter 2. For now, select any one of the print methods to add it in. (This code completion functionality is useful for informing you of what is and what isn’t valid code, and can save you a lot of time as well as typing.) Your line should look like this:

System.out.print();

This code will probably be underlined in red since it’s incomplete. The reason is that the two parentheses/brackets cannot be left empty. The parentheses are used to pass data to the print method. In other words, whatever we type in the parentheses will be passed to the print method so that the method may print it. If we don’t pass in any data then there’s no point in calling it in the first place. Previously we have passed text, which must go between double-quotes so that Java interprets it as plain text and doesn’t misinterpret it as code. The programming term for text is a string, as in a string of characters. Whenever we write stuff between double-quotes, we are writing a string.

System.out.print("You can never have enough strings.");

You can, in fact, write nothing between the double-quotes:

System.out.print("");

This is called an empty string. The print method will still accept it so you can run the program just fine but you can probably guess that it won’t print anything in this case.

The Run Process

If you had run any of the previous programs, by now you may have noticed that they don’t run straight away and it takes a second or two before you see the output. The reason for this is that your computer cannot readily understand Java code and so the program must go through several translation steps before it is able to start running.

So, what happens when you click Run? First, a specialised program called a compiler will attempt to compile the program. This means it will gather all the files that make up the program (one file in our case) and translate them into Java bytecode. Java bytecode is an intermediate language—a language between Java and machine code. For the program to run, at some point the Java bytecode must be translated into machine code. This is the responsibility of the Java Virtual Machine (JVM), which performs real-time translations as the program is running. This process is called just-in-time compilation (JIT).

The JVM is how Java achieves cross-platform compatibility. There are many computers in the world with significantly different hardware. If you compile your Java code to machine code for one hardware specification, it may not work on another. Instead, you compile your program to Java bytecode. As long as the computer running the program has a JVM installed, it will be able to convert the bytecode to machine code suitable for the hardware.

The compiler, debugger, and JVM are all included in the JDK we downloaded in the beginning. IntelliJ IDEA is providing us a powerful interface to those components, which is just one of the many reasons to use an IDE.

Classes and Packages

Throughout this book there will be many opportunities to write and run code. Every time you want to write a new program you could delete all the code in the main method to start again, but you may also want to keep certain programs instead of deleting them. You could create a new project for each program but for such small programs this is a little excessive. A better way is to create a new class for each program and organise them further into packages if necessary. You could also change the name of the current class from Main to something more fitting like HelloWorld. To do so, move your mouse over the class name (Main) and right-click it. Then go to Refactor > Rename…. Then type something like HelloWorld and press enter. You will see that not only has the class name changed, but also the name of the file, which has changed from Main.java to HelloWorld.java. This is because, in Java, both the name of the class and filename must match. This is why it’s better to go through the Refactor menu as IntelliJ IDEA will update both automatically (as opposed to simply erasing the name and writing a new one).

Note
There are standardised styling rules for class names. The main rule is they should be written in Pascal Case. This means that each word should start with a capital letter and there should be no spaces between words.

To create additional classes for more programs, right-click the src folder in the Project window and go to New > Java Class. Then enter a name, like HelloWorld2. Make sure Class is selected and press enter. A new class is created called HelloWorld2. This class is probably empty. To get the main method in this class, you could hand-type it or copy-paste it from the other class. However, the easiest way is to simply click inside the class body and type the word main. IntelliJ IDEA should pop up with a suggestion. Press enter and the main method will be added automatically.

At this point there are two classes with the main method in, so which one does IntelliJ IDEA execute when the run button is clicked? It will still only execute the main method in the first class that we started with. To run the new class, right-click its file in the Project window and click Run (it will say something like Run ‘HelloWorld2.main()’). This class is now the ‘active’ class and will run whenever the Run button is clicked.

You will probably want to organise your classes into packages at some point. Let’s say you wanted to organise your classes by chapter. To start, right-click the src folder and go to New > Package. Type ch4 as the name of the package and press enter. A new package called ch4 is created. You can then drag the HelloWorld files into this package. On doing so, a Move dialog will appear. Click Refactor and the move is complete. If you look at the code in these files, you’ll notice that a line has been added at the top that reads

package ch4;

This line tells you that the class is in a package called ch4. This line is required so that Java knows what package the class is in. By convention, package names should be lowercase, with multiple words separated by underscores e.g. my_lovely_package. This writing style is called snake case.

You can represent a hierarchy of packages by using the dot (.) notation. For example, the ch4 package may contain two more packages called sec1 and sec2, which in turn contain related classes. To demonstrate, right-click the ch4 package and go to New > Package. You will see it’s already partially filled in with the text “ch4.”. After this type sec1 so you end up with “ch4.sec1”. Then press enter. You will notice that package sec1 has been created in package ch4. Drag one of the HelloWorld files into this new package and click Refactor. Look in said file and you can see that the line at the top now reads

package ch4.sec1;

Ultimately, how you structure and name your packages and classes is up to you.

Leave a Reply

Your email address will not be published. Required fields are marked *