An introduction to programming in Java

Paul Flavell and Richard Kaye School of Mathematics and Statistics University of Birmingham

November 2000

These notes form a useful introduction to programming in Java as well as a reference guide for the second half of this term’s work and are based on notes produced by Paul Flavell for MSM2G5 in the academic year 1999–2000.

You will find it helpful to re-read them later on in the term after you have had some experience of writing Java programs.

1 Introduction

We only have time for a brief introduction to programming in Java. Much more information about Java is available in textbooks and on the web. A good place to find information on Java is the Sun website www.javasoft.com, in particular at

www.javasoft.com/docs/index.html and the online tutorial at

www.javasoft.com/docs/books/tutorial/index.html

I encourage you to explore these sites. They provide a more expansive view of Java than the one I will be able to present in this short course. It is the intention that everything you need to know about Java for MSM2G5 will be contained in these notes and the notes given out in the computer labs that start in the sixth week of term. You may like to get one of the numerous books on Java, many of which are kept in stock at the large book shops in town and in the book shop on campus. However, as far as I know, there isn’t any book that is really suitable for this short course to mathematicians. For this reason, these notes contain just about everything you will need.

Prerequisites. I will not assume you have any programming experience. Some of the programs that we shall write involve the manipulation of complex numbers, matrices, graphs, and other standard mathematical objects that you do know about. For example, you need to know about complex numbers:

their arithmetic, complex conjugate, modulus, polar coordinates, Euler’s formula, De Moivre’s Theorem and Nth-roots.

You will need to bring these notes to the practical classes.

1 2 Objects and classes

Objects in Java model objects in the ‘real world’. Examples. The following are objects:

• My bank account. • The complex number 3 + 4i.  1 2  • The matrix . 3 4

Objects have properties; the technical term for a property of an object is an instance variable. Examples. My bank account – the current balance. 3 + 4i – the real part.  1 2  – the number of rows. 3 4

We can also do things to objects. That is, we can invoke a method on an object. Examples. My bank account – credit a sum of money. 3 + 4i – calculate its modulus.  1 2  – multiply row 1 by 3. 3 4

A class is a blueprint for objects of a particular type, that is, it describes those things that all objects of that type have in common. A class consists of the following.

• Declaration of the instance variables. • Description of the methods. Example. For a BankAccount object, we might have Instance variables the name of the owner the current balance Methods credit/debit a sum of money add interest print the current balance.

Example. For a ComplexNumber object, Instance variables the real part the imaginary part Methods calculate modulus.

Example. For a Matrix, Instance variables number of rows number of columns entries Methods swap two rows transform into echelon form calculate determinant.

2 My bank account is an instance of the class BankAccount, or a BankAccount object. Tony Blair’s bank account is another instance of the class BankAccount. 1 + 2i is an instance of the class ComplexNumber, 7 is another instance of this class. A standard convention is that classes are given names that start with a capital letter, whereas instances of classes have names starting with a lower case letter. So ‘myBankAccount’ is a suitable name for my bank account, and ‘transformationMatrix’ would be a suitable name for a Matrix object. It’s important to understand that the instance variables of a class describe the properties possessed by a particular instance of that class. The methods of a class describe the operations that can be performed on that particular instance of that class. The type of an object is the class of which that object is an instance. For example, 3 − 2i has type ComplexNumber.

3 Java Programs

A Java program consists of a collection of files called source files. A source file is a file of text that contains a description of a class. This description must be written in the Java , not the informal language of the previous section. We will use the following example, which is a source file for a class BankAccount, to describe some of the main features of the Java programming language. class BankAccount { // INSTANCE VARIABLES:

// The name of the owner of the account String owner; // The current balance double balance;

// METHODS:

// credit the account void credit(double amount) { balance = balance + amount; }

// print the current balance void print() { System.out.println(owner + " has a balance of " + balance); }

// add interest to the account void addInterest(double percent) { balance = balance + balance*percent/100; }

// return the current balance double getBalance() {

3 return balance; } }

On the first line is the statement

class BankAccount

The word class indicates that what follows is a description of a class. The word BankAccount is the name of the class. A name must begin with a letter and be a sequnce of letters or digits. A letter is defined as ‘A’–‘Z’, ‘a’–‘z’, ’ ’ and ‘$’. Names are case sensitive, so Rectangle is not the same as rectangle. As already mentioned, it is customary for the names of classes to begin with a capital letter. On line 2 there is an opening brace { which is matched by a closing brace } on the last line. Thus a Java source file has the general form class name { description-of-class }

3.1 Comments

A comment is any string of characters following // up to the end of that line. So

// INSTANCE VARIABLES: is an example of a comment. A comment does not affect what the program does. Comments are there for the benefit of any humans that read the program (including the programmer). They are crucial for long programs since even the programmer may forget what various parts of the program do. Another way to introduce a comment is to enclose it between /* and */. This second sort of comment can run over several lines, but cannot contain the pair of characters */ of course. I will not use this sort of comment ver often in these notes, but you may use them if you wish.

3.2 Instance Variables

We have to explicitly declare the instance variables of a class. To declare an instance variable, we must define its type and assign it a name. In the BankAccount class, the statement

double balance; declares an instance variable called balance whose type is double. (Roughly speaking, a double is a way of representing a real number on the computer. We’ll say more about types and doubles later.) The computer stores objects in its memory. In any object that is an instance BankAccount, there will be an area of memory set asside to hold a double, and this double may be accesssed using the name balance. Different instance variables in a class must have different names.

4 3.3 Methods

Recall that a method is something that does something to an object. They are a little similar to procedures and functions in Maple. It should be straightforward to see what the methods in the BankAccount class do. Let’s analyze what we want a method to do in general.

• (Optional) start with some input data. • Change the state of the object and/or perform some calculation. • (Optional) Return an answer.

A method specification in Java has the following general form:

returntype methodname(parameter-list) { // here go the statements that actually do something }

The returntype specifies the type of answer that a method returns. If we don’t want a method to return an answer, then we specifiy the return type void. In the BankAccount class, the credit method is an example of a method that alters the state of a BankAccount object but does not return a value. The getBalance method is an example of a method that does return a value. Here is another example of a method that would be useful in the class BankAccount.

boolean isOverdrawn() { if(balance < 0) { return true; } else { return false; } }

Let’s take a look at this method. A boolean can have two values, true and false. (More about booleans later.) When the computer encounters a , it stops executing the method and returns a value. The parameter list specifies the input data to the method. For each item of input data to a method, we must specify its type and give it a name. Here is another example of a method, this one accepts two doubles as input.

// calculate the maximum of a and b double max(double a, double b) { if(a > b) { return a;

5 } else { return b; } }

Notice that in the parameter list, we must separate the parameters with a comma. You will notice that in all these examples, matching braces {...} are aligned under each other. This is very good practice and recommended for all your programs. (Without a convention like this it would be easy to make errors, thinking that an open-brace matched the wrond close-brace.) You probably also have noticed that statements like return a; require a semicolon after them, as do declarations of instance variables. Your Java program will not work if you omit these semicolons, so try to follow the examples here. (Note too, that there is no semicolon after if(a > b). Missing semicolons and semicolons in the wrong place are one of the most common kinds of error in a program.)

4 Types

We have seen that every instance variable must have a type. For example in the BankAccount class there is the declaration

double balance;

Moreover, many methods return an answer and we have to explicitly declare what type of answer a method returns, e.g.,

double getBalance() { return balance; }

So what is a type? The Java programming language comes equiped with eight intrinsic types and in addition to these the programmer may define user defined types.

4.1 Intrinsic types

The most important intrinsic types for our purposes are

int, double, boolean and char.

The other four intrinsic types are

short, long, byte and float.

The four most important types are as follows: int An int is an integer in the approximate range −231 to 231, that is

−2, 147, 483, 648 to +2, 147, 483, 648

6 double A double is a number in the approximate range

−1.79769313486231570×10308 to +1.79769313486231570×10308.

Thus a double is used to represent a real number. However, it is important to realize that a double is is only accurate to about 15 significant digits. This causes no problems in many programs, but in others, as we shall see, it can cause trouble. boolean A boolean can have one of two values, true or false. The type boolean is used in logical testing. For example, the expression

1 < 2

evaluates to true. The expression

a < 0

evaluates to true if the variable a is less than 0, false otherwise. char A char is used to represent a single character of text. For example

char ;

declares the variable c to be of type char. The statement

c = ’A’;

assigns the value ‘A’ to c. So then, for example, the statement

System.out.println(c);

will cause the computer to print the character A.

The other four intrinsic types are less important. short is used to represent integers in the approximate range −215 to 215. long is used to represent integers in the approximate range −263 to 263. byte is used to represent integers in the range −128 to 127. float is used to represent real numbers but only to about 7 significant figures.

4.2 User defined types

A user defined type is a class. For example, BankAccount is a user defined type.

5 A simple Java program

We’ll write a program that prints squares. The program consists of two source files, one called Square.java which defines a class called Square, the other called Test.java which will be used to test the Square class. Here is the file Square.java.

