Home Programming Learn Java with Projects

Learn Java with Projects

By Dr. Seán Kennedy , Maaike van Putten
books-svg-icon Book
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Getting Started with Java
About this book
Learn Java with Projects stands out in the world of Java guides; while some books skim the surface and others get lost in too much detail, this one finds a nice middle ground. You’ll begin by exploring the fundamentals of Java, from its primitive data types through to loops and arrays. Next, you’ll move on to object-oriented programming (OOP), where you’ll get to grips with key topics such as classes, objects, encapsulation, inheritance, polymorphism, interfaces, and more. The chapters are designed in a way that focuses on topics that really matter in real-life work situations. No extra fluff here, so that you get more time to spend on the basics and form a solid foundation. As you make progress, you’ll learn advanced topics including generics, collections, lambda expressions, streams and concurrency. This book doesn't just talk about theory—it shows you how things work with little projects, which eventually add up to one big project that brings it all together. By the end of this Java book, you’ll have sound practical knowledge of Java and a helpful guide to walk you through the important parts of Java.
Publication date:
November 2023
Publisher
Packt
Pages
598
ISBN
9781837637188

 

Getting Started with Java

Welcome to the exciting world of Java! Java is a very popular programming language. It is a multipurpose, powerful, and popular programming language that has been used by millions of developers worldwide to create a wide variety of applications. And yes, it really is multipurpose since it can be used to create all sorts of applications, from web and mobile apps to game development and beyond.

So, you’ve done a great job choosing a (new) language. We’re going to take you on a (hopefully) fascinating journey that will provide you with valuable skills and open new opportunities in the ever-evolving field of technology.

What are we waiting for? In this chapter, we’re going to cover the following main topics:

  • Java features
  • Installing Java
  • Compiling and running Java programs
  • Working with an integrated development environment (IDE)
  • Creating and running a program with an IDE
 

Technical requirements

Before diving into the magical world of Java programming, let’s ensure you have the right hardware. If your hardware doesn’t meet these requirements, don’t worry; online alternatives are discussed later in this chapter. If you are using your work laptop, make sure that you have download rights. Here’s a brief overview of the requirements:

  • Operating system: Java can run on various operating systems, including Windows, macOS, and Linux. Ensure that you have a recent version of one of these operating systems installed on your computer.
  • Java Development Kit (JDK): To compile and run Java programs, you’ll need the JDK installed on your system. The JDK includes the Java Runtime Environment (JRE), which contains the necessary libraries and components for running Java applications. We’ll see how to install this later.
  • System resources: More is always better, but Java isn’t too demanding. It doesn’t require high-end hardware, but it’s still a good idea to have a system with sufficient resources for a smooth development experience. The following are the minimum and recommended system requirements:
    • Minimum requirements:
      • CPU: 1 GHz or faster processor
      • RAM: 2 GB
      • Disk space: 1 GB (for JDK installation and additional files)
    • Recommended requirements:
      • CPU: 2 GHz or faster multi-core processor
      • RAM: 4 GB or more
      • Disk space: 2 GB or more (for JDK installation, additional files, and projects)

Keep in mind that these requirements may change with future updates to the JDK and related tools. We have placed the files in a GitHub repository. You can clone the projects with the use of Git and import them to your computer this way. It’s beyond the scope of explaining how to use Git here but it’s recommended to look into it independently. You can access the files and examples used in this book here: https://github.com/PacktPublishing/Learn-Java-with-Projects.

 

Exploring Java features

Java was developed by James Gosling at Sun Microsystems in the mid-1990s. When Java was created, it was originally designed as a language for consumer electronics. It attempted to support complex host architectures, focused on portability, and supported secure networking. However, Java outgrew its own ambitions. It quickly gained momentum as a versatile language for creating enterprise, web, and mobile applications. Today, Java no longer belongs to Sun Microsystems. Oracle Corporation acquired Sun Microsystems in 2010. And with that acquirement, Java became an integral part of Oracle’s software ecosystem.

Java was very unique at the time it was created. The huge success of Java can be attributed to some of its core features. These features were very innovative at the time but are now found in many other (competing) languages. One of the core features is object-oriented programming. OOP allows us to structure our code in a neat way that helps with reusability and maintainability. We’re going to start discussing the core features by having a look at object-oriented programming (OOP).

OOP in Java

Arguably the most important feature of Java is its support for OOP. If you ask any Java developer what Java is, the answer is often that it’s an OOP language.

It’s safe to say that OOP is a key feature. What is this OOP thing? you may wonder. OOP is a programming paradigm. It structures applications to model real-world objects and their interactions and behaviors. Let’s go over the main concepts of OOP:

  • Objects: This may be stating the obvious but, in OOP, objects are the main building blocks of your program. An object is a representation of a real-world entity, such as a user, an email, or a bank account. Each object has its own attributes (data fields) and behaviors (methods).
  • Classes: Objects are created using their class. A class is a blueprint for creating objects. It defines the attributes and methods that objects of the class should have. For example, a Car class might define attributes such as color, make, and model, and methods such as start, accelerate, and brake.
  • Inheritance: Another key feature is inheritance. Inheritance allows one class to inherit the attributes and methods of another class. For example, Car could inherit from a Vehicle class. We’re not going to cover the details here, but inheritance helps to better structure the code. The code is more reusable, and the hierarchy of related classes opens doors in terms of what we can do with our types.
  • Encapsulation: Encapsulation is giving a class control over its own data. This is done by bundling data (attributes) and methods that operate on that data. The attributes can only be accessed via these special methods from outside. Encapsulation helps to protect the internal state of an object and allows you to control how the object’s data can be accessed or modified. Don’t worry if this sounds tricky still, we’ll deal with this in more detail later.
  • Polymorphism and Abstraction: These are two key concepts of OOP that will be explained later when you’re ready for them.

Working with OOP

I can imagine this all sounds very abstract at this point, but before you know it, you’ll be creating classes and instantiating objects yourself. OOP helps to make code more maintainable, better structured, and reusable. These things really help to be able to make changes to your application, solve problems, and scale up when needed.

OOP is just one key feature of Java. Another key feature is that it’s a compiled language. Let’s make sure you understand what is meant by that now.

Compiled language

Java is a compiled programming language, which means that the source code you write must be transformed into a machine-readable format before it can be interpreted. This machine-readable format is called bytecode. This process is different from that of interpreted languages, where the source code is read, interpreted, and executed on the fly. During runtime, the computer interprets an interpreted language line by line. When a compiled language is running, the computer interprets the bytecode during runtime. We’ll dive deeper into the compilation process in just a bit when we are going to compile our own code. For now, let’s see what the benefits of compiled languages are.

Benefits of Java being a compiled language

Compiling code first requires an extra step, and it takes time in the beginning, but it brings advantages. First of all, the performance of compiled languages is typically better than interpreted languages. This is because the bytecode gets optimized for efficient execution on the target platform.

Another advantage of compilation is the early detection of syntax errors and certain other types of errors before the code is executed. This enables developers to identify and fix issues before deploying the application, reducing the likelihood of runtime errors.

Java code is turned into bytecode – a form of binary code - by the compiler. This bytecode is platform-independent. This means that it allows Java applications to run on different operating systems without modification. Platform independence is actually the key feature that we’re going to be discussing next.

Write once, run anywhere

Java’s Write Once, Run Anywhere (WORA) principle is another key feature. This used to set Java apart from many other programming languages, but now, this is rather common, and many competing languages also implemented this feature. This principle ensures that Java code can run on different platforms without requiring different versions of the Java code for each platform. This means that a Java program is not tied to any specific operating system or hardware architecture.

When you have different versions of the code for each platform, this means that you have to maintain all these versions of the code as well. Let’s say you have a code base for Linux, macOS, and Windows. When a new feature or a change is required, you need to add this to three places! You can imagine that WORA was a game-changer at the time Java came out. And it leads to an increased reach of your application – any device that can run Java applications can run yours.

Understanding the WORA elements

The WORA principle is made possible by bytecode and the Java Virtual Machine (JVM). Bytecode is the compiled Java program. The compiler turns the Java code into this bytecode, and this bytecode is platform-independent. It can run on any device that can run the bytecode executer.

This bytecode executer is called the JVM. Each platform (Windows, macOS, Linux, and so on) has its own JVM implementation, which is specifically designed to translate bytecode into native machine code for that platform. Since the bytecode remains the same across platforms, the JVM handles the differences between operating systems and hardware architectures. The WORA principle is explained in Figure 1.1.

Figure 1.1 – The WORA principle in a diagram

Figure 1.1 – The WORA principle in a diagram

You can see that the compiler creates bytecode and that this bytecode can be picked up by the JVM. The JVM is platform-specific and does the translation to the platform it’s on. There’s more that the JVM does for us, and that is automatic memory management. Let’s explore this next.

Automatic memory management

Another key feature that made Java great is its automatic memory management, which simplifies development and prevents common memory-related errors. Java handles memory allocation and garbage collection for you. The developer doesn’t need to take care of manually managing the memory.

