On this page:
Overview
1.1 Programs (in this course)
1.2 More Fields, and Java as a Calculator
1.2.1 Defining More Fields
1.2.2 Java as a Calculator
1.2.3 Not Quite Math
1.3 Syntax
6.8

Lecture 1: Java: The Basics

There are no related files for lecture

Overview

Note: throughout these lecture notes, you’ll see the following:

Do Now!

A Do Now! exercise is strongly recommended for you to do now, without reading ahead in the lecture notes. You should think through the question being asked, and then see if your understanding matches the concepts the lecture notes suggest.

Exercise

An Exercise is strongly recommended for you to do, now or when finished reading these notes. These exercises may suggest further applications of the concepts in the lecture notes.

A useful way to read these notes is with a terminal and editor open, so you can try out the given examples. Of course, it’s still good to read without having the ability to run Java close at hand, but if you can try out the examples as you go, you’ll get more out of the experience.

1.1 Programs (in this course)

In this course, we’ll write, test, and run programs in a language called Java. What that means (in very blunt terms) is that we’ll put a bunch of text into a file with the extension .java, and use tools to run it and check the output. We’re going to use a particular tool called the Tester library to run our programs. For now, most of the details are hidden from you, you’ll just follow two steps to write and run your program:

The instructions in the first lab will get you set up to do this, so you can run the programs in these notes.

Here’s our first simple program:

class ExamplesLecture1 {
int theNumberFive = 5;
}

The first line, run ExamplesLecture1, tells the tester to load up the file you specify with Java and run it.

When we save it in a file called ExamplesLecture1, and run it, we see something like this:

$ run ExamplesLec

Tester Prima v.2.3

-----------------------------------

Tests defined in the class: ExamplesLecture1:

---------------------------

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theNumberFive = 5

 )

---------------

No test methods found.

If you’ve programmed in Java before and are wondering where main went, don’t fret, you’ll see it soon enough. Around halfway through the course, we’ll learn how to make more standalone applications, and this will include running programs from main.

That’s a fair amount of output! We’ll explain it piece by piece as lectures go on. For now, just focus on this part:

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theNumberFive = 5

 )

This fragment of the output is printing back to us, in a slightly different format, the information we wrote in the original program. In particular, this output is saying that a single ExamplesLecture1 object was created, and it has a single field, which we can refer to with this.theNumberFive, whose value is 5. We’ll define the terms object and field in detail later, and see many more examples of their use.

1.2 More Fields, and Java as a Calculator

The first example we wrote was quite simple. Let’s build on it.

1.2.1 Defining More Fields

One way we can extend the program from before is by adding another field:

class ExamplesLecture1 {
int theNumberFive = 5;
int theNumberEight = 8;
}

Running the program (again using the run command), produces this unsurprising output:

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theNumberFive = 5

  this.theNumberEight = 8)

Indeed, we can declare an arbitrary number of fields, and freely choose their names and values; here are a few more examples:

class ExamplesLecture1 {
int theNumberFive = 5;
int theNumberEight = 8;
int theNumberTwo = 4;
int x = 58;
int y = 73;
}

Note the field theNumberTwo above – its name doesn’t match the value very well! We can pick any name for the fields we choose, and Java doesn’t know if the name is sensible for the value it stores or not. That is to say, Java doesn’t try to give meaning to our variable names; that’s up to the programmer. We say that the field name theNumberTwo is particularly bad style, since it makes the human-facing part of the program—the field name—very misleading when considering the program’s behavior. All of the examples above are somewhat contrived, since this is the first program we’re writing, but the other fields at least aren’t lying.

1.2.2 Java as a Calculator

Of course, just naming a bunch of numbers with fields is useful as an introduction, but it isn’t very exciting; we aren’t using the program for much other than printing information we already had. The next program is a little more interesting, because it uses some operators to do some calculation:

class ExamplesLecture1 {
int theAnswer = 5 + 2 * 45;
}

If we run this using make, we get:

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theAnswer = 95)

This used multiplication (with the * operator) and addition (with the + operator) to calculate the value 95 for the field theAnswer. It’s worth noting a few things with this simple example:

If we wanted the version of the program that evaluates to 315, we can insert parentheses around the part we want to evaluate first, as we would in math:

class ExamplesLecture1 {
int theAnswer = (5 + 2) * 45;
}