7 // This class is the blueprint for objects // that are squares made out of characters, for example // // **** and ZZZ // **** ZZZ // **** ZZZ // **** class Square { // INSTANCE VARIABLES:

// The character that will be used to print the square. char ch;

// The size of the square. int size;

// CONSTRUCTOR:

// This creates a new Square which is made out of the character c // and has size s. Square(char c, int s) { ch = c; size = s; }

// METHODS:

// This changes the character. void setCharacter(char c) { ch = c; }

// This returns the character that will be used to print the square. char getCharacter() { return ch; }

// This changes the size of the square. void setSize(int s) { size = s; }

// This returns the size of the square. int getSize() { return size; }

// This prints the square. void print() { // We use a loop that prints out size lines. // We need a counter to keep track of how many lines we’ve printed.

8 int i; for(i=0; i < size; i = i+1) { // we use another loop to print out size characters ch int j; for(j=0; j < size; j = j+1) { System.out.print(ch); } // Now we start a new line System.out.println(); } } }

There are many features of this class similar to ones you have already seen and a few that will be new. Next we discuss the various features of this class.

5.1 Instance variables

There’s nothing new here.

5.2 Constructors

We haven’t discussed these yet, but they are very important. A constructor is a bit like a method, but instead of doing something to an object, it actually creates the object. A constructor has the form

className(parameter list) { // statements that initialize a new instance of the class }

The constructor has to have the same name as the class and does not (and cannot) return a value. Look at the constructor in the Square class for an example. The main job of the constructor here is to set the instance variables at the beginning. In a program that uses a class, to create a new instance of a class, the word new is used. So for example, a Triangle object can be created by the instruction

new Square(’*’,5)

This tells the computer to create an instance of the class Square. The computer then executes the statements in the Square constructor, which initializes the instance variables ch and size to ’*’ and 5 respectively. We will see an example of how Square can be used shortly.

5.3 Methods

The only new things here occur in the print method.

9 ‘for’ loops You may have seen loops like these in Maple. ‘for’ loops in Java do the same sort of thing: they repeatedly execute a block of code a certain number of times. The differences are that the syntax in Java is a little different. If you study the print method, you should be able to figure out what’s going on. In any case, we’ll look at these in more detail later on and in the first practical. System.out.print(parameter) prints the parameter, without starting a new line after it is printed. System.out.println(parameter) prints the parameter and then begins a new line. System.out.println() doesn’t print anything, but it does start a new line. (This is a bit like like hitting the enter key when you type in text using a word processor.)

5.4 The Test class

We now look at a class called Test that constructs some instances of Square and uses their methods.

// This is a small program that tests the Square class. class Test { // When we type "java Test" the computer will begin // executing this "main(...)" method. public static void main(String[] arg) { // We begin by creating an instance of a Square. // We’ll assign this to the local variable s. // Note that we must explicitly declare the local variable s // to be of type Square before we can use it.

Square s; s = new Square(’*’,4);

// Let’s create another Square, this time we’ll assign it to the local // variable t. Actually we can declare t and assign it a value // in a single line

Square t = new Square(’Z’,3);

// Now we print out the square s, preceded by a message saying // what we are about to do. System.out.println("Printing s"); s.print();

// We do the same for t. System.out.println("Printing t"); t.print();

// We now alter the object that s refers to by using its set methods. s.setSize(5);

System.out.println("We’ve changed the size of s to " + s.getSize()); s.print();

// Finally we see what the following statement does.

10 s = t;

// It makes the variable s refer to the same Square as s, // to prove it:

System.out.println("After executing s = t ...") System.out.println("Printing s"); s.print(); System.out.print("... we see that s refers to "); System.out.println("the same Square that t does"); } }

5.5 public static void main(String[] arg)

This is the main method of the new class, and is automatically run when we run our program with the command java Test. It wouldn’t be terribly helpful at the moment to discuss the special keywords static, public or the square brackets and the parameter list in the method main at this stage. Just take it from me for now that this is what we need to do.

5.6 Invoking a method

We haven’t discussed how to invoke a method (i.e., cause the computer to execute a method). If v is a variable of type t and methodName is the name of a method of the type t then the statement

v.methodName(parameter-list) causes the computer to execute the method methodName on the object that v refers to. So for example, in the Test class,

s.setSize(5); alters the size of the Square that s refers to. It does not alter the object t, since at that point of the program, t refers to a different object.

5.7 The output

Here is the output that the computer produces.

Printing s **** **** **** **** Printing t ZZZ ZZZ ZZZ We’ve changed the size of s to 5 *****

11 ***** ***** ***** ***** After executing s = t ... Printing s ZZZ ZZZ ZZZ ... we see that s refers to the same Square that t does

12