Nowadays, this is the rule and not the exception. Most other modern languages have automatic memory management as well. However, it is important to know what automatic memory management means. The memory allocation and deallocation are done automatically. This actually leads to simplifying the code. There is no boilerplate code that just focuses on the allocation and deallocation of the memory. This also leads to fewer memory-related errors.

Let’s make sure you understand what is meant by memory allocation and deallocation.

Memory allocation

In code, you create variables. Sometimes, these variables are not simple values but complex objects with many data fields. When you create an object, this object needs to be stored somewhere in the memory of the device that it’s running on. This is called memory allocation. In Java, when you create an object, device memory is automatically allocated to store the object’s attributes and associated data. This is different from languages such as C and C++, where developers must manually allocate and deallocate memory. Java’s automatic memory allocation streamlines the development process and reduces the chances of memory leaks or dangling pointers, which can cause unexpected behavior or crashes. It also makes the code cleaner to read, since you don’t need to deal with any allocation or deallocation code.

Garbage collection

When a memory block is no longer used by the application, it needs to be deallocated. The process Java uses for this is called garbage collection. Garbage collection is the process of identifying and reclaiming memory that is no longer in use by a program. In Java, when an object is no longer accessible or needed, the garbage collector automatically frees up the memory occupied by the object. This process ensures that the memory is efficiently utilized and prevents memory leaks and the problems that come with it.

The JVM periodically runs the garbage collector to identify and clean up unreachable objects. Java’s garbage collection mechanism uses many different sophisticated algorithms to determine when an object is no longer needed.

Now that we’ve covered the basics, let’s move on to installing Java.

 

Installing Java

Before you can start writing and running Java programs, you’ll need to set up the JDK on your computer. The JDK contains essential tools and libraries required for Java development, such as the Java compiler, the JRE, and other useful utilities that help development.

We will guide you through the process of installing Java on Windows, macOS, and Linux, and we’ll give you some suggestions for when you don’t have access to either one of those. But before proceeding with the installation of Java, it’s a good idea to check whether it’s already installed on your system.

Checking whether Java is installed on your system

Java may have been pre-installed, or you may have installed it previously without realizing it. To check whether Java is installed, follow these simple steps. The first one depends on your operating system.

Step 1 – Open a terminal

For Windows, press the Windows key, type cmd, and press Enter to open the Command Prompt.

For macOS, press Command + Space to open the Spotlight search, type Terminal, and press Enter to open Terminal.

For Linux, open a Terminal window. The method for opening the Terminal window varies depending on your Linux distribution (for example, in Ubuntu, press Ctrl + Alt + T).

Step 2 – Check for the Java version

In the Command Prompt or Terminal window, type the following command and press Enter:

java -version

Step 3 – Interpret the response

If Java is installed, you will see the version information displayed. If not, the Command Prompt will display an error message, indicating that Java is not recognized or found.

If you find that Java is already installed on your system, make sure it’s version 21 or later to ensure compatibility with modern Java features. If it’s an older version or not installed, proceed with the installation process for your specific platform, as described in the following sections. If an older version is installed, you may want to uninstall this first to avoid having an unnecessarily complicated setup. You can install this the common way of uninstalling programs for your operating system.

In Figure 1.2 and Figure 1.6, you’ll see examples of the output you can expect when Java is installed.

Figure 1.2 – The macOS terminal output where Java 19 is installed

Figure 1.2 – The macOS terminal output where Java 19 is installed

Now, let’s see how to install Java on each operating system.

Installing Java on Windows

To install Java on a Windows operating system, follow these steps:

  1. Visit the Oracle Java SE Downloads page at https://www.oracle.com/java/technologies/downloads/. This software can be used for educational purposes for free, but requires a license in production. You can consider switching to OpenJDK to run programs in production without a license: https://openjdk.org/install/.
  2. Select the appropriate installer for your Windows operating system (for example, Windows x64 Installer).
  3. Download the installer by clicking on the file link.
  4. Run the downloaded installer (the .exe file) and follow the on-screen instructions to complete the installation.
  5. To add Java to the system’s PATH environment variable, search for Environment Variables in the Start menu and select Edit the system environment variables. You should see a screen similar to Figure 1.3.
Figure 1.3 – The System Properties window

Figure 1.3 – The System Properties window

  1. In the System Properties window, click on the Environment Variables… button. A screen like the one in Figure 1.4 will pop up.
  2. Under System variables, find the Path variable, select it, and click Edit. You can see an example of which one to select in the following Figure 1.4:
Figure 1.4 – The Environment Variables window

Figure 1.4 – The Environment Variables window

  1. Click New… and add the path to the bin folder of your Java installation (for example, C:\Program Files\Java\jdk-21\bin). In Figure 1.5, this has been done already.
Figure 1.5 – Adding the path to Java to the Path variable

Figure 1.5 – Adding the path to Java to the Path variable

  1. Click OK to save the changes and close the Environment Variables windows.
  2. Verify Java is installed by opening the Command Prompt (reopen it if you have it open already) and then typing the following:
    java -version
  3. The output should look as shown in Figure 1.6. However, your version should be 21 or higher to keep up with all the snippets in this book.

=

Figure 1.6 – Command Prompt after Java version check after installing Java

Installing Java on macOS

To install Java on a macOS operating system, follow these steps:

  1. Visit the Oracle Java SE Downloads page at https://www.oracle.com/java/technologies/javase-jdk16-downloads.html.
  2. Select the macOS installer (for example, macOS x64 Installer).
  3. Download the installer by clicking on the file link.
  4. Run the downloaded installer (the .dmg file) and follow the on-screen instructions to complete the installation.
  5. Java should be automatically added to your system’s PATH environment variable. To verify the installation, open the Terminal and run the following command:
    java -version
  6. You should see the version of Java you just installed, similar to Figure 1.2.

Installing Java on Linux

Installing on Linux can be a little bit tricky to explain in a few steps. Different Linux distributions require different installation steps. Here, we will see how to install Java on a Linux Ubuntu system:

  1. Open the Terminal and update your package repository by running the following command:
    sudo apt-get update
  2. Install the default JDK package by running the following command:
    sudo apt install default-jdk
  3. To verify the installation, run the java -version command. You should see the version of Java you just installed.
  4. If you need to set the JAVA_HOME environment variable (which you won’t need for working your way through this book but will need for doing more complex Java projects), you first need to determine the installation path by running the following command:
    sudo update-alternatives --config java
  5. Take note of the path displayed (for example, /usr/lib/jvm/java-19-openjdk-amd64/bin/java).
  6. Open the /etc/environment file in a text editor with root privileges:
    sudo nano /etc/environment
  7. Add the following line at the end of the file, replacing the path with the path you noted in Step 4 (excluding the /bin/java part):
    JAVA_HOME="/usr/lib/jvm/java-19-openjdk-amd64"
  8. Save and close the file. Then, run the following command to apply the changes:
    source /etc/environment

Now, Java should be installed and configured on your Linux operating system.

Running Java online

If you don’t have access to a computer with macOS, Linux, or Windows, there are online solutions out there. The free options are not perfect but, for example, the w3schools solution for trying Java in the browser is not bad at all. There are quite a few of these out there.

In order to work with multiple files there might be free tools out there, but most of them are paid. A currently free one that we would recommend is on replit.com. You can find it here: https://replit.com/languages/java.

You need to sign up, but you can work for free with multiple files and save them on your account. This is a good alternative if you would for example only have a tablet to follow along with this book.

Another option would be to use GitHub Codespaces: https://github.com/codespaces. They have the opportunity to enter a repository (for example the one we use for this book) and directly try the examples that are available in the repo and adjust them to try new things.

Having navigated through the installation of Java, it’s time to talk about compiling and running programs.

 

Writing our first program

Before diving into the process of compiling and running Java programs, let’s create a simple Java program using a basic text editor. This will help you understand the structure of a Java program and how to write and save a Java source code file. For this example, we will create a “Hello world!” program that will be used to demonstrate the process of compilation and execution.

Hello world

You may have heard of “Hello world!” programs. They are a common way to start learning a new programming language. It’s a simple program that prints the message "Hello world!" to the console. Writing this program will provide you with a very basic understanding of Java syntax, and it will help you to become familiar with the process of writing, compiling, and running Java code.

Steps to create the program

Alright, let’s start coding. Here are the steps:

  1. First, open a basic text editor on your computer. Notepad on Windows, TextEdit on macOS, or Gedit on Linux are suitable options.
  2. Write the following Java code in your text editor:
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello world!");
        }
    }
  3. Save the file as HelloWorld.java in a directory of your choice. Don’t forget the .java extension when saving the file. This indicates that the file contains Java source code. The code should not have .txt after .java. This happens sometimes in Windows, so make sure to not select the text file in the filetype dropdown.

TextEdit – file extension issues

The later versions of macOS have some issues with TextEdit. You can’t save it as a Java file by default. In order to enable this, you need to go to Format | Make Plain Text and select UTF-8.

After this, you can save it as a .java file. You may still run into encoding errors; the problem is with the encoding, and fixing it might be a lot of effort missing the goal of this exercise. It might be better to download Notepad++, TextPad, or Sublime for this part. Or go ahead and download the HelloWorld.java file from our GitHub repository.

Understanding the program

Let’s have a look at the code we just used. First of all, be aware that this is case-sensitive. That means that when you look at the code, most things will not work as you expect if you mix up lowercase and uppercase.

First, we created a class named HelloWorld with a main method. We’ll cover classes and methods in a lot more detail, of course. But a class is the fundamental building block of Java applications, and it can contain methods. Methods can be executed to do things – things being executing statements.

The main method is a special method. It is the entry point of our Java program and contains the code that will be executed when the program is run. The line with System.out.println("Hello world!"); writes the Hello world! message to the console. Please note, that println stands for print line, so it uses a lowercase L and not an uppercase i.

With the HelloWorld.java file saved, we are now ready to move on to the next section, where we will learn how to compile and run the Java program using the command line and an IDE.

 

Compiling and running Java programs

Now that we have our first program written, let’s discuss how we can compile and run it. We will cover the basics of the compilation process, the role of the JVM, and how to compile and run Java code using the command line and an IDE.

Understanding the compilation process

The source code is written in a human-readable format using the Java programming language. Or at least, we hope that this is your opinion after this book. Before the code can be executed, it must be transformed into a format that the computer can understand. You already know that Java is a compiled language and that this process is called compilation.

During compilation, the Java compiler (javac) converts the source code (.java files) into bytecode (.class files). Once the bytecode is generated, it can be executed by the JVM. We have already learned that the JVM is the bytecode executer and that every platform has its own custom JVM enabling the WORA feature of Java.

Compiling the code with javac on the command line

To compile a Java program using the command line, follow these steps:

  1. Open a terminal (Command Prompt on Windows, Terminal on macOS or Linux).
  2. Navigate to the directory containing your Java source code file (for example, the directory of your previously created HelloWorld.java file). In case you don’t know how to do that, this can be done with the cd command, which stands for change directory. For example, if I’m in a directory called documents and I want to step into the subfolder called java programs, I’d run the cd "java programs" command. The quotes are only needed when there are spaces in the directory name. It’s beyond the scope of this book to explain how to change directories for any platform. There are many excellent explanations for every platform on how to navigate the folder structure using the command line on the internet.
  3. Once you’re in the folder containing the Java file, enter the following command to compile the Java source code:
    javac HelloWorld.java

    If the compilation is successful, a new file with the same name but a .class extension (for example, HelloWorld.class) will be created in the same directory. This file contains the bytecode that can be executed by the JVM.

Let’s see how we can run this compiled code.

Running the compiled code with Java on the command line

To run the compiled Java program, follow these steps:

  1. In the terminal, make sure you are still in the directory containing the .class file.
  2. Enter the following command to execute the bytecode:
    java HelloWorld

The JVM will load and run the bytecode, and you should see the output of your program. In this case, the output will be as follows:

Hello world!

It’s pretty cool that we can write Java in Notepad and run it on the command line, but the life of a modern-day Java developer is a lot nicer. Let’s add IDEs to the mix and see this for ourselves.

 

Working with an IDE

Creating files in text editors is a little old-fashioned. Of course, you can still do it this way – it’s actually an excellent way of becoming an amazing programmer, but it’s also a very frustrating way. There are tools available to do quite a bit of the heavy work for us and to assist us while writing our code. These tools are called IDEs.

What is an IDE?

An IDE is a software application that comes with everything you need to write, compile, run, and test your code. Using an IDE can make it easier to develop all sorts of programs. Not only that but also debugging and managing your code is easier. Comparatively, you can think of an IDE somewhat like Microsoft Office Word for me as I write this book. While I could have written it using Notepad, using Word provides significant advantages. It assists in checking for spelling errors and allows me to easily add and visualize layouts, among other helpful features. This analogy paints a picture of how an IDE doesn’t just provide a platform to write code but also offers a suite of tools to streamline and enhance your coding experience.

Choosing an IDE

When it comes to Java development, there are several IDEs available, each with its own set of features and capabilities. In this section, we will discuss the factors to consider when choosing an IDE and help you set up some popular Java IDEs. Throughout this book, we’ll be working with IntelliJ. Alternatives that are also great would be VS Code and Eclipse.

Factors to consider when choosing an IDE

Most modern IDEs have features such as code completion, debugging, version control integration, and support for third-party tools and frameworks. Some of them have better versions of these than others. Compare and contrast what you prefer when choosing or switching IDEs.

Some IDEs require a heavier system to run on than others. For example, VS Code is rather lightweight and IntelliJ is rather heavy. Also, VS Code can be used for many languages, including Java. It is uncommon to do a lot of other things with IntelliJ rather than Java. Choose an IDE that provides a balance between features and performance, especially if you have limited system resources.

And of course, it’s possible that the IDE you’d prefer is not available for the platform you’re using. Make sure that it’s available and stable for your system.

Lastly, and very importantly, think about the costs. Some IDEs are free and others require a paid license. Luckily, many of the ones that require a paid license have a free edition for non-commercial use. So, make sure to also consider your budget and the licensing you need when choosing an IDE.

In the following subsections, we’ll walk you through the steps of setting up the three (currently) most common IDEs for Java development:

  • IntelliJ
  • Eclipse
  • Visual Studio Code

Note

We’ll be working with IntelliJ for the rest of this book.

Setting up IntelliJ

So, let’s start with that one. IntelliJ IDEA is a popular Java IDE that was developed by JetBrains. It offers both a free Community Edition and a paid Ultimate Edition. It provides a wide range of features, including intelligent code completion, debugging tools, version control integration, and support for various Java frameworks.

Here are the steps for installing IntelliJ:

  1. Visit the IntelliJ IDEA download page at https://www.jetbrains.com/idea/download/.
  2. Choose the edition you prefer: the free Community Edition or the paid Ultimate Edition. For beginners, the Community Edition is truly great already.
  3. Download the installer for your operating system (Windows, macOS, or Linux).
  4. Run the installer and follow the instructions to complete the installation.
  5. Launch IntelliJ IDEA. If you’re using the Ultimate Edition, you may need to enter your JetBrains account credentials or a license key.
  6. On the Welcome screen, you can create a new project, import an existing project, or explore the available tutorials and documentation.

Setting up Eclipse

Eclipse is a free, open source Java IDE that is widely used in the Java community. It has been around for a really long time already and quite a lot of companies work with it still. It offers a variety of features, just like IntelliJ. Eclipse can be customized to suit your needs, but its interface may be less intuitive than other IDEs.

To set up Eclipse, follow these steps:

  1. Visit the Eclipse download page at https://www.eclipse.org/downloads/.
  2. Download the Eclipse installer for your operating system (Windows, macOS, or Linux).
  3. Run the installer and select Eclipse IDE for Java Developers from the list of available packages.
  4. Choose an installation folder and follow the instructions to complete the installation.
  5. Launch Eclipse and select a workspace directory. This is where your projects and settings will be stored.
  6. On the Welcome screen, you can create a new Java project, import an existing project, or explore the available tutorials and documentation.

Setting up Visual Studio Code

Visual Studio Code, often referred to as VS Code, is a lightweight, free, and open source code editor developed by Microsoft. It’s incredibly popular for all sorts of tasks because it supports a wide range of programming languages. It is a popular choice for developers who prefer a more minimalist and fast-performing environment. All sorts of additions can be added with the use of extensions.

Here are the steps for installing VS Code and preparing it for Java development:

  1. Visit the Visual Studio Code download page at https://code.visualstudio.com/download.
  2. Download the installer for your operating system (Windows, macOS, or Linux).
  3. Run the installer and follow the on-screen instructions to complete the installation.
  4. Launch Visual Studio Code.
  5. Open the Extensions view by clicking on the Extensions icon (four squares) on the left side of the window.
  6. Search for Java Extension Pack in the Extensions Marketplace and click the Install button. This extension pack includes various extensions for Java development, such as Language Support for Java (TM) by Red Hat, Debugger for Java, and Maven for Java.
  7. With the Java Extension Pack installed, you can now create or import Java projects. If it doesn’t load directly, you may need to reopen VS Code.

Now that you’ve set up an IDE, let’s create and run a program with it.

 

Creating and running a program with an IDE

Working with an IDE such as IntelliJ as compared to working with a plain text editor is a breeze. We’re now going to guide you through creating, running, and debugging a program with the use of IntelliJ. We’ll create the same program as we did when we were using the text editor.

Creating a program in an IDE

When you use an IDE to type code, you’ll see that it helps you to complete your code constantly. This is considered very helpful by most people, and we hope you’ll enjoy this feature too.

In order to get started with IntelliJ, we first need to create a project. Here are the steps for creating our Hello World program again:

  1. Launch IntelliJ IDEA and click on New Project from the Welcome screen or go to File | New | Project.
Figure 1.7 – Initial screen of IntelliJ

Figure 1.7 – Initial screen of IntelliJ

  1. Name the project HelloWorld.
  2. Select Java for the language and make sure that the correct project SDK is selected. Click Next.
  3. Don’t tick the Create Git repository box and don’t tick the Add sample code box.
  4. Click Create to create the project.
Figure 1.8 – Wizard to create a new project

Figure 1.8 – Wizard to create a new project

  1. Once the project is created, expand the src folder in the Project view on the left. If there is no other folder underneath it, right-click on the src folder and select New | Java Class. If there is another folder underneath it, there is probably a main folder with a Java folder in there. Right-click on the Java folder and select New | Java Class. If it’s called something differently, just right-click on the blue folder.
Figure 1.9 – Create a new Java Class

Figure 1.9 – Create a new Java Class

  1. Name the new class HelloWorld and click OK. IntelliJ will create a new .java file with the class definition.
Figure 1.10 – Call the class ”HelloWorld”

Figure 1.10 – Call the class ”HelloWorld”

  1. In the HelloWorld class, write our main method:
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello world!");
        }
    }
Figure 1.11 – Code in HelloWorld.java

Figure 1.11 – Code in HelloWorld.java

Now that we’ve written our first program, make sure that it is saved. By default, IntelliJ automatically saves our files. Let’s see whether we can run the program as well.

Running your program

Admittedly, we had to take a few extra steps to create our program. We had to create a project first. The good news is, running the program is easier! Here’s how to do it:

  1. If you haven’t done so, make sure your changes are saved by pressing Ctrl + S (Windows/Linux) or Cmd + S (macOS). By default, auto-save is enabled.
  2. To run the program, right-click anywhere in the HelloWorld class and select Run 'HelloWorld.main()'. Alternatively, you can click the green triangle icon next to the main method and select Run 'HelloWorld.main()'. IntelliJ will compile and run the program.
Figure 1.12 – Running the program

Figure 1.12 – Running the program

  1. Verify that the output of the program, "Hello world!", is displayed in the Run tool window at the bottom of the screen.
Figure 1.13 – Output of the program

Figure 1.13 – Output of the program

Saved and unsaved files

In most IDEs, you can tell whether a file is saved or not by looking at the tab of the open file. It has a dot or an asterisk next to it if it isn’t saved. The dot is missing if it has been saved.

Debugging a program

Our program is quite easy right now, but we may want to step through our program line by line. We can do that by debugging the program. Let’s give our file a little extra content for debugging. This way we can see how to inspect variables, understand the execution flow, and, this way, find the flaws in our code:

  1. Update the HelloWorld.java file with the following code:
    public class HelloWorld {
        public static void main(String[] args) {
            String greeting = "Hello, World!";
            System.out.println(greeting);
            int number = 5;
            int doubled = doubleNumber(number);
            System.out.println("The doubled number is: " +
              doubled);
        }
        public static int doubleNumber(int input) {
            return input * 2;
        }
    }
  2. In this updated version of the program, we added a new method called doubleNumber, which takes an integer as input and returns its double. In the main method, we call this method and print the result. Don’t worry if you don’t fully get this – we just want to show you how you can step through your code.
  3. Save your changes by pressing Ctrl + S (Windows/Linux) or Cmd + S (macOS).

    Now, let’s debug the updated program.

  4. Set a breakpoint on the line you want to pause the execution at by clicking in the gutter area next to the line number in the editor. A red dot will appear, indicating a breakpoint. For example, set a breakpoint at the line int doubled = doubleNumber(number);. An example is shown in Figure 1.7.
Figure 1.14 – Adding a breakpoint on line 7

Figure 1.14 – Adding a breakpoint on line 7

  1. Start the debugger by right-clicking in the HelloWorld class and selecting Debug 'HelloWorld.main()' or you can click the green play icon next to the main method and select the debug option. IntelliJ will compile and start the program in debug mode.
  2. When the line with the breakpoint is going to be executed, the program will pause. During the pause, you can use the Debug tool window, which will appear at the bottom of the screen. Here, you can view the state of the program, including the values of local variables and fields. An example is shown in Figure 1.8.
Figure 1.15 – Debug tool window in IntelliJ. The intent of this screenshot is to show the layout and text readability is not required.

