Chapter 1 - Java for Beginners Course

Class Example - Defining a class

The idea with this example is to start introducing the syntax used in the Java language.

Don’t worry if there are things that aren’t clear at this stage, we’ll cover these concepts and others in more detail as we go along.

Let’s create a new file called Airplane.java with the following code:

/**
 * Basic example of a class representing an Airplane.
 */
public class Airplane {
    private String manufacturer;

    private int numberOfSeats;

    private boolean landed;

    private boolean gearDeployed;

    public void setManufacturer(String newManufacturer) {
        manufacturer = newManufacturer;
    }

    public void setNumberOfSeats(int newNumberOfSeats) {
        numberOfSeats = newNumberOfSeats;
    }

    public void takeOff() {
        landed = false;
    }

    public void land() {
        landed = true;
    }

    public void deployLandingGear() {
        gearDeployed = true;
    }

    public void retractLandingGear() {
        gearDeployed = false;
    }

    public void printDetails() {
        System.out.println("manufacturer=" + manufacturer + ", numberOfSeats=" + numberOfSeats + ", landed=" + landed + ", gearDeployed=" + gearDeployed);
    }

}

Breaking down the example above:

Example of Code Comments

/**
 * Basic example of a class representing an Airplane.
 */

These are code comments and are ignored by the Java compiler. They are used to provide explanations about the code that follows. Their purpose is to make the code easier to understand to other developers reading the code. You’ll see 3 main types of comments in Java:

  1. The one shown in the example above, a multi-line comment delimited at the beginning by /** (note the double star) and at the end by */. This is also known as a Javadoc comment that is also used by tools to generate software documentation. For example, the Java API documentation is generated based on the Javadocs present in the Java code.

  2. Regular (non-Javadoc) multi-line comments, that are delimited by a /* (single star) and a */, for example:

    /*
     * This is an example comment.
     */
  3. Single line comments, that are specified by a double forward slash //, for example, // This is a comment.

Note that in code examples/demos/tutorials, it is common to find a //…​ comment inside the example code. This is used as a way to indicate that additional code can be there, but it isn’t shown for simplicity.

Example of a Class declaration

public class Airplane {
	// ...
}

In Java, class declarations in their most basic form are specified by the keyword class and the name of the class we want to declare. For example: class Airplane.

The public at the beginning is to show an example of an access modifier that declares that this class can be accessed by all other classes. We’ll cover access modifiers in more detail in a later section.

The contents of the class are delimited by the braces { …​ }, which in Java we call a code block.

Other details about classes can be specified and we’ll cover this in a later section.

Examples of Field declarations

private String manufacturer;

private int numberOfSeats;

private boolean landed;

private boolean gearDeployed;

The fields represent the state of the class. In this case we have 4 different fields, all of them marked as private which means they can only be accessed by the Airplane class.

Here you can start seeing the pattern/syntax in Java, where the name of each field (for example numberOfSeats) is preceded by its type (for example int) that specifies the type of data the field will store. As mentioned before, fields are a type of variable in Java, and as such they hold a value.

For the purpose of this example, the types we are using are:

  1. The String type, that is used to store sequences of characters (or text), for example: "Boeing". Sequences of characters, or Strings, are delimited by double quotes as you’ll see in further examples.

  2. The int type is used to store integer numbers, for example: 250.

  3. The boolean type is used to store a true or false value.

Examples of Method declarations

public void setManufacturer(String newManufacturer) {
    manufacturer = newManufacturer;
}

public void setNumberOfSeats(int newNumberOfSeats) {
    numberOfSeats = newNumberOfSeats;
}

public void takeOff() {
    landed = false;
}

public void land() {
    landed = true;
}

// other methods omitted

The methods represent the behavior of the class. Here we are showing 4 different methods, all of them marked as public indicating that they can be accessed by all other classes.

We’ll cover method declarations in more detail in a later section, but we can start seeing examples of the Java syntax for declaring a method:

public void takeOff() { ... }

The name of the method, in this case takeOff is preceded by the data type it will return. The void type denotes that the method doesn’t return any value. The method can have additional modifiers which we’ll cover later.

Following the method name, we define the method inputs inside a parenthesis. In the case of the takeOff method, there are no inputs. In the case of the setManufacturer method, there is one input String newManufacturer. These inputs are called parameters.

The body of the method, as in, the code that will be executed, is also defined by a code block delimited by braces ({ …​ }).

All the methods in our example have a single line, but they can have multiple lines of code as well. In the case of the takeOff method, the body of the method is landed = false;.

Example of printing data to the console

You’ll notice that we have a method called printDetails that does the following:

System.out.println("manufacturer=" + manufacturer + ", numberOfSeats=" + numberOfSeats + ", landed=" + landed + ", gearDeployed=" + gearDeployed);

We’ll explain this in more detail later on, but for the time being please note that we can use the System.out.println method to print out details into the console.

For this beginners course we’ll be using this in different places to illustrate certain examples and help visualize what our application’s state is.

In this website, code examples that output text to the console will typically be followed by an Output section where we show what the application’s output would be.

A note on the assignment (=) operator

Some of the examples above use an operator that we haven’t formally introduced and that will be covered again in Chapter 2. However, as we’ll be using it in several of the examples in this chapter it’s good to provide an introduction.

The assignment operator, represented by an equals (=) sign in Java, indicates that the variable on the left will take the value that we provide on the right hand side of the = operator.

For example, in the Airplane class we have this statement in the land() method:

landed = true;

Here, we are assigning a value of true to the landed field, and this value will be stored in the field until another assignment occurs.

Keywords in Java

Java has a set of reserved words that have a defined meaning in the language and that we’ll be introducing throughout the course. In the Airplane class above we’ve already covered some of them, for example, class, private and public.

You cannot use a keyword as the name of your classes/fields/methods. For example, you cannot have a variable called public as it is reserved internally by the language.

In most IDEs, the keywords are highlighted in a different color.
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations