Java Primer I

Java Primer I: Making sense of Java syntax, objects, classes and methods

Contents

  • The Java Type System
  • Variables: Declaration and Assignment
  • Objects
  • Classes
  • Methods
  • Access Modifiers

All the videos in this tutorial are also available in a YouTube playlist.

Goals

 

  • Explain key Java concepts for people with little or no programming experience.
  • Show the Java syntax.
  • Introduce programming jargon.
  • Keep the theory as brief as possible, since the best way of learning is by making apps.

 

 The Java Type System

 

 

In essence programs are about manipulating data, whether they add up two numbers or look up a word in a dictionary, or simulate the physics of a black hole. Java enforces a set of rules (the type system) to distinguish between different kinds of data. Each value in Java must have a type.

Think of a type as a property which defines what category our data belongs to. To comply with the rules, Java code must distinguish between integers (whole numbers), a piece of text (e.g., the word “Hello”), and other data. Here are some examples of common types:

Type Set of Values Example
int integers (32-bit) 2001, -8, 15
double floating point numbers (64-bit) -4.14, 6.0002
boolean The value true or false true, false
String sequences of characters “ABC”, “All your base”

 

Declaration and Assignment Statements

 

In a program we’ll want to keep track of data and do calculations. For this we’ll need variables. Variables act as containers that can temporarily store the data. Just like the data itself, the container also has a type. In a declaration we specify a variable’s type and its name. A declaration looks like this:

double myValue;

In an assignment we are placing a value into our variable. The syntax for assignment uses the equals sign (=) like this:

myValue = 4.5;

Of course we can combine declaration and assignment like so:

String bookTitle = “War and Peace”;

Note how the type of data matches the type of the container. Variables can also be used to manipulate data.

double product = myValue*2;

The variable with the name product now holds the value of 9 since we assigned 4.5 to myValue earlier. We can also manipulate Strings or pieces of text.

String main = “Fish “;

String side = “ & Chips”;

String meal = main + side; // Comment: meal holds the value “Fish & Chips”

The grey text is a comment since it is preceded by two slashes (//). We use comments to make helpful notes in the Java code. None of the text in a comment will be executed.

Objects

 

 

Conceptually, both iPhone and Android apps are made of a collection objects that send messages to each other. This is where things get a bit abstract, but also interesting, so bear with me.

Objects are combinations of “data” and “procedures”. Programmers group related functionality into objects so that each object handles a specific part of the app. For example, some objects are responsible for drawing things on screen while other objects are responsible for fetching data from the database.

If you had the programmatic equivalent of a car, then the car object’s “data” or it’s “properties” would be information it contains like top speed, horsepower, or number of doors. The “procedures” or “behaviour” on the other hand are the things that the car does, like drive, indicate, or play the radio.

In Android, we have Button objects. The Button properties would be things like visibility, colour, position. While the Button behaviour would be things like recognising taps and clicks.

Creating an object

An object is created from a template – a class. Think of a class as the blueprint for an object. Our Car class, would be the blueprint which explains how to assemble a car object and what a car object can do.

Creating a new car object is a lot easier than building one in a factory. Using a combined declaration and assignment statement, we create a new object using the new keyword.

Car myFirstCar = new Car();

Again, we have to comply with the Java type system. On the left of the ‘=’ we have the type followed by the variable name (myFristCar). On the right of the ‘=’ we create a new instance of the Car class (a brand new car object) by calling the Car class’ constructor. The constructor gives us a car object which we are assigning to the myFirstCar variable.

 

Classes

 

Let’s take a look inside the Car class to see where the constructor comes from, what properties the car has, and what the car can do. The class is declared with the class keyword.

public class Car {

private int maxSpeed;    // Member variable holds info about the Car

private int nrOfSeats;

       // Next up is the constructor

public Car () {

maxSpeed = 120;

nrOfSeats = 4;

}  // This brace ends the constructor

}     // This last curly brace is the end of the class

The Car class has two variables: the maximum speed the car can travel and the number of seats it has. These are called member variables because the variables are part of the class and capture the properties of the car.

We discuss the keywords private and public at the end of the section. First, let’s focus on how object creation happens.

 

Constructors

 

Constructors are the part of our class template which is used to create (instantiate) new objects. A constructor always has the same name as the class. In the example above the constructor is:

public Car () {

maxSpeed = 120;

nrOfSeats = 4;

}

This constructor assigns the value 4 to the member variable nrOfSeats and the value 120 to maxSpeed. However, this is not very interesting, since we cannot make different types of cars. We want to be able to specify the number of seats and the speed of the car when we create one. For this we need to pass information into the constructor in the form of arguments. Imagine the constructor looked like this:

public Car (int speed, int seats) {

maxSpeed = speed;

nrOfSeats = seats;

}

This constructor takes two integer arguments: speed and seats. These values are promptly assigned to the maxSpeed and nrOfSeats member variables. Thus we can use our template to make two very different cars:

Car ferrari = new Car (250, 2);

Car bus = new Car (80, 50);

With the ferrari car object, we invoke the constructor and give the Ferrari a speed of 250 and 2 seats, while the bus car object has a speed of 80 and 50 seats.

 

Methods

 

Remember how we said objects were a combination of data and procedures (i.e., behaviour)? At the moment our Car doesn’t do anything because we have not specified any behaviour in the class. For this we need to write a method. A method is a group of statements inside a block of code surrounded by {…}.

Method Declaration

Here is how we declare a method in our Car class:

public class Car {

private int maxSpeed;

private int nrOfSeats;

// The constructor:

public Car (int speed, int seats) {

maxSpeed = speed;

nrOfSeats = seats;

}

// The method:

public void drive() {

System.out.println(“Cruisin in my Pinto, I see homies as I pass …”);

}  

}     // End of the Car class

Our drive() method will print the “Cruisin in my Pinto…” line to the console. There are a couple of things to note here.

  • The entire drive() method is inside the class declaration, i.e., within the last curly bracket (“}”) on the far left.
  • The method has a return type. Methods are often called to get something back. Say we have a method that multiplies two numbers. We want this method to do the calculation and then return the product. In Java each method needs to declare explicitly what type of thing it returns, even if that is nothing (which is the case here). The keyword void declares that our method is not returning anything.
  • See how the constructor above looks similar to a method declaration? The difference is that constructor’s name (Car) is the same as the corresponding class’ name (Car), and that the constructor declaration has no return type (not even void).