Figure 1.15 – Debug tool window in IntelliJ. The intent of this screenshot is to show the layout and text readability is not required.

  1. Use the step controls in the Debug tool window to step through the code (blue arrow with the angle in Figure 1.8), step into the method that is being called (blue arrow down), or continue the execution (green arrow on the left in Figure 1.8).

By following these steps, you can debug Java programs using IntelliJ IDEA and step through the code to see what is happening. This is something that will come in handy to understand what is going on in your code. This process will be similar in other Java IDEs, although the specific steps and interface elements may vary.

 

Exercises

And that’s all theory for this chapter! So, roll up those sleeves, and let’s dive into your first day at Mesozoic Eden. Welcome aboard! Mesozoic Eden is a famous zoo where dinosaurs live that have been brought to live with high end genetic manipulation techniques. Here are some exercises for you to test your knowledge so far:

  1. Your first task involves welcoming our guests. Modify the following code snippet so that it outputs "Welcome to Mesozoic Eden":
    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello world");
        }
    }
  2. Complete the following programs by filling out the blanks so that it prints out your name and the position you want to have in Mesozoic Eden 5 years from now:
    public class Main {
        public static void main(String[] args) {
            __________________________;
            String position = "Park Manager";
            System.out.println("My name is " + name + "
              and I want to be a " ______ " in Mesozoic
                Eden.");
        }
    }
  3. We’ve received some questions about opening hours. Complete the following program so that it prints the park’s opening and closing hours:
    public class Main {
        public static void main(String[] args) {
            String openingHours = "08:00";
            String closingHours = "20:00";
        }
    }
  4. Create a Java project with a package named dinosaur. You can create a package by right-clicking on the src/main/java folder, selecting “new” and choosing “package”.
  5. Modify the code from exercise 1 so that it prints out "Welcome, [YourName] to Mesozoic Eden!", where [YourName] is replaced by, surprise surprise, your name. Bonus: try to create a separate String variable as shown in the second and third exercises.
  6. Some guests reported feeling unsafe near the T-Rex. Let’s solve this by adding another System.out.println to the program of exercise 5. It should print the phrase "Mesozoic Eden is safe and secure." after the welcome message.
 

Project

Create a program that simulates a sign at the entrance of Mesozoic Eden. The sign is simulated by printing output to the console. The sign should display a welcome message, the opening and closing hours, and a short safety message.

 

Summary

You’ve made it through the first chapter! And we’ve done a lot already. We kicked off by exploring Java’s key features, such as its OOP approach, the (once unique) WORA principle, its compiled nature, and the super-helpful automatic memory management. These features make Java an incredibly versatile and powerful language – a great choice for different programming tasks, such as web development, desktop apps, mobile apps, and so much more!

Next, we walked you through the process of installing Java on various platforms: Windows, macOS, and Linux. We also discussed how to check whether Java is already installed on your system. After this part, you can be sure that you have all the essential tools to kick off your Java programming adventure.

After you had Java all setup, we demystified the compilation process and introduced you to the JVM, a vital component of the Java ecosystem that enables the portability of Java code. We then demonstrated how to compile and run Java code using the javac and java command-line tools. These tools lay the groundwork for working with Java programs at their core.

Of course, using the command line for this is great. But nowadays, we more often work with an IDE, and we can just press a button to do all this. So, we mentioned several advantages and nice features of working with an IDE, such as code completion, debugging, and project management. We discussed the factors to weigh up when choosing an IDE and provided guidance on setting up popular IDEs such as IntelliJ IDEA, Eclipse, and VS Code. In this book, we’ll be using IntelliJ throughout for the examples.

After covering the essentials of IDEs, we delved into creating and running a Java program using an IDE. We explained the structure of a typical Java program and guided you, step by step, through the process of creating, running, and debugging your very first Java program.

After this, you were ready for the first hands-on project. And now you’re here! All set and ready to take the next step on your Java journey. This next step will be working with variables and primitive data types. Good luck!

About the Authors
  • Dr. Seán Kennedy

    Seán Kennedy is a university lecturer with over 20 years of experience in teaching. He has a PhD in IT and is Oracle-certified in Java at the Professional level (OCP). In his daily work, he teaches Java on a bespoke master's program for a highly regarded software company. He has a YouTube channel called Let's Get Certified that teaches Java at all levels and prepares candidates for Java certification. He also has similar courses on Udemy. Outside of work, he enjoys tennis, walking, nature, reading, and TV.

    Browse publications by this author
  • Maaike van Putten

    Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.

    Browse publications by this author
Latest Reviews (3 reviews total)
Learn Java with Projects
Unlock this book and the full library FREE for 7 days
Start now