In this chapter we will create a new Java project in IntelliJ IDEA. The project will start off with a small amount of Java code. We will use an analogy of a recipe to understand the purpose of this code.

Creating a New Project

  1. Open IntelliJ IDEA.
    1. If you’re opening it for the first time, a small dialog may appear. Select Do not import settings and click OK. Next, you can choose the UI theme. Click on Darcular and Light to see which one you like best. For this book, I’m going to select the Light theme. Now click Skip Remaining and Set Defaults.
  2. Click Create New Project.
  3. On the left, make sure Java is selected. At the top you can select the Project SDK. This is where the JDK goes so that IntelliJ can interact with it. Current versions of IntelliJ may already show JDK 11 in the box. This is likely an error or a temporary measure since this JDK should not be used for Java development. Instead, click New and locate the JDK we downloaded previously. It should be under “C:\Program Files\AdoptOpenJDK”. Select the JDK folder inside e.g. jdk-13.0.1.9-hotspot. Then click OK. Then click Next.
  4. Select Create project from template. Click Next.
  5. On the next screen you can enter a project name, project location, and a base package.
    1. For the project name, enter “HelloWorld”.
    2. For the project location, you can leave it as the default or change it if you wish (just make sure the project location is set to either an empty folder or a folder that doesn’t exist because IntelliJ will put all the project files in this folder).
    3. For the base package1, it will probably say “com.company”. Delete this and leave it blank.
  6. Click Finish.
  7. The project will take a few moments to set itself up. One of the first things you’ll see is a Tip of the Day. You can close this.

1Packages can be thought of as the Java equivalent of folders. There are units of Java code called classes that can be put into different packages for organisational purposes. Packages also help to prevent naming conflicts because two classes with the same name cannot exist in the same package, similar to how two files with the same name cannot exist in the same folder. As long as they’re in separate packages, identically named classes isn’t an issue.

Your screen should look like this:

Figure 3‑1 | Fresh project in IntelliJ IDEA

On the left is the Project Window that shows us all the files in the project. Look in the HelloWorld/src folder and you will see a file called Main (Main.java). This is the file that’s currently open in the middle of the screen. The code shown is the contents of this file. You can close files via the tabs along the top and you can open files by double-clicking them in the Project window.

All the Java files we create will go in the src (source) folder. Java files have a .java extension, but other than that they are basically text files. To prove it, right-click the Main file and click Show in Explorer. Then in file explorer, right-click the Main.java file and go to Open with > Notepad. Unsurprisingly, it’s the same text as shown in the IDE, except IDEs automatically highlight and format the text for usability’s sake.

What does the code do?

We have some code in front of us but what does it mean? What does it do? Not a lot, really. This code is more structural than anything. But instead of slogging our way through explaining the code word for word, let’s gain an understanding of this code by way of an analogy.

A cookbook is surprisingly similar to a Java program. Imagine that we flick through the book and land on a page that details a recipe for baking a sponge cake. It might look something like this:

Recipe: Sponge Cake
 
Ingredients:
    ●  Flour
    ●  Eggs
    ●  Sugar
    ●  Water
 
Method:
    1. Preheat oven to 160C.
    2. Sift flour into a bowl.
    3. Sift in sugar.
    4. Sift in bicarbonate of soda.
    5. Mix together.
    6. Crack eggs into the bowl.
    7. Mix together well.
    8. Scoop bowl contents into tin.
    9. Place tin in oven for 25 minutes.

You can see a recipe has a structure to it with the title at the top, then the ingredients, and finally the method. You can also infer a hierarchy of sorts; you have the recipe itself—a sponge cake—which encapsulates a particular set of ingredients and a method. In turn, the method encloses a set of instructions. This concept of nesting elements inside other elements is what Java is all about. To aid in this understanding, let’s see how one might rewrite the recipe into a form that resembles a Java program. First, we’ll start with the title:

recipe SpongeCake { }

Like before, this tells us that the recipe is a sponge cake. Because it’s following the rules of the Java language, the name of the recipe cannot have spaces, therefore words are capitalised to distinguish them i.e. SpongeCake. Next is a pair of curly brackets/braces ( {} ). These brackets are the body/definition of the recipe; they’re purpose is to enclose/contain the recipe’s contents. Put simply, between these brackets is where the ingredients and method need to go. But how do these things fit in the brackets in a readable way? We simply put the closing bracket ( } ) further down the page:

recipe SpongeCake {



}

Anything that comes after the opening bracket ( { ) but before the closing bracket ( } ) is technically inside the brackets. So, let’s now insert the method:

recipe SpongeCake {

    Method:
        Preheat oven to 160C;
        Sift flour into a bowl;
        Sift in sugar;
        Sift in bicarbonate of soda;
        Mix together;
        Crack eggs into the bowl;
        Mix together well;
        Scoop bowl contents into tin;
        Place tin in oven for 25 minutes;

}

Spanning lines 3 to 12 is the method. The instructions are not labelled 1 to 9 like before because Java doesn’t use step numbers. This isn’t necessary because we naturally read from top to bottom anyway. Each instruction ends with a semicolon because semicolons are used to end instructions in Java. Also, just like the method is contained in the recipe, we can also say that the instructions themselves are contained in the method. Let’s reflect this by using another pair of curly brackets:

recipe SpongeCake {

    main {               
        Preheat oven to 160C;
        Sift flour into a bowl;
        Sift in sugar;
        Sift in bicarbonate of soda;
        Mix together;
        Crack eggs into the bowl;
        Mix together well;
        Scoop bowl contents into tin;
        Place tin in oven for 25 minutes;
    }

}

On lines 3 and 13 are the method’s brackets that contain the instructions. They denote the body of the method. Also, line 3 now reads “main” instead of “Method”. This is because a real Java program can have multiple methods and therefore each method needs a name to distinguish it from other methods. I’ve named it “main” simply because it is the only method in the recipe, which sort of makes it the main method by definition. Notice, also, the levels of indentation. Because the recipe itself is at the “top” level, it is not indented. However, because the main method is inside the recipe, it’s indented once to the right to make this clear to the reader. Then, inside the method are the instructions so they are indented once to the right relative to the method, which means they are indented two to the right overall. Incidentally, I’ve decided I don’t like the instructions I’ve written and would rather someone else write them. So, I’m going to erase them and leave a note to the next person who wants to author this recipe:

recipe SpongeCake {

    main {
        Note: Write instructions here
    }

}

And with that we can make some comparisons.

A Class Is Like a Recipe

Let’s now look at both the empty recipe and the Java program side by side:

recipe SpongeCake {

    main {
        Note: Write instructions here
    }

}
public class Main {

    public static void main(String[] args) {
        // write your code here
    }

}

Can you see the similarities between the two? Let’s break it down.

The “Main” class

On line 1 of the recipe it reads recipe SpongeCake and on line 1 of the program it reads public class Main. In Java, a class is like a recipe. “Main” is simply the name of the class, just like “SpongeCake” is the name of the recipe. But how exactly are they similar? Well, if you think about it, the title of a recipe doesn’t do much other than tell you what the recipe is. It’s the content that matters. In one sense, the same could be said for a class. You can think of a class as a container, label, or title, and it’s the content that matters most. When you learn about object-oriented programming (OOP) you’ll see that classes are much more than this but for our purposes this definition is suitable. Why is the class called Main? It’s just a default, descriptive name more than anything. Being the only class that exists in our project makes it the main one. We could change its name to almost anything we like, just like you can give your personal recipe any name you like, although we’ll leave it as Main for now. The curly brackets on lines 1 and 7 have the same purpose as in the recipe. The brackets represent the class body and contain the content of the class.

The “main” Method

Spanning lines 3 to 5 is the method. Remember that in the recipe, “main” is the name of the method, and the two curly brackets will contain instructions for the reader to follow. There’s even a note on line 4 telling the author that they should write the instructions here. In the program, the method works the same way, except the brackets will contain Java instructions for the computer to follow and, again, there’s a note telling the program author that they should write their code/instructions here.

On line 3, we can see the method simply starts with the method name, that is: main. We can call this the method header. In Java, the method header consists of much more than just a name i.e.: public static void main(String[] args). That’s a mouthful. The first three words–public, static, and void–can be ignored. For now, we can pretend they’re not even there since they’re not yet applicable to our learning objectives. The fourth word main is the name of the method, just like in the recipe. After this is the code (String[] args). Again, we can ignore this as well.

In Java, we call this method the “main method” or simply “main”. The main method is the entry point of the program. This means that Java will always run/execute the instructions in this method first, before any other method. In fact, it is the only method that runs automatically when the program starts. Any other methods you write will only run if you, the programmer, tell them to run. The main method must be written exactly as shown in the program. If you remove the main method or change some part of it and then try to run the program, Java will complain that it cannot find the main method and the program will not run. For example, if you were to simply remove the main method, then you’d be left with just the class definition:

public class Main {
    
}

Running the program at this point would cause a window to pop up with an error message:

Error: Main method not found in class Main, please define the main method as:
   public static void main(String[] args)

That’s pretty easy to understand. The message tells us that Java cannot find the main method in the class. It also says that you should write the main method as public static void main(String[] args). The class without the main method is like a recipe without a method—it is devoid of instruction. On the other hand, if you include the main method but omit the Main class:

public static void main(String[] args) {
    // write your code here
}

That won’t work either. Running the program now produces the following error:

Error:(3, 19) java: class, interface, or enum expected

It expects to see a class (or interface or enum). The main method without a class is akin to a recipe with no name–it has no identity and is structurally invalid.

So, there you have it. You need both a class and main method for Java to be happy.

Comments

At the moment the main method contains a line which reads “write your code here”. Obviously, it’s telling us to write our code there but how does Java interpret that? It’s an English sentence, after all, not Java code. Java will actually ignore this line because it has two forward slashes (//) at the beginning. A line with two forward slashes at the beginning is a comment. Whenever Java comes across a comment, it will ignore it and skip over it. This is because comments are designed for us to read, as humans, and they are not Java code. Comments are little notes you can leave for yourself within the program, or for other people. For example, if you have written some code that needs some explaining, you could document it by putting comments above or near the code that explain what it does, how it works, why it’s needed, etc. You might also write comments for the purpose of reminding you or your colleagues to add or make changes to parts of the program. Feel free to erase the comment inside of main because we’re going to write some Java in there next.

Leave a Reply

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