This would print instead:

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theAnswer = 315)

Exercise

Add a field called anotherAnswer whose value is computed by (5 + 2) - 3 * 9. Run the program with make to ensure it works as expected. Then edit it to produce the result of ((5 + 2) - 3) * 9 instead, and again check that it works as you expect.

Note that there’s nothing special about the names theAnswer or anotherAnswer; if we picked other names like x or someReallyLongFieldName, the programs would still perform the calculation and print it just fine.

Exercise

Confirm that this is true; change theAnswer to someReallyLongFieldName in one of the examples above, and rerun the program to make sure it still calculates the right answer.

1.2.3 Not Quite Math

The examples above mention addition with +, multiplication with *, and subtraction with -. Division is conspicuously missing; at first it seems straightforward to use if we know the operator for division in java is forward slash (/), as in this example:

class ExamplesLecture1 {
int theAnswer = (5 + 3) / 2;
}

This produces:

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theAnswer = 4)

Since we’re calculating 8 / 2, this ought to be what we expect. But, if we alter the example slightly:

class ExamplesLecture1 {
int theAnswer = (5 + 4) / 2;
}

we get the surprising answer below!

ExamplesLecture1:

---------------

 

 new ExamplesLecture1:1(

  this.theAnswer = 4)

So far, we’ve avoided describing anything about the word int (short for integer) that appears above before each field name. It turns out that this is an important detail, and has to do with a key way that Java works, and differs from actual math. In particular, when dividing int values, Java simply removes the decimal part so that the answer is always an integer. Note that it does not round the number, it simply removes any decimal portion of the number entirely (even if it would be 0.9999).

Exercise

What about negative results for division of ints? Do they also have the fractional part removed, or does something else happen? Write an example and run it to test this yourself.

For negative ints as well, Java will simply remove the fractional part. These are the rules of integer arithmetic in Java – multiplication, addition, and subtraction work as we expect, but division doesn’t preserve the fractional part of an answer. Later, we’ll see some ways to represent fractional answers; for now we’ll work with integers only, taking care to use division safely.

There are actually some other caveats about very large numbers that apply to ints that we won’t tackle right away.

1.3 Syntax

In all the examples above, the program was defined simply as a sequence of characters in a plain text file. Some of them, like {, ;, and =, and the arithmetic operators, are special symbols that have specific meaning to Java. Others, like class and int are normal English words that mean something specific to Java – we call these keywords. Others we picked, like theNumberFive or x, and we could have used any word there.

Java expects an extremely specific order for all of these words and symbols in a valid program. We call these rules the syntax of Java. For example, it’s required that after the keyword class comes a name (in all the examples above that name was ExamplesLecture1). For now, that name will always be followed by an open curly brace ({). Then comes a sequence of fields, each separated by a semicolon. Then comes a closing curly brace (}).

It’s useful to see what Java does if we break these rules, and write invalid syntax. For example, if we remove the opening curly brace after ExamplesLecture1, the program would look like:

class ExamplesLecture1
int theNumberFive = 5;
}

If we run this, we get:

⤇ make

javac -cp ../../../lib/tester.jar:. ExamplesLecture1.java

ExamplesLecture1.java:1: error: '{' expected

class ExamplesLecture1

                      ^

1 error

make: *** [ExamplesLecture1.class] Error 1

So Java refuses to run the program, because it doesn’t have the right syntax. Java is extremely picky, and forces us to get things exactly right. You must get used to reading and responding to error messages like the one above. It’s nearly impossible to write correct syntax on the first try all the time, so you’ll often be interpreting error messages many times to make a program run. Be patient with yourself, read the code carefully, and try to make the fix.

Exercise

Take the above example, put the curly brace back, and make sure the program works. Then delete the semicolon, run the program, and check the error message you get. Fix the program.

Exercise

Take the above example, and make sure the program works. Then delete the semicolon, run the program, and check the error message you get. Fix the program.

Exercise

Run the above example, and make sure the program works. Then delete the equals sign, run the program, and check the error message you get. Fix the program.

It’s important to get some practice in responding to error messages like these. Programmers get used to seeing these dozens or hundreds of times per week as they work through programming projects. Don’t be intimidated by them, but use them to figure out your mistakes, misconceptions, and typos.