Calling Methods

Now that our Car class has a method, we can call this method in other parts of our program. To call a method all we need is a Car object and use the dot operator (.). Since we created a ferrari object earlier, we can call our drive() method on it:

ferrari.drive();

and read the lyrics of an ageing punk band on our console.

 

Methods with Parameters

Let’s up the ante to keep track of the gear our car is in. First, we change our class to add a new member variable, currentGear. Second, in the constructor, we set the currentGear to 1 so that all new Car objects start out in first gear (because everyone is parked on a hill or something).

public class Car {

private int maxSpeed;

private int nrOfSeats;

private int currentGear;

 

public Car (int speed, int seats) {

maxSpeed = speed;

nrOfSeats = seats;

currentGear = 1;

}

public void drive() {

System.out.println(“Cruisin in my Pinto, I see homies as I pass …”);

}

// Two new methods for the Car class

public void shift (int newGear) {

// The statements between the {…} are called the method “body”

currentGear = newGear;

}

public int whichGear() {

return currentGear;

}  // End of the whichGear() method

}  // End of the Car class

Here we added two methods: shift(…) and whichGear().

  1. The shift(…) method takes, as its input (i.e., argument) an integer (int) value. Within the body of the method (that is, between the curly braces) that argument is known by the variable name newGear and we are setting the currentGear member variable equal to the new integer value supplied. Since this method does not give any information back, its return type is void.
  2. The whichGear() method has the return type of int. This is the same type as the variable currentGear, which also has the type int.

So, back to driving our ferrari. To shift up and straight into 5th gear, we pass in 5 as an argument into the shift method:

ferrari.shift(5);

currentGear now holds the value 5. If we write:

ferrari.shift(99);

We can subsequently assign the integer value 99 to a new variable as follows:

int bottlesOfBeerOnTheWall = ferrari.whichGear();

 

Access Modifiers

 

So what were these public and private keywords lurking around in our code? public and private are called access modifiers. These determine “visibility” and whether other classes can use a particular field or method.

The private fields and methods are the things we want to hide. The public fields and methods are the bits that we want other parts of the app to interact with.
Say our car does things that are internal to it, like using ABS or traction control during braking. We don’t want other code to tell our car when to use ABS or otherwise interfere, so we declare this method as private.

public class Car {

public void brake() {

// some code here

useABS();

}

private void useABS() {

// more fancy proprietary code here

}

}

This means we can call useABS() within the Car class like inside the brake() method, but not outside of it. If we have a Car object in another class, we can call that object’s public methods, but we cannot call the private methods. Imagine we had a class called Roadtrip:

public class Roadtrip {

Car ferrari = new Car(250, 2); // Creating a car object

ferrari.brake(); // This is OK because the method is public

ferrari.useABS(); // NOT OK because useABS() is private. Error!

}

Why are access modifiers important? It has to do with how programmers group functionality into classes and objects. Remember how apps are really a collection of classes? All the classes are “connected” with each other through their public methods. We don’t want to “link” the class that’s responsible for drawing things on screen to the intricacies of another class’ methods for fetching data. We can ensure this doesn’t happen by making those methods private. This way if we have to go back and change any private methods or fields we know for sure that we won’t be affecting other parts of the program (because nothing is linked to those methods/fields).

We will encounter three access modifiers in Java:

  • If declared private, visibility is restricted to the class only. It is the safest kind of declaration and the one you’d want to be associated with the variables holding your credit card information.
  • If declared public, visibility is unrestricted
  • If declared protected, visibility is restricted to the package (i.e., groups of related classes).

 

Summary

 

  • Objects are combinations of data and procedures.
  • A class is a blueprint for an object.
  • The constructor is invoked to create a new object.
  • A method is a group of statements that can be referred to by name.
  • Methods must specify a return type. If the method does not return anything, the return type is void.
  • private methods and variables are only visible inside the same class.

 

Read part two of this tutorial here.