An Introduction to Programming in Java
Total Page:16
File Type:pdf, Size:1020Kb
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 programming language, 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 return statement, 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.