object oriented programming – with javarkuiper/2z820/book12.pdf · object oriented programming...

89
Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008

Upload: others

Post on 15-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Object Oriented Programming – with Java

Kees Huizing Ruurd Kuiper

December 24, 2008

Page 2: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Preface

Computers are used almost everywhere. Their role is to process data values. A computer can perform anydata processing concern we desire if we provide it with the appropriate description, a program. Executingthe program on a computer results in performing the desired data processing concern.

Programs and their execution can easily become very complex. Therefore, structuring is necessary to makeit feasible for humans to develop programs. Object Oriented Programming (OOP) is a powerful and widelyused programming paradigm that supports structuring. Java is a representative, modern, OOP language.

This book explains OOP and Java.

The approach

No previous knowledge about programming is assumed.

One OOP methodology and style are explained rather than going into alternatives; especially for the noviceprogrammer it is more helpful to be shown one consistent approach than to have to make uninformedchoices. Java is explained and motivated as an OOP language. Knowledge is build up incrementally,without branching or making de-tours, chapters generally depending on previous ones. The emphasis is onconcepts rather than on details. This “narrow path” approach provides a fast route to understanding OOPand Java for the conceptually inclined traveler.

The larger structure of the book is in parts, motivated by the way OOP supports structuring.

OOP provides supports structuring of programs as well as of their execution.

The first option OOP provides for structuring is composition. A program then contains separate descrip-tions of collaborating data processing concerns, called classes. During the execution, these classes giverise to collaborating objects in the computer.

The second option OOP provides for structuring is specialization. A class then is developed as a spe-cialization of some other class. The corresponding objects can also be viewed as specializations of oneanother.

Before building larger structures, using these two options, their elements need to be considered: the classand the corresponding object.

The book therefore consists of three parts.

Part I Basic programming Describing a small data processing concern in one class, giving rise to oneobject.

Part II Composition Describing a larger data processing concern using several classes, giving rise to col-laborating objects.

Part III Specialization Describing a data processing concern using classes that are specializations of otherclasses, giving rise to specialized objects.

1

Page 3: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

The parts contain many small chapters that each consider one programming concept. The chapters have afixed structure.

A section Aim makes the programming aim explicit. A (learner) programmer is driven by programmingaims, and has to (learn to) find solutions corresponding to the aims.

A section Means provides the corresponding programming concept. An example illustrates the conceptthat is being introduced.

A section Execution model incorporates the new concept in the execution model. This model is moredetailed and more explicit than is usually provided. In OOP one’s thinking often moves between the static,fixed, description in classes and the dynamic objects, processing data (significantly, the paradigm is namedObject Oriented Programming rather than Class Oriented Programming). Thinking at the static level issupported by the language facilities. Thinking at the dynamic level is less directly and explicitly supported.The execution model remedies this, as it represents the dynamic behavior of objects that results fromexecuting the static code of the classes. Such a model is useful to aid one’s thinking about programming,e.g., to explain programming concepts; it also is helpful in discussions about programming issues if theparticipants have an explicit, shared, model in mind. A basic model is provided from the outset, which isextended when new concepts require so. To help acquiring a good understanding of the execution model,an execution model viewer, called CoffeeDregs, is provided; this is a piece of software that visualizes theexecution model on screen for each specific program.

In some cases, the treatment of a concept involves further subdivision; then subsections are used, maintain-ing the structure as just outlined.

Where needed, a Remarks section is added.

Exercises are provided, separately, for each chapter. To learn OOP, it is necessary to do a substantialamount of the exercises, preferably after reading the corresponding chapter, before moving on to the nextone. This, and explorations by yourself, will make you an amateur programmer; professional programmingof course requires further education and training.

The book and the exercises are available on the website of the authors ??. Also, the execution model viewerCoffeeDregs, is available there.

Additional web sources

The ”narrow path” approach may require consulting other sources for further detail. Web sources foradditional information are the following.

• For explanations about Java programming in general, see the SUN Java tutorials:http://java.sun.com/docs/books/tutorial/

• For a complete description of the Java language, see The Java Language Specification, third edition:http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

• For information about parts of Java programs, see the J2SE version of the Application ProgrammersInterface (API): http://java.sun.com/j2se/1.5/docs/api/

2

Page 4: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Preliminaries

To write, execute and, in the approach of this book, visualize Java programs, the appropriate software needsto be present on the computer. It is assumed that the reader has some basic knowledge about downloadingand installing software and about using an editor. The software mentioned below is available for free.

To conveniently write Java programs an Integrated Development Environment (IDE) needs to be present.Various IDEs are available, the book does not depend on a particular one, all provide the facilities needed.A suitable IDE is NetBeans, available from http://www.netbeans.org/ . NetBeans runs on Windows, Unix,Linux, and Macintosh platforms.

To execute Java programs, a run-time environment needs to be present. The Java Development Kit, JDK6,provides this; it is available from http://java.sun.com/ .

To visualize the execution of Java programs, the model viewer, CoffeeDregs, needs to be present. Coffee-Dregs is available from the web site of the authors ??.

3

Page 5: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Contents

I Basic programming – One class, one objectDescribing a small data processing concern in one class, giving rise to execution in one object 7

1 Class and object 8

1.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.4 Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Method, built-in data types 14

2.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.4 Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3 Typed instance variables 23

3.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4 Scanner and System.in 27

4.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.4 Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

5 Data dependent control flow 30

5.1 Choice – if-else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

5.2 Repetition – while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

5.3 Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

4

Page 6: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

6 Arrays of variables 38

6.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

6.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

6.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

7 Several instance methods 40

7.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

7.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

7.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

8 Local variables 43

8.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

8.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

8.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

8.4 Remark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

9 Parameters and return value 46

9.1 Data to methods – input parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

9.2 Data from methods – return value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

9.3 Functions and side effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

10 Method recursion 52

10.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

10.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

10.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

11 Overloading 56

11.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

11.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

11.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

11.4 Remark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

12 Constructors 58

12.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

12.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

II Object structures – CompositionDescribing a larger data processing concern in several classes, giving rise to execution in several

5

Page 7: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

collaborating objects 60

13 Method calls between objects 61

13.1 More classes for more objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

13.2 More objects from one class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

14 Method calls with parameters and returns 66

14.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

14.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

14.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

15 Objects with reference communication 68

15.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

15.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

15.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

16 Decomposition scoping 72

16.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

16.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

17 Restricted mutable and immutable data 74

17.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

17.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

17.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

18 Less restricted mutable data 83

18.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

18.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

19 Object recursion 85

20 Class object 86

20.1 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

20.2 Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

20.3 Execution model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

6

Page 8: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Part I

Basic programming – One class, oneobject

Describing a small data processing concern in one class, giving rise to execution in one object

7

Page 9: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 1

Program and execution – Class andobject

A computer is a machine that stores and manipulates data values, like numbers or text, it performs a dataprocessing concern. A computer can perform any data processing concern we desire, if we provide it withan appropriate description.

1.1 Aim

We want the computer to perform different data processing concerns, of our choice and design.

1.2 Means

We develop in the programming language Java a program that contains a class with the description of thedata processing concern. We execute the program on a computer, which results in an object in the computerthat performs the data processing concern.

Java is a language for Object Oriented Programming (OOP), a programming paradigm that is motivatedand explained during the exposition in this book. Java is a “real world” language, not primarily designedfor teaching purposes, so sometimes features show up at times that they cannot yet be appreciated; insuch cases explanation is deferred till later. “Class” and “object” are like that: they make an immediateappearance and are essential OOP concepts, but in Part I are only exploited in a limited fashion.

1.2.1 Writing the source code

Program text is called source code, or simply code - often such somewhat less specific terms are used. Tobe executable, code must follow the Java syntax, a concise set of words and symbols, and grammaticalrules. Also coding conventions are introduced that, unlike the syntax rules, are not binding but are strongsuggestions that improve the readability and other quality aspects of the code. The conventions reflectgenerally accepted practice.

In programming, the computer plays a double role: apart from its main purpose, performing the executionof a program, it also supports writing the program. Such software is called an IDE (Integrated DevelopmentEnvironment). We assume that an IDE has been installed. Amongst other things, an IDE provides an editorwhich we use to write the program.

8

Page 10: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

As an example, we write a small program to put a text message on the screen.

The desired output is:

Hello world, this a Java program.Good luck, programmer!

We write the code stepwise, introducing and explaining the syntax. The program, in this simple case,contains just one class, which we call HelloWorld. It is the container for the code for the data processingconcern.

We store the code in a file with, by rule, the same name as the class and with the extension .java; in ourcase HelloWorld.java.

public class HelloWorld { // class header (class declaration)// here the class body will be written

}

The code of a class consists of a class header and a class body. The header states that the descriptionfollowing is a class and provides the class name; this is called the declaration of the class. By convention,the first letter of a class name is in uppercase. Java is case sensitive, e.g., names that differ in just theuse of an upper- or lowercase will refer to different entities. public in the class header has to be there –explanation deferred.

Curly brackets { and }mark the place where we will write the class body. The text following //, on the sameline, is comment and ignored by the computer. Comments are added to code to help humans understand thatcode. In the examples comments are also used didactically, e.g., to explain newly introduced programmingfeatures. Hence in the examples sometimes more comment may be present than is usual practice.

In this simple case only code for data manipulation is present. Later a class will be seen to contain morethan just such code; this code for manipulation therefore is placed in a sub-container, a method. We callthe method show.

public class HelloWorld {

void show() { // method header (method declaration)// here the method body will be written

}}

The text that describes a method also consists of a header and a body. By convention, method namesstart in lowercase. void before the method name and the parentheses () in the header have to be there –explanation deferred.

The new bracket pair marks the place where we will write the method body.

Finally, we write the code for the method body, that describes putting the message on the screen.

The code to achieve this will consist of command statements. A statement describes an instruction for thecomputer to perform. Statements end in a ; (semicolon). The order in which such statements occur in themethod is the order in which they will be executed.

public class HelloWorld {

void show() {System.out.println(”Hello world,this is a Java program.”); // output and newline statementSystem.out.println(”Good luck, programmer!”); // output and newline statement}

}

We only use the output statement, System.out.println. . . . It describes to output a line of text in a fixedtext window on the screen and to move the output-cursor to the next line on output, i.e., possible further

9

Page 11: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

output is put on the next line. The window is called the console; this kind of output is called consoleoutput. Between the parentheses is data provided to the output command, i.e., the text to be output. Text inJava must be placed between double quotes, " and ". So we use the System.out.println. . . twice, withdifferent output text. We use indentation for readability, it does not influence the workings of the program.We now have written in the class the description of the data processing concern that we aimed for.

However, this code cannot be executed directly. We also have to describe explicitly to create an objectand to call, i.e., start, its method. This we do, in a standard manner and a standard form, by adding thefollowing special piece of start-up code to the class.

public static void main(String[] args) { // marks start−up codenew HelloWorld().show(); // create object, start method

}

For now, the relevant part of the start-up code is the statement new HelloWorld().show();, which infact describes two things. The new HelloWorld() part describes to create, in the computer, an objectaccording to the description of the data processing concern in the class HelloWorld. This object containsan executable form of the method, show. The .show() part, a method call, describes to start the executionof the method show of the object.

new HelloWorld().show(); has to be executed as the first activity of the program, before the objectexists: its very purpose namely is to get things off the ground, i.e., to create the object and to start themethod. To make this happen, new HelloWorld().show(); is contained in a special piece of code, theso-called main, that signals that its contents should be executed first. Why this code looks as it does willbe explained (much) later.

If we write another class for another data processing concern, the name of that class and the code in thebody will be completely different, but the shape of the code in the start-up part remains the same, with onlythe name of class and method being different.

By convention, we put the start-up code at the end of the class. Also by convention, we include a commentabout the purpose of the class right before the class code and a comment about the effect of the method justbefore the method; we also indicate the start-up code by a comment. The complete class, with the didacticcomments omitted, is then as follows.

// demonstrates console outputpublic class HelloWorld {

// puts message on consolevoid show() {

System.out.println(”Hello world, this is a Java program.”);System.out.println(”Good luck, programmer!”);

}

// start−up codepublic static void main(String[] args) {

new HelloWorld().show();}

}

1.2.2 Checking the source code for syntactic correctness

To be executable, a program has to be syntactically correct, i.e., follow the Java syntax. Apart from aneditor, the IDE provides a compiler to check for syntax errors. Having the file containing the program codeopen in the editor, we compile the code (available via a menu option or button with a name such as CompileFile. As a result, information about syntactic errors in the code appears in a special window. After we havecorrected the errors, we compile the code again. Compilation and correction have to be repeated until noerrors are reported anymore.

10

Page 12: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

1.2.3 Translating the source code to byte code

To be executable, the human-readable Java code that we have written needs to be translated into machine-executable code, so-called byte code The compiler also provides this translation: when no syntactic errorsoccur in the code, compilation automatically produces the machine-executable code. The byte code is,automatically, stored in a file with the same name as the class but with extension .class; in our case Hel-loWorld.class. Usually, this file is, again automatically, placed in the same folder as the file with the Javacode. We hardly notice the machine-executable code issue; it is only mentioned here to explain the occur-rence of the .class file.

1.2.4 Executing the byte code

Software that enables to execute programs is called a run-time environment. We assume that a run-timeenvironment has been installed.

We start the actual execution by choosing the command (menu option, button, etc.) Execute (or a similarname).

Now the object is created and the method show is called and starts executing the command statements inthe order that they occur in the code.

Output is:

Hello world, this is a Java program.Good luck, programmer!

1.3 Execution model

In the previous section, two issues about programming showed up. First, that a program is a description ofhow a data processing concern should be performed. The program is syntactic, static, it does not changeduring the execution. Second, that a program can be executed, which makes things happen inside thecomputer. In particular, an object is made from the class. The goings-on inside the computer are themeaning or semantics of the program. The semantics of a program is dynamic, it captures the changesinside the computer over time.

To write good programs, it is important to have a clear understanding of the semantics of a program.However, it is not needed or even helpful to describe in detail, say electronically, what goes on inside thecomputer. Therefore, a conceptual, pictorial representation of the semantics is given, called the executionmodel.

The execution model pictures the execution as a sequence of snapshots, called states. A state representsthe relevant information about what is present inside the computer at one moment in time.

Figure 1.1 pictures the execution of HelloWorld.

Modeling the execution of the start-up part is deferred till later. Thus, the execution sequence starts withthe result of the start-up phase, an object that is labeled with the class name, HelloWorld, and an arbitrarynumber, #90 in this case. (Later several objects of one class will be made, therefore the number.) Theobject contains the method show. There is a dotted line above the method; later an object will containother things than methods as well, that will be placed above the dotted line.

The computer executes one instruction at the time, namely the one where the so-called control is at. Thisinformation is also part of the state. The statement to be executed next is highlighted and marked with acursor symbol. The main difference between the code in the class and the text in the dynamic object is thepresence of control. Note that the start-up code is not present at all in the object.

Output is not part of the state, it appears on the console. For clarity, it is pictured in a separate box.

11

Page 13: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Figure 1.1: Execution of HelloWorld

HelloWorld #90

void show() { System.out.println("Hello ... program."); System.out.println("Good luck, programmer!");}

show()

HelloWorld #90

void show() { System.out.println("Hello ... program."); System.out.println("Good luck, ...!");}

show()

Hello, this is a Java program.Output

HelloWorld #90

void show() { System.out.println("Hello ... program."); System.out.println("Good luck, ...!");}

show()

Hello, this is a Java program.Good luck, programmer!

Output

The pictures shows a sequence of execution states, beginning immediately when the start-up code is fin-ished. For HelloWorld, this is when control is just before the first line of the body of show. In the nextstate, the effect of executing the instruction that was indicated by control is shown. In this case, Helloworld, this is a Java program. is put on the output console. Furthermore, control has movedto the next, second, line of the body of show. This movement of control is called the control flow.

In the subsequent state, similarly Good luck, programmer! is put on the console. Control thenmoves to the last line of the object.

1.4 Remarks

1.4.1 The Java Language Specification

The book provides the essential syntactic and semantic concepts of Java. This entails that not all detailedlanguage features will always be treated in full.

For example, there is another output command, System.out.print rather than the System.out.printlnthat we used, that does not advance the cursor on the console output window to a new line. This statementcan be used to split one line of output over two output statements, for instance to avoid having lines in thesource code that are longer than the editor screen is wide.

Furthermore, when " occurs in the output text itself, i.e., is desired to be output, it has to be indicated thatit is text, and not to be interpreted by the computer as marking the beginning or ending of the text. This isachieved by placing a \ in front of the ".

Such details are not always considered in the book. A complete description of both the Java syntax andsemantics can be found in The Java Language Specification [?], provided by and made available on-line bySUN Microsystems, the developers of Java. It can be consulted when additional information is needed. Thedescriptions given there can only be fully understood by someone who has knowledge about programming,

12

Page 14: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

i.e., the information in [?] should become more appreciable when progressing through this book.

1.4.2 Byte code and the Java Virtual Machine

For most languages, the machine-executable code that the compiler produces is so-called machine-codecode that is directly executed by the computer.

In the case of Java, the compiler produces not machine-code but byte-code, which is an intermediate levelof code that is not executed by the computer directly, but by an intermediate program, the Java VirtualMachine (JVM).

This standardized intermediate ground between source code and computer has advantages for portability,the extend to which programs can be executed by different machines, and for security, the protection of themachine against, e.g., viruses. Both issues are important for web use of programs. A price to be paid forthese advantages is that the JVM approach makes programs less efficient.

As stated above, in section 1.2.3, we hardly notice the machine-executable code issue; this additionalinformation is merely provided because one sometimes may easily encounter the terms byte code and JVMelswhere.

1.4.3 Programming without a specific IDE

Rather than using an IDE to support programming, it is also possible to directly program. A program canbe written using any editor. The Java JDK runtime environment then provides a compiler and enables torun the byte code. The command to compile source code in, say, a file program.java to byte code isjavac program.java which does the syntax check and yields the file program.class containing thesource code. The command to execute the byte code stored in program.class is java.program.

13

Page 15: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 2

Data manipulation – Method, built-indata types

In the previous chapter it was shown how to output fixed textual data values, namely strings of characters.An essential part of data processing is to calculate new data values from given ones. The basic languageelements to do this are introduced now.

2.1 Aim

We want to calculate new data values from given ones.

2.2 Means

We use the Java data types. A data type provides syntax (notation) to describe calculations and semanticsto let the computer perform these calculations. There are several such data types because there are severalkinds of data values, e.g., numbers and text, with corresponding operations.

The syntax of a data type is as follows.

1. Literals, a notation for data values, like 7 and 17.3; literals are also called (simple) expressions.

2. Operators, like +, that take arguments to form (compound) expressions, like 7 + 17. The argu-ments of an operator can be literals, but also other expressions, possibly using parentheses; thus,expressions can be complex formulas, like -(7+5*(-2+17)-8/4).

Expressions describe data manipulations, and hence are written in the body of the method of a class.

The semantics of a data type is as follows.

1. The semantics of a literal is a value in the data type, e.g. a number; inside the computer it is repre-sented as some sequence of bits.

2. The semantics of an operator is an operation that takes values as arguments and produces a new value;inside the computer this is represented as producing a new sequence of bits. The semantics of anexpression is the resulting value produced by successively applying the operations on (intermediate)values, so called evaluation of the expression; e.g., the expression 7 + 2 * 17 evaluates to thevalue 41.

14

Page 16: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

In general, expression evaluation follows the rules that we know from arithmetic etc. Like in arithmetic,parentheses may be used to influence the order of evaluation. The precise evaluation is explained by meansof the execution model, in section 3.3.

Java has three categories of built-in data types: various numeric types, two textual types and a logic type.The essentials are explained below, complete descriptions of the types can be found in ??.

The numeric types can be grouped as dealing with integral numbers or with decimal decimal numbers,usually called floating point numbers. Of each of these groups the most relevant type, int double, re-spectively, is presented. They are used as the first choice, as so-called default type. The other numerictypes are very similar to these and differ only in precision and range.

2.2.1 The integral type int

int is a so-called integral type, used to calculate with integers, i.e., whole numbers.

Syntax

1. literals: ..., -1, 0, 1, ....

2. operators: + addition, - subtraction, * multiplication, / integer division, % modulo (remainder).

Semantics

The literals denote the corresponding values. For performance reasons, the value range of a type is fixed.The values in int range from −231 to 231 − 1. Note that this exponent notation is not part of Java. It isimportant to be aware of these bounds, because if even during calculations values occur that are outside therange of the data type, the outcome may be quite unexpected.

The semantics of the operators is as in usual integer arithmetic, except for the last two operators. / denotesinteger division, producing the integer part of a division. % denotes modulo, producing the remainder afterinteger division.

In the following example, we let the computer evaluate an expression that computes interest using integers.To show the result, we simply apply an output command to such an expression, i.e., we put the expressionbetween the parentheses of an output command.

// handles accountpublic class InterestInt {

// computes interest in integersvoid computeInterest() {

System.out.print(”For a balance of ”);System.out.println(60);

System.out.print(”At rate 3% interest rounded down to a whole number is ”);System.out.println((3 ∗ 60)/100); // integer division}

// start−up codepublic static void main(String[] args) {

new InterestInt().computeInterest();}}

Output is:

15

Page 17: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

For a balance of 60At rate 3% interest rounded down to a whole number is 1

2.2.2 The floating point type double

double is a so-called floating point type, providing a notation for decimal numbers with a flexible posi-tioning of the decimal point.

Syntax

1. literals: floating point notation, e.g., 123.45 or so-called “scientific” notation, with powers of 10,e.g., 1.2345E2, which stands for 1.2345 · 102.

2. operators: + addition, - subtraction, * multiplication, / division.

The notation determines the type: 7.0 denotes a value of type double, whereas 7 denotes a value of typeint.

Semantics

The literals denote the corresponding values. Note that 123.45 and 1.2345E denote the same value. Thevalues in double range from -1.79769313486231570E+308 to +1.79769313486231570E+308.

The operations behave approximately as in decimal number arithmetic.

The idea of a “floating point” is, that the round-off errors that are inevitable because of the finite representa-tion of values in a computer can be minimized by placing the decimal point at the optimal place rather thanat a fixed place. This is a complex issue; to provide some intuition about what precision can be expected incalculations, a sketch is given of how floating point calculations proceed. Roughly and intuitively, eighteendigits are available for the number part. Good precision is achieved by putting the decimal point imme-diately to the right of the first non-zero digit. For example, imagining instead of floating point numbers a3-digit (three rather than eighteen for ease of writing the examples) fixed point number, i.e., with the pointat a fixed place three digits from the right, 0.001234 can only be written as rounded to 0.001. In the 3-digitfloating point case this can be written with greater precision as 1.23E-3.

An expression is evaluated by stepwise computing each (intermediate) value with the decimal point placedin the optimal position. For example, in a 3-digit fixed point computation, i.e., with the point at a fixedplace three digits from the right, the computation 0.120 x 0.120 results in 0.014. Using 3-digit floating pointnotation, with the floating point placed immediately to the left of the first non-zero digit, the computation1.20E-1 x 1.20E-1 results in 1.44E-2. The floating point representation achieves one digit more precisionthan the fixed point representation.

Roughly, the precision of double calculations is determined by a representation using eighteen digits.Roughly, because the computer does not calculate with decimal fractions, it uses binary numbers. Thisdifference affects the precision. E.g., the decimal number 0.5 is a recurring fraction when written as abinary number. Hence, it cannot be exactly represented in a Java calculation.

The division operator / applied to operands of the type double means ordinary division. This is differentfrom its meaning when it is applied to ints. Using the same symbol to denote different operations iscalled overloading of that symbol. In an expression with an overloaded symbol, the type of the operandsdetermines the type from which the operation is taken.

We change the previous example to a program that computes and prints interest with double precision.

// handles accountpublic class InterestDouble {

// computes interest precise and rounded

16

Page 18: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

void computeInterest() {

System.out.print(”For a balance of ”);System.out.println(60.00);

System.out.print(”At rate 3% interest is exactly ”);System.out.println((3 ∗ 60.00)/100); // double division}

// start−up codepublic static void main(String[] args) {

new InterestDouble().computeInterest();}}

For a balance of 60.0At rate 3% interest is exactly 1.8

Java has several more numerical types, providing for different requirements as regards range of values,precision and amount of storage space used. The numerical types are, ordered according to increasingrange, byte, short, int, long, float, double. byte, short, int, long are integral types,float and double are floating point types.

The type of a value is determined by the notation, as mentioned before, 7 is an int and 7.0 a double. Theother types are distinguished by a letter after the digits. For example, to distinguish literals of type longfrom those of type int, the first have an L after the digits, like 7L. This can be used to ensure that the storagespace is large enough for a result or intermediate value occurring during the computation: (1000000L *1000000L)/1000000L remains within the range of a long and correctly evaluates to 1000000. On theother hand, (1000000 * 1000000)/10000000) exceeds the size of an int during computation andwrongly evaluates to -727.

descriptionexample

expressionresult

* multiplication 5 * 2 10

/integer division

ordinary division

5 / 2

5.0 / 2

2

2.5

+arithmetic addition

string concatenation

1+1

"1"+"1"

2

"11"

–subtraction

minus

5-2

-(5-2)

3

-3

%remainder after

division

10 % 5

7 % 5

0

2

Figure 2.1: Arithmetic operators

2.2.3 The textual type char

char is the type used to represent single characters.

Syntax

17

Page 19: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

1. Literals: characters in single quotes, such as ’c’, ’7’ and ’&’.

2. Operators: although applicable, the numerical operations are not very useful. Sometimes the com-parison operators (==, etc., see below) can be used.

Semantics

A character in single quotes denotes the corresponding character value.

2.2.4 The textual type String

String is a textual type, used to represent sequences of characters.

Syntax

1. Literals: sequences of characters in double quotes, such as "Hello world!" , "7" and "17".

2. Operators: + concatenation.

Semantics

A string in double quotes denotes the corresponding string value. + denotes concatenation of strings, e.g.,"a"+"b" has the value "ab".

So the symbol + is overloaded: for int and double arguments addition is performed, for String argu-ments concatenation is performed.

In the following example, we let two strings be concatenated and then be output.

// String concatenationclass HelloString {

// concatenates and outputs two Stringsvoid show() {

System.out.println(”Hello, World, ” + ”this is a Java program.”); //concatenate StringsSystem.out.println(”Good luck, programmer!”);

}

// start−up codepublic static void main(String[] args) {

new HelloString().show();}

}

Output is

Hello World, this is a Java program.Good luck, programmer!

2.2.5 The logic type boolean

boolean is the logic type, used to handle the logical values true and false. The role of boolean inprogramming is somewhat different from that of the other types. As will be shown in chapter 5, logicvalues play a supporting role in programming.

Syntax

18

Page 20: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

operator descriptionexample

expressionresult

<

>

less than

greater than

2 < 3

2 > 2

true

false

<=

>=

less than or equal to

greater than or equal to

2 <= 2

3 >= 5

true

false

==

!=

equal to

not equal to

1 == 1

1 != 1

true

false

&& logical and0 < 2 && 2 < 3

0 < 2 && 3 < 2

true

false

|| logical or0 < 2 || 3 < 2

2 < 0 || 3 < 2

true

false

! negation, logical not!true

!(2<0)

false

true

^ exclusive or2 < 0 ^ 0 < 2

0 < 1 ^ 0 < 2

true

false

Figure 2.2: Boolean operators

1. Literals (just two): true, false.

2. Operators: ||, &&, !, and ˆ .

There are a few less relevant operators which have been omitted.

Semantics

The two literals denote the corresponding truth values. || denotes logic “or” (disjunction), && denoteslogic “and” (conjunction) ! denotes logic “not” (negation), ˆ denotes “exclusive or”.

The following example shows the values of some logic expressions.

// logic expressionsclass LogicExpressions {

// evaluates logic expressions and outputs resultsvoid show() {

System.out.print(”true || false evaluates to ”);System.out.println(true || false);

System.out.print(”true && false evaluates to ”);System.out.println(true && false);

System.out.print(”! true evaluates to ”);System.out.println(! true);

System.out.print(”true ˆ true evaluates to ”);System.out.println(true ˆ true);

}

// start−up codepublic static void main(String[] args) {

new LogicExpressions().show();}

}

Output is:

19

Page 21: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

true || false evaluates to truetrue && false evaluates to false! true evaluates to falsetrue ˆ true evaluates to false

2.2.6 Comparison operators

There is something more to operations on data types: there are also operations that take values from onedata type but produce a value in another data type. An example are the comparison operations, wherecomparing two values of some type yields a value true or false of type boolean. Because the result isof a boolean type, these are called boolean expressions.

Comparison operators, applicable to all numeric types are == (equals), != (does-not-equal), > (greaterthan), >= (greater than or equal), < (smaller than), and <= (smaller than or equal).

Java uses so-called Unicode, a numerical encoding, to represent characters as from char. A character insingle quotes, like ’c’, has as numerical value the corresponding Unicode. The equality operator (==)will later be shown to be of use in programming; as it compares the unicode values, the comparison iscase-sensitive. The < operator then means “less than” according to the ordering of the Unicodes. Becauseof the Unicode values chosen, this is like an alphabetic ordering, although it is not always useful, since it,e.g., orders all lower case characters before (less than) all uppercase characters.

The comparison operator to compare Strings on equality, is equals(), applied as follows: "abc".equals("def");. The unusual syntax comes from the fact that equals is not an operator, but a method. This will be ex-plained later.

The following example shows some comparisons.

// comparisonsclass Compare {

// evaluates comparisons and outputs resultsvoid compare() {

System.out.print(”boolean expression 7 + 17 > 25 evaluates to ”);System.out.println(7 + 17 == 25);

System.out.print(”boolean expression (true || false) == true evaluates to ”);System.out.println((true || false) == true);

System.out.print(”boolean expression ’c’ == ’C’ evaluates to ”);System.out.println(’c’ == ’C’);

System.out.print(”boolean expression \”Hello world\”.equals(\”Hello \” + \”world\”) evaluates to ”);System.out.println(”Hello, World”.equals(”Hello, ” + ”World”));}

// start−up codepublic static void main(String[] args) {

new Compare().compare();}}

Output is:

boolean expression 7 + 17 > 25 evaluates to falseboolean expression (true || false) == true evaluates to trueboolean expression (’c’ == ’C’) evaluates to false

20

Page 22: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

boolean expression "Hello world".equals("Hello " + "world") evaluates to true

Comparing expressions such as these and printing “true” or “false” does not seem very useful. In the nextchapters, when more programming constructs are available, more useful applications of comparisons willbe shown.

2.2.7 Mixing types in an expression

The idea of a type as concerning just one closed set of values is somewhat too restrictive for many practicalsituations. Sometimes it is practical to mix similar types in expressions, say adding an integer to a double.Therefore there is some flexibility in writing typed expressions.

In expressions it is allowed to mix different numeric types. The values are then automatically convertedto the type used in the expression that has the greatest range or precision. This is called widening. Forexample, 7 + 17.0 has double value 24.0.

For a complete description of how these matters are resolved in Java, see the [?], Chapter 5 Conversionsand Promotions.

Warning: be careful with the overloaded operator +. Do not apply it to Strings and numbers in the sameexpression, or at least separate the numeric parts from the String-parts.

2.2.8 Type correctness

Because literals are typed, we know which operators can be applied to them and also, in case of overloading,which operation an operator denotes. Furthermore, the expression itself has a type, following from thetype(s) of its constituents. So we know which evaluable expressions can be formed, namely those consistentwith the type(s) used in the expression. Such an expression is called type correct. It is not necessary toevaluate the subexpressions to determine the type of an expression: it suffices to know the types of thesubexpressions. Type correctness thus can be, and is, checked by the compiler before execution.

The notion of type correctness and the compiler match the flexibility that allows mixing types to someextend.

2.3 Execution model

Evaluation of expressions in Java follows the rules of arithmetic and in general the results should not besurprising. When expressions get more complicated, it is sometimes helpful to know what exactly is goingon. Therefore, the evaluation process is explained in some detail here.

Evaluation of expressions involves two activities: determining the operands for each operator, parsing, andapplying the operators in some order.

2.3.1 Parsing

The subexpressions that are the operands for an operator follow from the binding rules of the operators.These rules are are as in arithmetic (multiplication before addition, etc.), with the additional clause that iftwo operators are equal in binding strength, they are applied from left to right (so-called left-association).

The following example shows the parsing process in steps. The binding of the operators is shown by meansof extra parentheses.

7 - 5.0 + 2 * 3 + 17 gets parsed into

21

Page 23: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

7 - 5.0 + (2 * 3) + 17 because of stronger binding of *; this gets parsed into

(7 - 5.0) + (2 * 3) + 17 because of left-association; this gets parsed into

((7 - 5.0) + (2 * 3)) + 17 because of left-association.

Parsing is part of the compilation process, expressions are analyzed syntactically and the operators areassociated to operands.

When during the execution of the program an expression is evaluated, the process is as follows.

2.3.2 Evaluation step by step

At each step in the evaluation, a so-called evaluable subexpression is evaluated and is replaced by theresulting value. A subexpression is evaluable if its operands are values, i.e., not composite subexpressions.When there is more than one evaluable subexpression, the left-most one is chosen.

The following example explains this. Before each step the subexpression that is going to be evaluated isunderlined.

7− 5.0 + 2 ∗ 3 + 17 −→2.0 + 2 ∗ 3 + 17 −→2.0 + 6 + 17 −→8.0 + 17 −→25.0

Presented here is the most detailed level of modeling: the evaluation of each subexpression is picturedas a step. Depending on the level of detail desired, steps can be omitted. For example, all left-to-rightevaluations could be pictured as one step; this would remove the second state in the example. Also, thewhole evaluation could be pictured as one step; this would remove all but the first and last state in theexample.

2.4 Remarks

2.4.1 Three kinds of errors

The first kind of error is, as we have seen already, that a program is not syntactically correct. The compilerchecks for this, without running the program and produces error messages when the program is not correct.For example, if a ; is omitted. The compiler only completes the translation of a program into executableform when it is syntactically correct, so only then can it be executed.

Syntactic correctness however, does not guarantee the absence of a second kind of errors, run-time errors,that occur during execution and disrupt the execution, causing the program to abort. For example, when ina computation-step division by 0 occurs, the compiler will not report an error, because the problem onlyshows up when the expression is evaluated.

Even when a program does not abort, there can still occur a third type of errors, so-called logical errors,namely that the program does not produce the intended result. For example, when the wrong formulafor computing the interest on a balance is used the program may well execute without aborting, but theoutcome will be wrong. More subtly, if in in a computation a data type used that does not have theappropriate precision or range, the outcome may be wrong too.

22

Page 24: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 3

Data storage – Typed instance variables

In the previous chapter it was shown how to calculate with data values. Often it is necessary to also storevalues. For example when the same initial value is to be used several times or when intermediate valuesneed to remain available for later use in a computation. Additional to providing built-in data types forvalues and operations on them, Java enables storage of values.

3.1 Aim

We want to store and retrieve data values of built-in data types.

3.2 Means

We use typed variables as storage space for values of a built-in type in the computer. We use the assignmentoperator, = to store a value in a variable of that type.

As an example, we use the types double and int to store the contents and the interest rate of a bankaccount. We use the variables in computing the interest and new balance and outputting data. We write thecode stepwise.

To obtain a space for values, we declare variables at the top of the class, before the method. A declarationof a variable consists of its type followed by the name of the variable, which we choose. At creation of theobject, the necessary storage space for values of that type is reserved.

// handles accountpublic class AccountInterest {

double balance; // variable decalarationint rate; // variable declaration}

To store a value in a variable, we use the assignment operator, =. On the left of = we put the name of avariable. On the right of = we put an expression, e.g., a simple value, of the corresponding type. Togetherthis forms an assignment statement. When the assignment statement is executed, the expression on theright hand side of the = is evaluated and the resulting value is stored in the variable on the left hand side.

// handles accountpublic class AccountInterest {

double balance;

23

Page 25: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

int rate;

// updates balancevoid update() {

balance = 60.00; // storing the balance valuerate = 3; // storing the rate value}}

To retrieve a value, the notions of expression and evaluation are extended. The name of a variable isalso an expression. Note, that an expression and thus also a variable as well, can be used to form largerexpressions. When at execution an expression is evaluated that contains a variable, the value stored inthe variable is retrieved and used. E.g., the System.out.print(); and System.out.println();

commands can also be used for variables: in that case the value of the variable is output. The preciseevaluation is explained by means of the execution model, in section 3.3.

// handles accountpublic class AccountInterest {

double balance;int rate;

// updates balancevoid update() {

balance = 60.00;rate = 3;

System.out.print(”Current balance is ”);System.out.println(balance); // retrieving the balanceSystem.out.print(”Interest rate is ”);System.out.println(rate); // retrieving the rate

balance = balance + (rate ∗ balance)/100; // retrieving, computing and storing

System.out.print(”New balance is ”);System.out.println(balance); //retrieving the new balance}

// start−up codepublic static void main(String[] args) {

new AccountInterest().update();}}

Output is

Current balance is 60.0Interest rate is 3New balance is 61.8

Variables balance and rate are initialized at the start of the program. If the same computation is desiredfor different values, only the initialization has to be changed. E.g., the code for the computation of the newbalance balance = balance + (rate * balance)/100 remains unchanged, because it uses valuesstored in variables rather than fixed values.

Note that the assignment statement is asymmetric: when it is executed, first the right-hand side is evaluatedand then the result is stored in the variable on the left-hand side. In the example, in the update of balance,

24

Page 26: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

the old value stored in balance is retrieved and used in the evaluation of the expression on the right handside of the =, and only then the occurrence of balance on the left hand side of = causes the new value tobe stored inbalance.

Be aware of the difference between = and ==. The first is the assignment operator and the second is thecomparison operator that tests for equality.

3.2.1 Mixing types in assignment

Like for values, types also allow some flexibility for variables: if a value is stored in a wider type than itsown type, it is converted to that type. Note, that the value is converted, i.e., if a value is stored in a variableof wider type, the value retrieved will be of the wider rather than the original type.

Conversely, the type of a value can be narrowed using the cast operator. For example, if one knows thatat some point in the computation a variable g of type long in fact holds a value that is only of int-size,one can convert this to a value of type int and store it in a variable i of type int through casting: i =

(int)g. If the actual value of g is greater than an int can hold, the operation will nevertheless be executedand the result is probably not what was intended. It is wise to avoid the cast operator whenever possible.

3.2.2 Type correctness

Type correctness as introduced for expressions with just values in chapter 2 extends to variables and as-signment.

Because variables are typed, we have the information which type of values can be stored in a variable,and thus also which type of values will be retrieved. So we know which evaluable expressions can beformed with those variables, namely those for which the type of the variables are consistent with the typesthat we want in the expression. We also know which values can be stored in a variable, namely those ofcorresponding type. For example, if x is an int variable and s a String variable, the expression x + s isillegal and the assignment x = s is illegal as well.

Even though the values are stored in the variables at run-time, the type of the variables is fixed, so typecorrectness can be checked by the compiler using the type of the variables (which restricts the type ofvalues that can be stored), i.e., before execution. It is therefore called static type checking. Strong typingmeans that the static type check guarantees that no run time errors will occur because of wrong typing.Java supports strong typing to a great extent.

3.3 Execution model

The execution model is extended for variables.

The object state is extended with variables that are put above the dotted line in the object. These are picturedas little boxes containing the value of the variable and labeled with name and type of the variable. Whenthe object is created, the boxes contain the standard initial value of the type, which is 0 for all numerictypes and false for the boolean type. Strings are initialized with the special value null, which will beexplained later. The execution model provides the dynamic, changing, information about an object, whichincludes, obviously, the value of variables.

When an assignment statement is executed, the value of the expression on the right hand side of the =-signis written in the box of the variable which name appears on the left hand side of the =-sign.

In addition to the situation thus far, variable names can also occur in expressions. Therefore, valuation ofexpressions is extended with retrieving the values stored in variables. When we want to show the executionof an expression in detail, we include a step for each variable evaluation in the expression. The order inwhich the values of these variables are retrieved is from left to right.

25

Page 27: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Figure 3.1: Execution of AccountInterestAccountInterest #88

void update() { balance = 60.00; rate = 3; System.out.print("Current ... is ");

update()

0.0double balance 0int rate

AccountInterest #88

void update() { balance = 60.00; rate = 3; System.out.print("Current ... is ");

update()

60.0double balance 0int rate

AccountInterest #88

rate = 3; System.out.print("Current ... is "); System.out.println(balance); System.out.print("Interest rate is ");

update()

60.0double balance 3int rate

AccountInterest #88

rate = 3; System.out.print("Current ... is "); System.out.println(balance); System.out.print("Interest rate is ");

update()

60.0double balance 3int rate

Current balance is

AccountInterest #88

rate = 3; System.out.print("Current ... is "); System.out.println(balance); System.out.print("Interest rate is ");

update()

60.0double balance 3int rate

Current balance is 60.0AccountInterest #88

System.out.print("Interest rate is "); System.out.println(rate); balance = balance + (rate * balance)/100; System.out.print("New balance is ");

update()

60.0double balance 3int rate

Current balance is 60.0Interest rate is

AccountInterest #88

System.out.print("Interest rate is "); System.out.println(rate); balance = balance + (rate * balance)/100; System.out.print("New balance is ");

update()

60.0double balance 3int rate

Current balance is 60.0Interest rate is 3

AccountInterest #88

System.out.print("Interest rate is "); System.out.println(rate); balance = balance + (rate * balance)/100; System.out.print("New balance is ");

update()

61.8double balance 3int rate

Current balance is 60.0Interest rate is 3

AccountInterest #88

System.out.print("Interest rate is "); System.out.println(rate); balance = balance + (rate * balance)/100; System.out.print("New balance is ");

update()

61.8double balance 3int rate

Current balance is 60.0Interest rate is 3New balance is

AccountInterest #88

balance = balance + (rate * balance)/100; System.out.print("New balance is "); System.out.println(balance); }

update()

61.8double balance 3int rate

Current balance is 60.0Interest rate is 3New balance is 61.8

AccountInterest #88

System.out.println(balance); }

update()

61.8double balance 3int rate

Current balance is 60.0Interest rate is 3New balance is 61.8

The execution of AccountInterest is depicted in figure 3.1.

Note, that in the execution of the assignment statement balance = balance + (rate * balance)/100;

in the evaluation of the two balance variables on the right hand side of the = the value 60.0 is used asstored in variable balance in the corresponding states, and that the resulting value 61.8 is put in to thevariable balance in the state where the assignment is completed.

26

Page 28: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 4

Console input – Scanner and System.in

In the previous chapter variables were initialized through assignment of values that were written in themethod code. The result of data processing by a program was shown to the human by outputting these onthe console. It is often convenient to also enable the user to input values to a program via the console. Javaprovides predefined code that enables to do this.

4.1 Aim

We want to input values from the console.

4.2 Means

We use console input statements that are provided as predefined utility code, Scanner.

The use of input in Java is not as direct as the use of output. We have to add a little standard code to obtainthis utility – explanation deferred.

1. Before the code of the class we add: import java.util.*;

2. Before the variable declarations in the class we add: Scanner sc = new Scanner(System.in);

The effect of these statements is that statements are available for input from the console, e.g., sc.next().

When sc.next() is up for execution, we can type a word, i.e., a sequence of characters, on the console.When subsequently we type a return, the statement takes the input from the console to the program. Whenan input statement is up for execution and there is no input available, the program waits until this is pro-vided. To prompt the user that an input is expected, we often put a request for input on the console, usinga System.out.println. . . statement preceding the input statement.

After input, sc.next() acts as an expression that has the value that has been input. As every value has atype, also sc.nextLine() has a type: sc.next() returns a value of type String. E.g., a value can beinput and then be assigned to a String variable using an assignment statement. For example, when str isa variable of type String, the statement str = sc.nextLine(); will input a line of characters from theconsole (typed in by the user) and store this sequence in str.

If the value is intended to be of another type than String, e.g., of type int when a number is needed, aninput statement has to be used that returns that type. Java provides uniform input statements for the built-intypes except Char, for example the following.

27

Page 29: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

• sc.nextInt() has a value of type int

• sc.nextDouble() has a value of type double

• sc.nextBoolean() has a value of type boolean

• sc.next() has a value of type String

Their semantics is a little subtle, to enable practical use of console input. On the console, we can putnot only one word , but several, separated by by whitespace, i.e., one or more spaces, tabs, or newlinecharacters. When followed by a return, these words are taken from the console and put in a queue insidethe computer and then processed one by one by the input statements that, consecutively, are up for execution- for details see the 3.3.

Additionally, there are two input statements that are somewhat different.

• sc.nextLine() has a value of type String

Different from the other statements, whitespace is not considered als separating words, but the whole lineis input as one String.

• sc.next().charAt(0) has a value of type char

Different from the other statements, this statements takesinput single character values.

The difference between nextLine and next is that the first takes a complete line from the input and thesecond one takes only one word; here, words are separated by whitespace, i.e., one or more spaces, tabs,or newline characters.

Note that these commands only work well when a correct number (or boolean value resp.) is typed. E.g.,when sc.nextInt(); is executed and the user types abc, a run-time error will occur.

In the example below we use the additional code and the direct input of double and int values.

import java.util.∗; // provides Scanner description// handles accountpublic class AccountInput {

Scanner sc = new Scanner(System.in); // enables console input via Scanner

double balance;int rate;

// inputs account info and outputs it using consolevoid infoAccount() {

System.out.println(”Type amount for balance and for interest rate”);balance = sc.nextDouble(); // inputs balance amount from consolerate = sc.nextInt(); // inputs rate from console

System.out.println(”Current balance is ” + balance + ”.”);System.out.println(”Interest rate is ” + rate + ”.”);

balance = balance + (rate ∗ balance)/100;

System.out.println(”One year interest has been added.”);System.out.println(”Current balance is ” + balance + ”.”);}

// start−up code

28

Page 30: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

public static void main(String[] args) {new AccountInput().infoAccount();}}

Output and input (indicated by underlining) are:

Type amount for balance and interest rate.

60.0

3

Current balance is 60.0.

Interest rate is 6

One year interest has been added.

New balance is 61.8

Because of the flexibility of the console input, input could also have been given as follows.

60.3

NB The command nextDouble() looks for a decimal point or a decimal comma, depending on the set-tings of your computer. E.g., if your computer is configured for the Dutch settings (so-called locale), it willonly accept a comma in double numbers. In this book, we will use a decimal point.

4.3 Execution model

The input is shown in the console window. Text that hasn’t been read is presented in bold face.

Example to be supplied.

4.4 Remarks

4.4.1 Separating input and conversion

Another approach to inputting values is to use only the sc.next() statement for inputting values. sc.next()caninput any word, i.e., sequence of characters, that is put on the console and delivers it as a value of typeString.

If the value is intended to be of another type than String, e.g., of type int when a number is needed,it is separately converted from the type String to that type. For each built-in type there is a conversionoperator. For the type int this is Integer.parseInt() which convers String values to int values.Inputting a value of intended type int and assigning it to a variable i of type int therefore is done by i

= Integer.parseInt(sc.next()).

Note, that any word can be input and converted this way, but not a whole line containing spaces or a singlecharacter. These cases can be treated by, respectively, programming repeated application of the sc.next()statement and the use of the input statement sc.next.charAt(0).

29

Page 31: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 5

Data dependent execution order – datadependent control flow

The method of an object processes data using statements, e.g., for assignment of values to variables andfor in- and output. The execution order of statements is determined by the order in which control passes tostatements, the control flow. Up till now, statements were executed in the order as written; control flow wassequential. Furthermore, this order was independent of the data values being processed; control flow wasdata independent. In many cases this is too restrictive, as at certain points in the execution it may depend onthe current data values which of several possible actions should be taken, i.e., which of several statementsshould be executed. Java provides data dependent control statements that make this possible.

5.1 Choice – if-else statement

Depending on data values one of two statements is chosen for execution.

5.1.1 Aim

We want to describe that one of two statements that are both written in the program are executed, wherewhich one is executed depends on data values that may differ for different executions of the program.

5.1.2 Means

We use the if-else statement, which selects one of two statements for execution, depending on the value ofa selection guard. The flow of control is data dependent: which statement is chosen for execution dependson data values and may, e.g., differ for executions with different input values.

In the example below, different updates are performed on an account depending to whether a balance issolvent or overdrawn.

import java.util.∗;

// handles accountpublic class AccountUpdate {

Scanner sc = new Scanner(System.in);double balance; // balance of account in some currencyint rate; // interest rate in percent

30

Page 32: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

int debitRate; // debit rate in percent

// set and update balancevoid handleBalance() {

System.out.println(”Type interest rate.”);rate = sc.nextInt();

System.out.println(”Type debit rate.”);debitRate = sc.nextInt();

System.out.println(”Type amount for balance.”);balance = sc.nextDouble();

if (balance>=0) { // guardbalance = balance + (rate ∗ balance)/100;System.out.println(rate + ” % interest has been added.”);

} else {balance = balance + (debitRate ∗ balance)/100;System.out.println(debitRate + ” % debit interest has been subtracted.”);

}

System.out.println(”New balance is ” + balance + ”.”);}

// start−up codepublic static void main(String[] args) {

new AccountUpdate().handleBalance();}

}

Result output is, in case of inputting a non-negative amount of, e.g., 60:

Type interest rate>3Type debit rate>5Type amount for balance.>603% interest has been added.New balance is 61.8.

Result output is, in case of inputting a negative amount of, e.g., -60:

Type interest rate>3Type debit rate>5Type amount for balance.>-305% debit interest has been subtracted.New balance is -31.5.

When the if-else statement is executed, first the guard, (balance >= 0), is evaluated. In case theguard is true, i.e., the account is solvent, the statements between the brackets following the if are executed,adding interest. In case the guard is false, i.e., the account is overdrawn, the statements between the bracketsfollowing the else are executed, imposing the penalty. After execution of the chosen statement, execution

31

Page 33: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

of the if-else statement is completed and control goes, in both cases, to the next statement, showing thenew balance.

The general shape and meaning of the if-else statement are as follows.

Syntax Template

if ( boolean expression ) {statements1

} else {statements2

}

A group of statements surrounded by brackets, a so-called code block is again one statement. By conven-tion, we always write the statements in the two clauses of the if-else statement between brackets, also ifa clause consists of only one statement. The complete if-else statement together with its sub-statementsis again one statement. If the program only needs to perform a statement when the guard is true, and doesnot need to do anything in case the guard is false, the else clause may be omitted.

Semantics

The guard is evaluated, if boolean expression is true, statements1 is executed, else statements2 isexecuted. Then the execution of the if-else statement is completed and control goes to the next statementin the program.

5.1.3 Execution model

Example to be added

5.2 Repetition – while statement

Depending on, changing, data values a statement is executed repeatedly.

5.2.1 Aim

We want to describe that a statement (or group of statements) is executed repeatedly, where how often thestatement is executed depends on variables that change during the execution of the statement.

5.2.2 Means

We use the while statement to repeatedly execute a statement, the while body, depending on the value of arepetition guard. The flow of control is data dependent: how many times the statement is executed dependson data values that change during the execution of the program. The data values that govern the control flowshould be updated in the statement that is repeatedly executed: data change is used to stop the repetition.

In the example below, the build-up of compound interest of 5% from an inputted balance is shown, untilthe owner is a millionaire.

import java.util.∗;

32

Page 34: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

// handles accountpublic class AccountCompound {

Scanner sc = new Scanner(System.in);

double balance;

int rate;

// shows compound interest build−upvoid handleBalance() {

rate = 5;

System.out.println(”Type amount for balance.”);balance = sc.nextDouble();System.out.println(”Balance is ” + Math.round(balance) + ”.”);

while (balance <= 1000000) {balance = balance + (rate ∗ balance)/100;System.out.println(”Balance is ” + Math.round(balance) + ”.”);}

System.out.println(”Goodbye, millionaire.”);}

// main instantiates and uses the objectpublic static void main(String[] args) {

new AccountCompound().handleBalance();}}

Console shows (input is in bold face):

Type amount for balance.800000Balance is 800000.Balance is 840000.Balance is 882000.Balance is 926100.Balance is 972405.Balance is 1021025.Goodbye, millionaire.

When control arrives at the while statement, the guard, balance>=0 is evaluated.

If it is true the body,

System.out.println(”Balance is ” + balance + ”.”);balance = balance − 100;

is executed and after that control goes back to the guard and the execution repeats.

If it is false, the while statement is completed and control goes to the next statement.

The general shape and meaning of the while statement are as follows.

33

Page 35: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Syntax Template

while ( boolean expression (guard) ) {statements (body)

}

Semantics

When control arrives at the while-construct, the guard is evaluated. When it is false, the while-constructterminates immediately, otherwise the body is repeatedly executed. After each execution of the body, theguard is evaluated and the execution of the while-construct is terminated if it is false.

5.2.3 Execution model

In figure 5.1 the first states of the execution of AccountCompound are shown. The value of the variablescanner is presented as a number similar to the number that labels the AccountCompound object. Wewill explain this later.

5.3 Remarks

5.3.1 More repetition constructs

There are two more repetition constructs that are similar to the while construct. There is no essentialdifference, but in some case one construct is intuitively easier to use than the other.

There is a repetition construct that is quite similar to the while loop, where the body is executed at leastonce, also when the guard is initially false. In the example program this construct could be naturally usedin the case that always, regardless of the balance, at least one donation of 100 is given. The while-codewould then be replaced by the following.

do {System.out.println(”Balance is ” + balance);balance = balance + (5 ∗ balance)/100;

} while (balance < 1000000);

Syntax Template

do {statements

}while (boolean_expression);

Semantics

statement0 initialises the variables that are used in the guard. Then control arrives at the body, which isexecuted. Then control arrives at the guard update statements. If the guard is true, control returns to thestart of the body, else control goes to the end of the while statement.

The constructs have the same expressive power.

34

Page 36: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Figure 5.1: Initial part of the execution of AccountCompound

Type amount for balance80000Balance is 800000.

Type amount for balance80000Balance is 800000.

Type amount for balance80000Balance is 800000.

80000Balance is 800000.Balance is 840000.

Type amount for balance80000Balance is 800000.

AccountCompound #92

void handleBalance() { rate = 5; System.out.println("Type amount for balance."); balance = sc.nextDouble();

handleBalance()

0.0double balance

0int rate#13Scanner scanner

AccountCompound #92

void handleBalance() { rate = 5; System.out.println("Type amo ... balance."); balance = sc.nextDouble();

handleBalance()

0.0double balance

5int rate#13Scanner scanner

double balance

Type amount for balance AccountCompound #92

void handleBalance() { rate = 5; System.out.println("Type amo ... balance."); balance = sc.nextDouble();

handleBalance()

0.0 5int rate#13Scanner scanner

Type amount for balance80000

AccountCompound #92

void handleBalance() { rate = 5; System.out.println("Type amo ... balance."); balance = sc.nextDouble();

handleBalance()

0.0 5int rate#13Scanner scanner

Type amount for balance80000

double balance

double balance

AccountCompound #92

balance = sc.nextDouble(); System.out.println("Balance is " + Math.round(balance) + "."); while (balance <= 1000000) {

handleBalance()

800000.0 5int rate#13Scanner scanner

double balance

AccountCompound #92

balance = sc.nextDouble(); System.out.println("Balance is " + Math.round(balance) + "."); while (balance <= 1000000) {

handleBalance()

800000.0 5int rate#13Scanner scanner

double balance

AccountCompound #92

System.out.println("Balance is " + Math.round(balance) + "."); while (balance <= 1000000) { balance = balance + (rate * balance)/100;

handleBalance()

800000.0 5int rate#13Scanner scanner

double balance

AccountCompound #92

System.out.println("Balance is " + Math.round(balance) + "."); while (balance <= 1000000) { balance = balance + (rate * balance)/100;

handleBalance()

800000.0 5int rate#13Scanner scanner

double balance

AccountCompound #92

while (balance <= 1000000) { balance = balance + (rate * balance)/100; S..ln("Balance is " + Math.round(balance) + "."); }

handleBalance()

840000.0 5int rate#13Scanner scanner

double balance

AccountCompound #92

while (balance <= 1000000) { balance = balance + (rate * balance)/100; S..ln("Balance is " + Math.round(balance) + "."); }

handleBalance()

840000.0 5int rate#13Scanner scanner

double balance

80000Balance is 800000.Balance is 840000.

AccountCompound #92

while (balance <= 1000000) { balance = balance + (rate * balance)/100; S..ln("Balance is " + Math.round(balance) + "."); }

handleBalance()

840000.0 5int rate#13Scanner scanner

double balance

80000Balance is 800000.Balance is 840000.

AccountCompound #92

while (balance <= 1000000) { balance = balance + (rate * balance)/100; S..ln("Balance is " + Math.round(balance) + "."); }

handleBalance()

882000.0 5int rate#13Scanner scanner

double balance

...

35

Page 37: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

There is yet another repetition construct. This construct groups the initialization of the guard, the evaluationof the guard and the update of the guard (that in case of the while and the do-while takes pace in the body)together and separates-out the body.

The change to the example program consists in removing the initialization of balance and replacing thewhile loop with the following.

for (balance = sc.nextInt(); (balance < 1000000); balance = balance + (5 ∗ balance)/100)) {System.out.println(”balance is ” + balance);

}

Syntax Template

for ( initialization ; guard ; update ) {body statements

}

Semantics

The initialization gives the variable in the guard its starting value (if more than one initialization statementis needed, these have to be separated by commas). Then control arrives at the guard. If the guard is true,control arrives at the body, else control goes to the end of the for-statement. Then the update is executedand control returns to the guard.

Note that the update is executed after each execution of the body.

All three repetition constructs of java have the same expressive power.

5.3.2 Which control statements should there be – goto?

Intuitively, this dependency of execution order on data could be achieved more flexibly by a control state-ment like:if control is at a certain point and some variable has certain value, then control goes to some other point,for example indicated by a label. This idea was adopted in early programming languages. This so-calledgoto control statement fully achieved data dependent control flow, intuitively to encode all control floworderings.

However, the resulting programs became very difficult to understand, because the labels could be placedanywhere: from the static coded of program it was very hard to see where during the dynamic excutioncontrol would go, resulting in error-prone programs. Therefore modern programming languages do nothave a goto statement anymore, but the more well-structured data dependent control statements givenabove: the if-else construct and the while (or an equivalent variant).

This does not limit the programming tasks that can be solved: the two statements can be shown to enableto write programs with the same computation power as the goto, i.e., provide the same expressive powerbut in a more structured, less error-prone manner.

5.3.3 Computability

Not only provide the above statements the same computation power as the goto, but a much stronger andmore general result holds.

There is an intuitive, not formally defined, notion of effectively computable: “anything that can be com-puted following a recipy of simple instructions”. There are various quite different formalizations of thisintuitive notion, notably Turing machines, an operational definition of an idealized computer, and recursive

36

Page 38: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

functions, a non-operational, mathematical notion. This thesis is not provable, because it links an intuitivenotion to a formal one. Such formal notions have been proven to be equivalent in computation power.

This led to Church’s Thesis: The effectively computable functions are the ones that are computable by aTuring machine (or a recursive function, or any of the other provably equivalent formal notions).

The result now is that, given some suitable coding agreements, any computable function is computable bya computer that has the data type integer and the control flow constructs sequential composition, choiceand while.

This means that at this point we can in principle program everything! However, the main problem inprogramming is not what can be programmed in principle, but how to obtain the programs. For this,structuring, more specifically decomposition into manageable parts and abstraction to a manageable levelis the main option. This is what the rest of the book is about.

37

Page 39: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 6

Matrices of variables – Arrays ofvariables

Up till now only the built-in types were used. To enable structured storage there is a type constructor inJava to make new types from already available ones. There is some flexibility because the precise formdesired may differ from program to program.

6.1 Aim

We want to store several data items of one type in a matrix that can be accessed using indices.

6.2 Means

We use the array construct to make a new type that is a list of fixed length of variables of an alreadyavailable type, with integer indices. To use such a type involves three things.

1. Definition of the new type, an array of the desired type. Java provides variables of the new array typeif [] is put behind the type of the desired items (see the example).

2. Declaration of a variable of the new type. (Step 1 and 2 are performed together.)

3. Creation of an array of the desired type. Java provides the new array type if [] is put behind the typeof the desired items. The length, i.e., the number of elements, of the array is set here, by putting itbetween the []. After creation the length of an array cannot be changed anymore.

The indexing starts with 0. Elements of an array are accessed by writing the array name and the index,say i: 〈arrayname〉[i]. Each element is a variable of the given type, so all operations of that type can beperformed on it, and also assignment.

Provided with an array is the variable 〈arrayname〉.length, that contains the length of the array. Note,that since the indexing starts at 0, the last index in the array is the length minus 1.

As an example we write a program that stores numbers of type int in an array numbers.

38

Page 40: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

import java.util.∗;

class ArrayDemo {// handles array of integer numbersScanner sc = new Scanner(System.in);

int[] numbers; // introduction of the type int[]// and declaration of the array numbers

// fills and prints arrayvoid demo(){

numbers = new int[5]; // creation of the array numbers

for (int i = 0; i < numbers.length; i++) {System.out.println(”Type array element with index ” + i);numbers[i] = sc.nextInt(); // initialization of the elements of numbers}

System.out.println(”First array element is ” + numbers[0]);System.out.println(”Array element with index 2 is ” + numbers[2]);System.out.println(”Last array element is ” + numbers[numbers.length − 1]);}

public static void main(String[] args) {new ArrayDemo().demo();}}

NB In the example we put the creation of the array in the method. It is also possible, to create the arrayoutside the method, when the variable is declared: int[] numbers = new int[10]; Java does notallow to do declaration and creation as separate steps outside the method.

Arrays of more dimensions are also possible in Java: for example, a 2-dimensional array of integers isdefined as an array of arrays through int[][]. Creation then is split over several statements. First, astatement where between the first [] pair the number of rows is written, leaving the next [] pair empty.Second, statements for each row where between the next [] pair the number of columns for that row, i.e.,the length of the row-array, is written. Numbering starts from the left-hand upper corner, top to bottom forrows (!), left to right for columns.

Also, two dimensional arrays with rows of unequal length are possible: ragged arrays. The number ofrow-arrays is obtained through 〈arrayname〉.length, the number of elements in each of the row-arrays ithrough 〈arrayname〉[i].length.

6.3 Execution model

The variable naming an array is, unlike the variables of the primitive types, a reference variable (explanationdeferred to chapter ??). An array in the object is depicted as follows.

---------------| ----------- |

numbers ->| | | | | | | || ----------- || 0 1 2 3 4 || || length 5 || |---------------

39

Page 41: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 7

Partitioning manipulation – Severalinstance methods

Up till now we described the data manipulation task in a class in just one method. When the task is large,it may be difficult to write, understand and maintain the code for it.

In programming, there are many situations like this, where something is too complex to be dealt withconveniently as a whole. The general approach of partitioning can often be applied in such situations. Herea general description of the approach is given, followed by a specific application to the case of methods.Other applications of partitioning are given further on in the book.

Partitioning means dividing something complex into less complex parts that can, to some extent, be treatedseparately. The approach is based on two ideas. For ease of explanation, the case for two parts is considered.

The first idea is composition: making the whole from less complex parts that put together form the whole.

To reduce complexity, making a separate part should be simpler than making the whole directly. Thisrequires that when making one part, not all the details of the other part should have to be considered.Similar holds for putting the parts together. The second idea in the partitioning approach is therefore tomake an abstraction of a part: a description of a part that provides only the information necessary to makethe other part. Similar for putting the parts together. That such an abstraction can be made, depends onchoosing relatively independent parts.

The idea of partitioning is now applied to the method.

7.1 Aim

We want to partition the data manipulation task in a class.

7.2 Means

Applying the idea of composition, we declare and define several methods, with different names, in theclass, that each contain the description of a subtask. One method is, as usual, started from main. Thisstarts the processing; from this method others are started, called, these may call other methods, and so on.A method call takes place when control arrives at a statement that consists of the method name followed bya (often empty) pair of parentheses. In this way the parts are combined. This approach is called “groupingand naming”: grouping of code in a method that has a name by which it can be called. This code can beused repeatedly and at different places in the code by writing a call where desired.

40

Page 42: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Applying the the idea of abstraction, we write a short description of the effect of the method on the instancevariables as a comment just before the method declaration.

The various methods manipulate the data stored in the instance variables of the class. These variables areaccessible for all methods: it is the data manipulation that is partitioned, not the data storage.

import java.util.∗;

// handles accountpublic class AccountPartitioned1 {

Scanner sc = new Scanner(System.in);

double balance;int rate;

// initializesvoid initialize() {

rate = 5;System.out.println(”Type amount for balance.”);balance = sc.nextDouble();

}

// shows balancevoid showBalance() {

System.out.println(”Balance is ” + balance + ”.”);}

// updates balancevoid updateBalance() {

balance = balance + (rate ∗ balance)/100;System.out.println(rate +” % interest has been added.”);

}

// handles balancevoid handleBalance() {

initialize(); // call to method initializeshowBalance(); // call to method showBalanceupdateBalance(); // call to method updateBalanceupdateBalance(); // second call to method updateBalanceshowBalance(); // second call to method showBalance

}

// start−up codepublic static void main(String[] args) {

new AccountPartitioned1().handleBalance(); // start method handleBalance}

}

Output is (input in bold) :

Type amount for balance.60Balance is 60.0.5 % interest has been added.5 % interest has been added.Balance is 66.15.

We declare and define methods in the class, as before, but now several rather than just one. The class hasfour so-called instance methods, initialize, updateBalance, showBalance and handleBalance

41

Page 43: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

(the method main is a method, but not an instance method). Three of them are called from the method that isexecuted first, i.e., handleBalance. The same method can be called several times, e.g., updateBalenceis called twice here.

We obtain the description of the whole task as the composition of the description of subtasks, here initialize,updateBalance, showBalance and handleBalance. The composition is subtle, in the sense that thereis no separate combination operator: we combine the descriptions of the parts through the calls in thiscase inside one of them, handleBalance. So the parts themselves contain the information about theircomposition.

The abstraction is that to write each of the methods we only have to consider the variables of the class andabstract descriptions of the other methods. We provide the abstract descriptions as a comment above eachmethod that describes its activity. The code then needs not be read. When sensible names are chosen forthe methods, often even just these provide enough information.

7.3 Execution model

Example to be provided

The execution model reflects that a method becomes part of the object when it is called. Although the start-up code will be discussed in more detail later, it is mentioned now that in this start-up code the methodhandleBalance is called.

From then on, further calls are made from the methods in the object, like initialize being called fromhandleBalance Also the method from which the call is made, here handleBalance remains part of theobject. When a method is executed, a new method execution box is drawn inside the object. The body ofthe method is displayed inside the box, below the dotted line. The control marker is put at the beginningof the body of the called method. A passive control marker is left at the place of the call andr signals theplace where control has to return when the called method is finished. After the method that has been calledfinishes, the method execution box is removed from the object and the passive marker becomes activeagain, putting control just after the method call.

So the object has a more permanent existence then the methods. The instance variables of the object arepictured outside the methods and are accessible for the methods; they are as persistent as the object is. It ishelpful to view the object as a data container, storing values, with methods to manipulate the values.

In the same way as partitioning in methods was used in writing the description of the manipulation task ofthe class, this partitioning is helpful in understanding the execution. As shown in the example, the existenceof methods in an object may vary during execution – this is not directly seen from the class description butit is reflected in the execution model.

42

Page 44: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 8

Temporary data storage, in methods –Local variables

An object is a data container, storing data like a bank account balance in instance variables, and manipulat-ing the data by means of various methods. Such data is persistent in that it is preserved over the executionof different methods.

However, additional data may be used in the execution of one method, for example a while-loop counter.Such data is relevant only to individual executions of that specific method rather than needing to be pre-served in an instance variable of the object. Such data therefore belongs in the method that uses it ratherthan in the object and is not accessible from outside the method execution.

Local variables in methods enable better abstraction.

8.1 Aim

We want to describe temporary storage of data that only is required for the duration of a method execution,as opposed to the persistent data that the object is the container for.

8.2 Means

We use local (with respect to the method) variables that are declared in the body of the method; usually atthe beginning of the method body.

Consider the compound interest program from chapter ??. There the number of iterations depended on adesired amount in the balance to be achieved.

We now consider a variant of the compound interest example where the number of iterations is chosen bythe user. The amount in the balance is the relevant persistent data for this class, so it is stored in an instancevariable. balance.

The number of iterations is of relevance for computing the compound interest only, the method compoundInterest.Hence we make this number a local variable, say years, of compoundInterest.

import java.util.∗;

// handles accountpublic class AccountCompoundLocal {

Scanner sc = new Scanner(System.in);

43

Page 45: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

double balance;int rate;

// inputs and sets balancevoid initialize() {

System.out.println(”Provide amount for balance and interest rate.”);balance = sc.nextDouble();rate = sc.nextInt();

}

// shows balancevoid showBalance() {

System.out.println(”Balance is ” + balance + ”.”);}

// compute and add compound interestvoid compoundInterest() {

int years; // local variable, counter for number of iterations

System.out.println(”How many years of compound interest you want?”);years = sc.nextInt();

while (years > 0) { // uses the local variable yearsbalance = balance + (rate ∗ balance)/100;showBalance();years = years−1; // updates the guard

}}

// handles balancevoid handleBalance() {

initialize();compoundInterest();

}

// main instantiates and uses the objectpublic static void main(String[] args) {

new AccountCompoundLocal().handleBalance();}

}

Output of this program is (input in bold):

Provide amount for balance.60How many years of compound interest you want?2Balance is 61.8.Balance is 63.6 ...

8.3 Execution model

Local variables are drawn at the top of the method execution box, above the dotted line. They are just asinstance variables, the only difference being their location.

44

Page 46: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Example to be added

As can be seen from the execution model, the variable years only exists while compoundInterest exists.

8.4 Remark

The for-construct as discussed in chapter ?? allows an even stronger localization of variables than place-ment in a method rather than in an object.

We first show how the last example changes to a for loop and then discuss the further localization.

for (int years = sc.nextInt(); years > 0; years = years−1) {balance = balance + (rate ∗ balance)/100;

}

The first item of the three items in the control part of the for-loop, initialization of the guard, also allowsto declare the guard variable there. So the following further change is possible, moving the declaration ofyears inside the for-construct.

The result of this change is, that as far as the program concerns, this variable years exists only for the forloop fragment: if another variable with the same name years is declared, it is in fact another variable andit will behave as if it had a different name. The idea is that the variable years is relevant for the for looponly, and thus need not be available outside that so called scope. For example when various indexed loopsoccur, this makes the parts of the code less dependent of each other and simplifies writing and maintainingthe code.

45

Page 47: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 9

Flexible data exchange with a method –Parameters and return value

A method provides flexibility as to where in the code its task is described to be performed: anywhere themethod is called. Up till now a method acted on values stored in the instance variables of the object or inlocal variables of the method. This makes it not so flexible as regards selecting the values with which themethod performs the task: these have to be stored in these fixed variables. Often the data manipulationtask that a method performs is useful to apply for various values that are not all stored in these fixed places,but that rather are selected at different applications of the method. For example, a method that computesthe square root should be able to do so for values stored in many different places or even to values directlygiven to the method as a literal. Explicitly providing different choices of such values to the method isenabled by the parameter mechanism.

Similarly, the result value of a method might be desired to be made available not in a fixed variable butmore flexibly. In case of a square root, it should be possible to make the result available wherever needed.Explicitly providing a result value from a method is enabled by the return mechanism.

The idea to achieve this is to have special local variables in the method that contain the desired start valueswhen the method starts. Then the method executes using these start values. Finally, a result can also beput in a special local variable. Because a method provides abstraction in he sense that local variables arenot accessible outside the method, a language feature is introduced to provide values to the method and toobtain the result value.

9.1 Data to methods – input parameters

We show how data can be provided to a method.

9.1.1 Aim

We want to provide data to a method explicitly in a flexible manner.

9.1.2 Means

We provide data to a method through a parameter. In the header of the method, inside the parentheses afterits name, formal parameters and their types are added. A formal parameter can be used in the body of themethod as a local variable, for example on the right hand side of an assignment. It can be viewed as a local

46

Page 48: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

variable, with one difference: it is initialized at the call. In the method call, we fill in expressions betweenthe parentheses: the actual parameters. When the method is executed, as the first action the value of theactual parameters is assigned to the formal parameters in the body. The number and types of the actualparameters has to match the list of formal parameters exactly. The order in which the actual parametersappear in the call determines to which formal parameters their values are assigned.

In the example below the interest rate is a parameter to the method addInterest.

import java.util.∗;

// handles accountclass AccountParameter {

Scanner sc = new Scanner(System.in);

double balance;int rate;

// initializesvoid initialize() {

System.out.println(”Type amount for balance.”);balance = sc.nextDouble();System.out.println(”Type amount for interest rate.”);rate = sc.nextInt();

}

// shows balancevoid showBalance() {

System.out.println(”Balance is ” + balance);}

// adds interest r to balancevoid addInterest(int r) { // r formal parameter

balance = balance + (r ∗ balance)/100;}

void handleBalance() {int bonusRate;

initialize();

System.out.println(”First, a start interest is addded, at the fixed start rate ” + 1);addInterest(1); // value 1 as actual parametershowBalance();

System.out.println(”Next, a bonus interest is added, at the bonus rate that you type in ”);bonusRate = sc.nextInt();addInterest(bonusRate); // value of ’bonusRate’ as actual parametershowBalance();

System.out.println(”Next, the interest is added according to the account rate ” + rate);addInterest(rate); // value of ’rate’ as actual parametershowBalance();

}

//start−up codepublic static void main(String[] args) {

new AccountParameter().handleBalance();}

}

47

Page 49: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Output is (input in bold):

Type amount for balance.60Type amount for interest rate.3First, a start interest is added, at the fixed start rate 1Balance is 60.6Next, a bonus interest is added, at the bonus rate that you type in7Balance is 64.842Next, the interest is added according to the account rate 5Balance is 66.78726

9.1.3 Execution model

Parameters are drawn as variable boxes above the dotted line in method executions. To distinguish themfrom local variables, their name is prefixed with a @-character. When the method execution is created, theparameter boxes are filled with the value of the actual parameters.

9.2 Data from methods – return value

We show how data can be obtained from a method.

9.2.1 Aim

We want to obtain data from a method explicitly in a flexible manner.

9.2.2 Means

We obtain data from a method through the return statement of that method. At the end of the methodbody, a return statement is added, consisting of the word return followed by an expression that hasthe desired data value, terminated by a semicolon. We say that the value of this expression is returned bythe method and the effect is that this value is filled in for the method call in the expression where the callappears. This valueis used in the evaluation of the expression.

The type of the returned value is given at the header of the method definition: instead of void, the type iswritten.

Note that, in contrast to the input case where more than one parameter is possible, only one value can bereturned.

In the example below the interest is returned by the method giveInterest and can either be displayed tobe collected or added to the balance.

Note, that the two mechanisms, parameters and return value, are independent: as shown, a method canhave parameters without having a return value and vice versa; a method can also have neither or both.

import java.util.∗;

// handles accountclass AccountReturn {

Scanner sc = new Scanner(System.in);

48

Page 50: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

double balance;int rate;

// initializesvoid initialize() {

System.out.println(”Type amount for balance.”);balance = sc.nextDouble();

System.out.println(”Type amount for interest rate.”);rate = sc.nextInt();

}

// shows balancevoid showBalance() {

System.out.println(”Balance is ” + balance);}

// compute interest at stored ratedouble computeNewBalance() {

return balance + (rate ∗ balance)/100; // returns balance with interest}

void handleBalance() {String choice;

initialize();

System.out.println(”For balance to be updated with interest, type ’u’.”);System.out.println(”For balance plus interest just to be displayed, type any other letter.”);choice = sc.next();

if ( choice.equals(”u”) ) {balance = computeNewBalance();

} else {System.out.println(”Balance plus interest would be ” + computeNewBalance());

}

showBalance();}

//start−up codepublic static void main(String[] args) {

new AccountReturn().handleBalance();}

}

Output is (input in bold):

Type amount for balance.60Type amount for interest rate.3Balance to be updated with interest, type ’u’.Balance plus interest just to be displayed, type any other letter.uBalance is 61.8

or

49

Page 51: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Type amount for balance.60Type amount for interest rate.3Balance to be updated with interest, type ’u’.Balance plus interest just to be displayed, type any other letter.dBalance plus interest would be 61.8Balance is 60.0

In the first case, the return value of computeNewBalance is assigned to the variable balance. In thesecond case, the return value is put on the console.

9.2.3 Execution model

When a method with return value terminates, the return value is used in the evaluation of the expression inwhich the call is made. The value is not directly shown in the model, it is indirectly visible in the effectthat it has in, e.g., the new value of a variable.

9.3 Functions and side effects

A restricted application of the parameter and return mechanisms enables to write functions.

9.3.1 Aim

We want to program functions.

9.3.2 Means

We use the parameter and return mechanism with additional restrictions.

A function is a special method that has parameters and returns a value. Additionally, a function shouldhave no side effects, i.e., should not change any instance variable value.

These features make a function fit to be used in expressions, in a similar fashion as in mathematics.

In the example below, the interest is computed using such a function.

import java.util.∗;

// handles accountclass AccountFunction {

Scanner sc = new Scanner(System.in);double balance;int rate;

// initializesvoid initialize() {

System.out.println(”Type amount for balance.”);balance = sc.nextDouble();

}

// shows balance

50

Page 52: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

void showBalance() {System.out.println(”Balance is ” + balance);

}

// returns interest for balance amount b at rate rdouble computeInterest(double b, int r) { // b and r formal parameter

return (r ∗ b)/100;}

void handleBalance() {

System.out.println(”For a balance under 1000, the interest rate is 3%.”);System.out.println(”For example, 900 yields interest ” + computeInterest(900, 3));

System.out.println(”For a balance over 1000, the interest rate is 4%.”);System.out.println(”For example, 1100 yields interest ” + computeInterest(1100, 4));

System.out.println(”Please type your choice for balance amount.”);System.out.println(”We will add a year of interest.”);

initialize();

if (balance < 1000) {rate = 3;

}else{rate = 4;

}balance = balance + computeInterest(balance, rate);

showBalance();}

//start−up codepublic static void main(String[] args) {

new AccountFunction().handleBalance();}

}

Output is:

For a balance under 1000, the interest rate is 3%.For example, 900 yields interest 27.0For a balance over 1000, the interest rate is 4%.For example, 1100 yields interest 44.0Please type your choice for balance amount.We will add a year of interest.Type amount for balance.1100Balance is 1144.0

9.3.3 Execution model

As follows from combining the paramaters and return values.

51

Page 53: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 10

Recursive problem solving – Methodrecursion

Some data manipulation tasks can, by their nature, best be performed as performing some small manipula-tion task on the result of first performing the same task on simpler data. This is repeated until such a simpletask results that it can be performed directly. The small manipulation tasks created in this process are thenperformed, in the order opposite of the one in which they were created.

This is the recursive (recurring to itself) execution of a task: a recursive algorithm. A task is called recursiveby nature if a recursive algorithm is the easiest kind of algorithm to design for it.

10.1 Aim

We want to perform a task recursively (the simplification usually being in terms of the data).

10.2 Means

We write a recursive method for the task. The method body firstly contains code that describes the recursivepart of the task, followed by a call to the method itself, with simpler data. This part is executed whenthe simplest case is not reached yet. Secondly, the method body contains code that describes how todirectly perform the task for the simplest case. This code is executed when the method is called with datacorresponding to the simplest case.

The data that is relevant for the recursive execution of the task, and thus has to become simpler at eachrecursive call, is usually provided through parameters. To enable use of the results of the calls, in buildingthe total result, the results of the calls are usually provided through the return.

NB A recursively performed task can always also be performed using a, different, iterative algorithm.Translation often is not easy. Usually an iterative algorithm is more efficient, especially in terms of memoryuse, than a recursive one.

In the example below, a recursive method is used to compute the factorial of an integer number.

import java.util.∗;

class FactorialParameterReturn{Scanner sc = new Scanner(System.in);

long factorial(int n){

52

Page 54: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

if (n==0)return 1;

elsereturn n∗factorial(n−1);

}

public void demo(){int n;

System.out.println(”Provide a number to compute the factorial for”);n = sc.nextInt();System.out.println(”Factorial of ” + n + ” is ” + factorial(n));}

// main instantiates and uses the objectpublic static void main(String[] args) {

new FactorialParameterReturn().demo();}}

An alternative is, to not store each intermediate values in a separate variable, as is the case in the aboveapproach using parameters and returns, but re-use the variables at each step. This involves undoing valuechanges as in the following adaptation of factorial.

import java.util.∗;

class Factorial{Scanner sc = new Scanner(System.in);

int n;long fac;

void factorial(){if (n==0)

fac = 1;else{

n=n−1;factorial();n=n+1;fac=n∗fac;

}}

public void demo(){

System.out.println(”Provide a number to compute the factorial for”);n = sc.nextInt();factorial();System.out.println(”Factorial of ” + n + ” is ” + fac);}

// main instantiates and uses the objectpublic static void main(String[] args) {

new Factorial().demo();}}

53

Page 55: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

10.3 Execution model

Each recursive call gives rise to a new instantiation of the method, until the simplest case is reached.When, starting with the simplest case, the execution of some method is completed, the result is returned tothe previous method and the returning method disappears.

---------------------- --------------------|>fac(3){ | | fac(3){ || if (n==0) | | if (3==0) || return 1; |->-| return 1; |->| else | | else || return n*fac(n-1);| |> return 3*fac(2);|| } | | } |---------------------- --------------------------------------------------------------| fac(3){ >fac(2){ || if (3==0) if (n==0) || return 1; return 1; |->| else else ||- return 3*fac(2); return n*fac(n-1);|| } } |----------------------------------------------------------------------------------| fac(3){ fac(2){ || if (3==0) if (2==0) || return 1; return 1; |->| else else ||- return 3*fac(2); > return 2*fac(1);|| } } |----------------------------------------------------------------------------------------------------| fac(3){ fac(2){ >fac(1){ || if (3==0) if (2==0) if (1==0) || return 1; return 1; return 1; |->| else else else ||- return 3*fac(2); - return 2*fac(1); - return 1*fac(0);|| } } } |------------------------------------------------------------------------------------------------------------------------| fac(3){ fac(2){ fac(1){ || if (3==0) if (2==0) if (1==0) || return 1; return 1; return 1; |->| else else else ||- return 3*fac(2); - return 2*fac(1); > return 1*fac(0);|| } } } |---------------------------------------------------------------------------------------------------------------------------------------------| fac(3){ fac(2){ fac(1){ >fac(0){ || if (3==0) if (2==0) if (1==0) if (0==0) || return 1; return 1; return 1; return 1; |->| else else else else ||- return 3*fac(2); - return 2*fac(1); - return 1*fac(0); return 0*fac(-1);|

54

Page 56: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

| } } } } |------------------------------------------------------------------------------------------------------------------------------------------------------------------| fac(3){ fac(2){ fac(1){ fac(0){ || if (3==0) if (2==0) if (1==0) if (0==0) || return 1; return 1; return 1; > return 1; |->| else else else else ||- return 3*fac(2); - return 2*fac(1); - return 1*fac(0); return 0*fac(-1);|| } } } } |----------------------------------------------------------------------------------------------------------------------------------------| fac(3){ fac(2){ fac(1){ || if (3==0) if (2==0) if (1==0) || return 1; return 1; return 1; |->| else else else ||- return 3*fac(2); - return 2*fac(1); > return 1*1;|| } } } |------------------------------------------------------------------------------------------ ---------------| fac(3){ fac(2){ | | fac(3){ || if (3==0) if (2==0) | | if (3==0) || return 1; return 1; |->-| return 1; || else else | | else ||- return 3*fac(2); > return 2*1;| |> return 3*2;|| } } | | } |----------------------------------- ---------------

55

Page 57: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 11

Naming similar methods – Overloading

Method names can be used to indicate similar methods if the methods differ in the parameter lists.

11.1 Aim

Sometimes methods perform essentially the same tasks, but only differ in the kind of information thatis provided as input through their parameters. Such methods can be given the same names, using thedifference in parameter lists to distinguish between them.

11.2 Means

We use overloading of method names, i.e., methods with the same names but with a different list of pa-rameters are regarded as different methods. Note that a difference in the names of parameters only doesnot count as a difference in methods. Only a difference in the list of types is what counts, i.e.., a differentnumber of parameters, a different type of a certain parameter, or a different ordering of types.

In the example below, there are three methods with names that differ only in the parameter lists.

class AccountOverloader{double balance;int rate;

void initialize() {balance = 0;rate = 0;

}

void initialize(double b) {balance = b;rate = 0;

}

void initialize(double b, int r) {balance = b;rate = r;

}

void showData(){

56

Page 58: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

System.out.println(”Balance is ” + balance);System.out.println(”Interest rate is ” + rate);

}

void demo(){initialize();showData();

initialize(50.0);showData();

initialize(50.0, 5);showData();

}

// start−up codepublic static void main(String[] args) {

new AccountOverloader().demo();}

}

The three calls lead to the execution of three different methods.

11.3 Execution model

In the execution model, the method that is executed as a result of a call is made visible in the object. Adifferent actual parameter list will lead to a different method being executed and hence a different methodbody will be drawn in the object.

11.4 Remark

– Overloading and narrower or wider types

As discussed in chapter ??, types may be in a relation, e.g., int being a narrower type than the wider typelong. E.g., values of a narrower type can be assigned to variables of a wider type. Similarly, a value of anarrower type can be used in method calls where the formal parameter is of a wider type.

For the selection of an overloaded method, the “best match” is then chosen, i.e., if there is only a methodm(T t) and a call m(v)is made with with a variable v of narrower type S of T, this method will be executed.However, if there is also a method m(S s) available, then this will be the method that is executed at thecall m(v).

Subtle mixtures of types could occur, e.g., in case of methods with more than one variable. This may leadto calls where it is ambiguous which method to apply. As an example, consider again the type T withnarrower type S. Let m(T t, S s) and m(S s, T t) be overloaded methods. Let v and w be variablesof type T. In the case of a call m(v, w) both methods match, neither of them more precise than the other.This is called ambiguous invocation and results in a compilation error. In general, it is not wise to defineoverloaded methods that differ only in subtle ways like this.

57

Page 59: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 12

Initializing objects – Constructors

Up till now, initialization of instance variables was often done using a method, say, initialize, andcalling this method before most of the other methods. Java incorporates this idea in the language, thusproviding a convenient way to initialize objects and to guarantee that this code is executed before any othermethod.

12.1 Aim

We want to initialize the instance variables of an object before any other code is executed on the object.

12.2 Means

We use a constructor to initialize objects. A constructor is a special method with as name the name ofthe class that it belongs to. A constructor is automatically called, directly when an object is created. Byconvention, the definitions of the constructors are positioned before the other methods in the class, justafter the declaration of the instance variables.

A class can have several constructors. Overloading is used to distinguish between these, i.e., the construc-tors differ in the parameters they have. When an object is created, values for parameters are given in thenew-clause, between the parentheses following the class name. Which parameters are provided decideswhich constructor is called.

Constructors are different from ordinary methods in the following way:

1. a constructor has no return type (not even void);

2. the name of a constructor is the same as the name of the class; an ordinary method can not have thename of the class as its name;

3. a constructor can not be called directly; it is automatically called at creation of an object (by the newstatement), and only then.

In the example below the constructor is demonstrated.

// demonstrator of constructorsclass AccountC{

double balance;int rate;

58

Page 60: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

AccountC(double b) {balance = b;rate = 0;

}

AccountC(double b, int r) {balance = b;rate = r;

}

void showData(){System.out.println(”Balance is ” + balance);System.out.println(”Interest rate is ” + rate);

}

// start−up codepublic static void main(String[] args) {

new AccountC(50.0).showData(); // creates AccountC object using constructor with double parameter}

}

Because one actual double parameter 50.0 is filled in, the constructor with that parameter is called.

Output is:

Balance is 50.0Interest rate is 0

To call the constructor with two parameters, the startup code is modified to:

// start−up codepublic static void main(String[] args) {

new AccountC1(50.0, 5).showData(); // creates Account object using constructor with double parameter and int parameter}

Output is:

Balance is 50.0Interest rate is 5

Remark Before constructors were introduced, no constructors were present in the class. In that case, anobject can, only be created without parameters. Once one or more constructors are present in the class, anobject can only be created with these constructors. As a consequence, the new-clause without parametersis for such a class only legal if there is a constructor without parameters present. The idea is, that oncea programmer provides some explicit initialization information in constructors, this should be providedexplicitly for all parameter list choices used in object creation.

59

Page 61: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Part II

Object structures – CompositionDescribing a larger data processing concern in several classes, giving rise to execution in several

collaborating objects

60

Page 62: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 13

Objects with control communication –Method calls between objects

So far data processing concerns were described in one class and performed by one object. However, a dataprocessing concern often consists of several smaller interacting sub-concerns. To improve code organiza-tion such sub-concerns and their relations are described in separate classes. The classes are instantiatedto objects, so the activity in the computer is structured similarly. Two cases are treated: obtaining moreobjects by writing for each object a class that describes it, and also creating several objects from the sameclass. Communication between objects is by means of method calls.

13.1 More classes for more objects

We show how more classes and objects can be used to structure a concern into sub-concerns.

13.1.1 Aim

We want to organize code and execution by dividing a data processing concern into sub-concerns.

13.1.2 Means

For each sub-concern we describe in a separate class the data processing to be performed by the corre-sponding object. Setting-up the relations between objects and their interaction is also described in theclasses.

First, we consider the structure. Every object has a unique number by which it can be addressed, calledaddress hereafter. One class can use another class in its description by describing that an object of thissecond class is created and by describing that it has the address of that object.

Note that structuring occurs at both the class and the object level: The class refers, in its code, to anotherclass; the object has the address of another object. A reference variable stores the address, also called thereference, of an object of a certain class. The type notion is extended to include classes. The new command,that up till now only occurred in the main, is used at other places in the class code as well.

In Class1 a reference variable, say object2, is declared of the type Class2, that can store the addressof an object of type Class2. Reference variables can occur as instance variables, as local variables, andas parameters. As instance variables they are declared at the top of the class description, together with theother instance variables.

61

Page 63: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

In Class1, generally in its constructor, the statement object1 = new Class2(); describes that Class2is instantiated and that the address of the created object is assigned to the variable object1.

As before, the first object is created by instantiating Class1 through main. The other objects are thencreated and connected through the (automatic) execution of the constructor of the coordinating object.

Second, we consider the collaboration: an object calls methods of the objects it has references to. Thisis done through a command of the form 〈reference variable〉.〈method name(. . .)〉. The reference variableholds the address of the object on which the method should be called.

As before, the first (non-constructor) method of the first object is called from main. From this method,other methods, also of other objects, can then be called. Convention: method calls are the only means ofcommunication between objects. This means that variables of objects are not referred to directly in otherobjects (although it is possible in Java).

Note that an object can only call a method of another object if it has a reference to that object. Also notethat when a call from a certain object is terminated, control returns to this object. So collaborating objectsdo so sequentially: several objects simultaneously exist and store data, but only one at the time is active.A call from one object to another is asymmetric. The calling object needs to have a reference to the otherobject; the other object, however, does not need, and in many cases does not have, a reference to the callingobject. Lastly note, that control is passed along references (and passed back against references).

The following example is about a bank that has a safe from which money can be put into an account, whichin turn can be spent. We organize the code and the execution by modeling the bank and the account as twoseparate objects.

class Account {double balance;

Account() {balance = 0;

System.out.println(”Account has been created, contains ” + balance);}

void add100() {balance = balance + 100;System.out.println(”100 has been added to account, now contains ” + balance);}

void take10() {balance = balance − 10;System.out.println(”10 has been taken from account, left is ” + balance);}

}

class BankOne {double safe;Account account; //reference variable to store address

BankOne() {account = new Account(); //creates an account

}

void banking(){safe = 1000;System.out.println(”Safe is filled with ” + safe);

safe = safe − 100; //to mimick transfer to account, money is taken from safeSystem.out.println(”100 is taken from safe, safe now contains ” + safe);

62

Page 64: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

account.add100(); //reference to account used to call add100}

// main instantiates and uses the objectpublic static void main(String[] args){

new BankOne().banking();}

}

Output is:

Account has been created, contains 0.0Safe is filled with 1000.0100 is taken from safe, safe now contains 900.0100 has been added to account, now contains 100.0

The class BankOne describes the declaration of a reference variable of type Account and the instantiationof an object of that type as well as the assignment of the address to the reference variable. The descriptionof the class Account is given separately.

Executing main instantiates an object of the class BankOne. This object has an instance variable that canhold a reference to an object of type (i.e., class) Account. Then the constructor of the BankOne objectcreates an object of the type Account and stores its address in the instance variable account.

The BankOne object calls, from its method banking, methods of the Account object; it uses the addressin the reference variable account to refer to this object.

Note that interaction between objects consists solely of control being passed between methods of theseobjects; as yet no data is transferred between objects.

In the class Account there is no longer one special method where the processing starts. This is becausefrom the viewpoint of an object that uses another object, there are usually several equally important methodsthat process data; in this case the add100 and the take10 method.

13.1.3 Execution model

Every object is labeled with a unique number, prefixed with a #-character to indicate that it is an address.This number is not chosen by the programmer but by the system and has no meaning, except that it isdifferent for different objects. One can not expect that in an actual execution in the computer these exactnumbers are used. When a reference variable holds a reference to an object, the address of this object isput in the box of the variable.

Instead of just one object, several may be drawn in an execution state. Passing control between objectsbehaves as expected: a passive control marker is placed in the calling method and a new method box isdrawn in the called object, where the active marker is placed.

13.2 More objects from one class

We show how more objects from one class can be used to structure a concern into collaborating smallerconcerns.

13.2.1 Aim

To have a structure of classes and collaborating objects. Some of the objects may be of the same class.

63

Page 65: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

13.2.2 Means

To obtain several objects of the same class, the new-command for that class has to be executed severaltimes. To distinguish between these objects, different reference variables need to be used.

As an example, two objects of the class Account are created and the addresses of these objects are storedin two reference variables.

In case multiple objects are instantiated from the same class, in the coordinating object different variablesrefer to each object. We added a variable name to put the name as information in the object itself, forexample to show it on screen, to distinguish between objects of the same class.

class Account {String name;double balance;

Account(String n) {name = n;balance = 0;

System.out.println(”Account ” + name + ” has been created, contains ” + balance);}

void add100() {balance = balance + 100;System.out.println(”100 has been added to account ” + name + ”, now contains ” + balance);}

void take10() {balance = balance − 10;System.out.println(”10 has been taken from account ” + name + ”, left is ” + balance);}

}

class BankMore {double safe;Account account1; //reference variable to store addressAccount account2; //reference variable to store address

BankMore() {account1 = new Account(”FirstAccount”); //creates an accountaccount2 = new Account(”SecondAccount”); //creates an account

}

void banking(){safe = 1000;System.out.println(”Safe is filled with ” + safe);

safe = safe − 100; //to mimick transfer to account1, money is taken from safeSystem.out.println(”100 is taken from safe, safe now contains ” + safe);account1.add100(); //reference to account1 used to call add100

safe = safe − 100; //to mimick transfer to account2, money is taken from safeSystem.out.println(”100 is taken from safe, safe now contains ” + safe);account2.add100(); //reference to account2 used to call add100}

// main instantiates and uses the object

64

Page 66: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

public static void main(String[] args){new BankMore().banking();}

}

Output is:

Account FirstAccount has been created, contains 0.0Account SecondAccount has been created, contains 0.0Safe is filled with 1000.0100 is taken from safe, safe now contains 900.0100 has been added to account FirstAccount, now contains 100.0100 is taken from safe, safe now contains 800.0100 has been added to account SecondAccount, now contains 100.0

13.2.3 Execution model

Nothing really new here.

Example to be provided

Note, that the reference variables account1 and account2 are both in the object of class BankMore andthat the variable name in the objects instantiated from class Account holds the name of each account.

65

Page 67: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 14

Objects with data communication –Method calls with data parameters andreturns

Previously, only control was passed between objects. This chapter considers also communicating datavalues. A centrally organized structure with data communication is shown, other structures are analogous.

14.1 Aim

We want to describe collaborating objects with data communication. To not compromise the idea of havinga structure of relatively independent objects, the data communication is at an abstract level.

14.2 Means

We use methods with data parameters to communicate data values from the calling object to the calledobject. We use data returns to communicate data values from the called object to the calling object.

An important convention in object-oriented programming is to use method calls as the only means tocommunicate between objects. This means that instance variables of objects are not approached directlyfrom other objects. The advantage of this convention is that another implementation (e.g., with a moreefficient data representation, using different instance variables) of a class can be used in place of the originalone without changing the code of other classes. These other classes, namely, do not refer to the instancevariables directly and communicate only via calls to methods of the changed class. If the code of thesemethods is changed to deal with the new data representation, the changes remain within the class.

Note that using the parameter and return mechanisms the communication is two-way, but that the construc-tion is not symmetric: only the calling object needs to have a reference to the called object, but not theother way around. Furthermore, the initiative for the communication lies with the calling object.

An important design principle for object oriented programs is to have no more dependencies, in the formof references, than necessary.

class Account {double balance;

66

Page 68: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Account() {balance = 0;

}

double getBalance(){return balance;

}

void add(int a) {balance = balance + a;}

}

class BankDataParameters {double safe;Account account; //reference variable to store address

BankDataParameters() {account = new Account(); //creates an account

}

void banking(){safe = 1000;System.out.println(”Safe is filled with ” + safe);

safe = safe − 100; //to mimick transfer to account, money is taken from safeSystem.out.println(”100 is taken from safe, safe now contains ” + safe);account.add(100); //reference to account used to call add

System.out.println(”Account now contains ” + account.getBalance());}

// main instantiates and uses the objectpublic static void main(String[] args){

new BankDataParameters().banking();}

}

Output is:

Safe is filled with 1000.0100 is taken from safe, safe now contains 900.0Account now contains 100.0

From the program it can be seen how information goes into the object through the parameters and goes outfrom the object through the return.

14.3 Execution model

Again, nothing new. Data is passed via parameters and return values as described in the chapters onmethods.

67

Page 69: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 15

Objects with reference communication– Method calls with referenceparameters and returns

Previously, only data values were passed between objects. This chapter considers also communicatingreference values. There is no difference in mechanism between the case of data or reference values. Acentrally organized structure with reference communication is shown, other structures are analogous.

15.1 Aim

We want to describe collaborating objects with data communication. To not compromise the idea of havinga structure of relatively independent objects, the data communication is at an abstract level.

15.2 Means

We use methods with reference parameters to communicate reference values from the calling object to thecalled object. We use reference returns to communicate references from the called object to the callingobject.

Thus we respect the important OO convention to use method calls as the only means to communicate valuesof (reference) data between objects. This means that reference variables of objects can not be approacheddirectly from other objects, hence the use of methods.

A reference variable holds the address of an object, which can also be viewed as a pointer. Changing thevalue of a reference variable therefore can be viewed as changing the address value, or, equivalently, asre-directing the pointer in the variable to point to the object with the new address.

An example of passing information to an object, using parameters, is the following.

class Account {double balance;

Account() {balance = 0;

}

void add100() {

68

Page 70: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

balance = balance + 100;}

void show() {System.out.println(”Balance is ” + balance);

}}

class Client {Account account;

Client() {account = new Account(); //makes null reference}

void add100() {System.out.println(”Client adds 100 to account.”);account.add100();}

void setAccount(Account a) { //enable others to set reference to account clientaccount = a;}

}

class BankReferenceParameters {Client client;Account account;

BankReferenceParameters() {account = new Account(); //creates and makes reference to accountclient = new Client(); //creates and makes reference to client

}

void banking(){

System.out.println(”Bank adds 100 to account”);account.add100();

System.out.println(”Bank sets clients reference to banks account.”);client.setAccount(account);

client.add100();account.show();}

// main instantiates and uses the objectpublic static void main(String[] args){

new BankReferenceParameters().banking();}

}

Output is:

Bank adds 100 to accountBank sets clients reference to banks account.Client adds 100 to account.Balance is 200.0

69

Page 71: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

From the program it can be seen how information, here reference information, goes into the object throughthe parameter.

An example of obtaining information from an object, using the return, is the following.

class Account {double balance;

Account() {balance = 0;

}

void add100() {balance = balance + 100;}

void show() {System.out.println(”Balance is ” + balance);

}}

class Client {Account account;

Client() {account = new Account(); //creates and makes reference to private account}

void add100() {System.out.println(”Client adds 100 to account.”);account.add100();}

Account getAccount() { //provides reference to account client to othersreturn account;}

}

class BankReferenceReturn {Client client;Account account;

BankReferenceReturn() {account = null; // makes null referenceclient = new Client(); //creates and makes reference to client

}

void banking(){

client.add100();

System.out.println(”Bank gets clients reference to clients account.”);account = client.getAccount();

System.out.println(”Bank adds 100 to account”);account.add100();account.show();}

70

Page 72: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

// main instantiates and uses the objectpublic static void main(String[] args){

new BankReferenceReturn().banking();}

}

Output is:

Client adds 100 to account.Bank gets clients reference to clients account.Bank adds 100 to accountBalance is 200.0

From the program it can be seen how information, here reference information, is obtained from the objectthrough the return.

15.3 Execution model

Nothing new, models for both examples follow directly. The address value of the account is passed as aparameter, respectively returned, in the same way as any other value.

71

Page 73: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 16

Decomposition scoping

So far, we have only used conventions to limit dependencies between classes. One category of such conven-tions concerns accessibility of variables and methods. Now we introduce language constructs that enableto enforce this accessibility.

16.1 Aim

Decrease dependencies between classes.

16.2 Means

Restrict what classes can see and use from other classes. Methods and variables can be hidden from otherclasses. This way, the other classes can not use the hidden methods and variables and hence do not dependon them.

16.2.1 Visibility modifiers

A visibility modifier is a special word that you write at the start of a declaration of methods, variables, andclasses. Examples:

private double income;

private doube calculateIncome() {...

}

This variable and method are private. They can only be “seen” (i.e., for the method, called, for the variable,used) inside the class where they are declared.

public int score;

public void actionPerformed(ActionEvent e) {...

}

This variable and method are public. They can be seen from any class in the system.

72

Page 74: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Between these two extremes there are two intermediate levels of visibility that have to do with grouping ofclasses into so-called packages.

Packages

A package is a group of classes that belong together and are labeled as such by the programmer. Anexample is java.io, a set of classes that deals with input and output and files. The class Scanner is partof the package java.io. You can declare that the classes in a file belong to package myPackage byputting the line

package myPackage;

at the beginning of the file and putting the classes together in a folder with this name.

When you leave out the line with package, the classes belong to the so-called anonymous package forwhich the name of the folder is irrelevant.

Overview of visibility modifiers from wide to narrow:

• public: no limitations, visible in all classes;

• protected: visible only in classes of the same package and in all subclasses1;

• none (sometimes called ”package”): visible only in the classes of the same package (this is what wehave used mostly so far);

• private: visible only in the same class.

1subclasses are treated in Part III

73

Page 75: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 17

User-built data types – Mutable andimmutable data

In some cases the kind of data that a program uses is not provided as a built-in data type by the language.Then a data type can be programmed: a user-built data type.

17.1 Aim

To make user-built data types.

A built-in data type provides values, variables and operations, as described in chapter ??. Furthermore, abuilt-in data type has several implicit properties that support programming. User-built data types shouldalso have these properties, so we list these explicitly.

1. Variable declaration: naming and creation of variable.

2. Value assignment: both as values for initialization and as terms containing, e.g., variables or methodreturns.

3. No outside change: no change to variable values is possible except through operators of the datatype.

4. Value-equality operator.

5. Instance variable accessibility: methods of an object can act on instance variables.

6. Method parameters: values and expressions (e.g., containing variables) can be used as parameters.

7. Method returns: a value can be returned and can be assigned to variables or used in terms.

17.2 Means

We use the class construct to program a user-built data type and explain how to achieve the properties.

A user-built data type is given as a class and consists of the following items.

1. Values. A value is the data part of an object of the class. The data part is built from variables frombuilt-in data types or previously defined user-built data types (possibly recursively).

74

Page 76: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

2. Operators. An operator is an instance method of the class. The operators are built from operators ofbuilt-in data types or previously defined user-built data types (possibly recursively).

3. Variables. A variable is an instance variable of the class. A variable should, intuitively, store a valueof the user-built data type, i.e., an object. An instance variable in fact holds the address of an object,not the object itself - we handle the consequences below.

Note, that because methods are associated with an object, the form of a binary operator like for comparisonis not of form equals(o1, o2) but rather of form o1.equals(o2). Using a static equation oper-ator, say equals(o1, o2), would be against the idea that static operators concern class data, in staticvariables, rather than object data.

A value is, intuitively, stored in only one variable at the time. Note, that operators can change the valuesthat variables store. Each value can only be stored in one variable, so it does not make a difference whethera new value stored is a variable through changing the old one or through replacing the old one.

We discuss how to achieve the properties we identified.

1. Variable declaration. Variable declaration provides a name for the variable and and the creation ofan object to hold the value. See the next item for details about value assignment. Assignment of adefault value is optional and can be effected through a constructor without parameters. (If this is notprovided, the variables from the built-in types of which the new data type is built-up will be assignedthe default values as in the built-in data types.) Initialisation with a chosen value is also optional andcan be effected through a constructor with parameters.

2. Value assignment. We distinguish values and terms containing, e.g., variables or method returns.Because the user-built data type stores values of a new form, which are not part of the language,in variables, these values have to be build-up from part-values that belong to the data types fromwhich the user-built data type is constructed. If these are values from built-in types they can beprovided directly as part-values, if not, they can be only provided as stored in variables. We providea method assign with two implementations, distinguished by overloading. One enables to assignpart-values, the other to assign values that are already stored in variables of the user-built type.

3. No outside change. This concerns the fact that a variable holds the address of an object rather thanthe object itself. Because in a data type changes to a variable value (the object) should only occurthrough user-built data type operators some measures have to be taken to ensure this. There are twoissues.

(a) No outside change at the variable level should occur except through the user-built data typemethods. Variables now are objects, the variable name contains the address of the object. Toensure that a change to one variable does not cause a change to another one, aliasing has to beprevented: only one name should hold the address of a variable. This is achieved by disallowingthe use of =, which affects the address, and replacing it by assign, which affects the storedvalues.

(b) No outside change to parts should occur except through the user-built data type methods. Vari-ables may have user-built data types as parts. To ensure that these are not changed, there shouldbe no references from outside the user-built data type to these parts. This is enforced by makingthe internal variables that refer to such parts private in the user-built data type. Note, that thisdoes not prevent pointers from (parts of) one object in the user-built type to (parts of) anotherobject of this type: this should simply not be programmed in the user-built type.

4. Value-equality operator. The equality operator of the user-built data type should compare values, notadresses. Therefore, provide a method o1.equals(o2) that compares the stored values in o1 ando2 and returns true if they are the same. Comparison is achieved through the equals method;the use of == on variables of the user-built data type is disallowed.

5. Instance variable accessibility: methods of an object act on instance variables. Achieved.

75

Page 77: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

6. Method parameters: values and variables can be used. Achieved for variables. If so desired, over-loading allows to write methods that also take part-values that together make up a value.

7. Method returns: a value is returned and can be assigned to variables or used in terms. Achieved.Note, that to store a return value in a variable, assign is to be used, not the disallowed =

8. Partial mutability: changes to part of a value. Achieved. Methods can be written that change parts ofa variable; this is quite efficient, as this also means only a partial change to the object that implementsthe variable.

Because the variable contents can be changed, this is called the mutable approach. Summarizing, forprogramming with a mutable user-built data type the restrictions are the following

1. assign for assignment (in stead of =).

2. equals for comparison (in stead of ==).

There is another option to ensure no outside change. The idea is again that a value is an object and thestored value is the stored part-values, but rather than preventing that two variables hold the same object, weprevent that that object gets changed. This is done by ensuring that for each new value, a different objectis created. Then = can be retained for assignment.

Because the contents can not be changed (another object is used instead), this is called the immutableapproach. Summarizing, for programming with a immutable user-built data type the restrictions are thefollowing.

1. equals for comparison (in stead of ==).

Note, that inside the data type quite different things happen for mutable/immutable, e.g. regarding instancevariables, but that outside the effect is the same. Also note, that it is still possible to define part-valueoperations, but that, as in the immutable case also for the partial-changes a whole new object is created,this is not efficient anymore.

In the example, we restrict ourselves to assignment and equality operators.

Example mutable approach

We built a data type Rat that supports rational numbers.

import javax.swing.∗;class Rat {

private int n;private int d;

public Rat () {n = 0;d = 1;}

public Rat (int n, int d) {if (d == 0) {

JOptionPane.showMessageDialog(null, ”Denominator 0 is not allowed”);} else {

this.n = n;this.d = d;}}

public Rat (Rat r) {

76

Page 78: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

n = r.n;d = r.d;}

public void assign (int n, int d) {//enables assignment through part−values (int)if (d == 0) {

JOptionPane.showMessageDialog(null, ”Denominator 0 is not allowed”);} else {this.n = n;this.d = d;}}

public void assign (Rat r) { // enables assignment Rat valuen = r.n;d = r.d;}

public Rat add(Rat r) {Rat sum = new Rat();

sum.n = n ∗ r.d + r.n ∗ d;sum.d = d ∗ r.d;

return sum;}

public void simplify() { // enables to simplify a Ratint i = 2;

while (i <= (int) (Math.min(n, d))){if ((n%i == 0) && (d%i == 0)) {

n = n/i;d = d/i;}else{

i = i+1;}

}}

public boolean equalsClever(Rat r){ // works for both immutable and mutableboolean e;

e = (this.n ∗ r.d ==this.d ∗ r.n);return e;

}

public boolean equals(Rat r) { // only works for mutableboolean e;Rat s = new Rat();Rat t = new Rat();

s.assign(this);s.simplify();

t.assign(r);t.simplify();

e = ((s.n == t.n) && (s.d == t.d));return e;

77

Page 79: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

}

void draw() {if (d == 1){

System.out.println(n);}else{

System.out.println(n + ”/” + d);}}

}

class RationalDemoMutable {Rat r1 = new Rat();Rat r2 = new Rat(6, 4);Rat r3 = new Rat(r2);Rat r4 = new Rat();Rat r5 = new Rat();

void demo() {r4.assign(2, 7);r5.assign(r4);

System.out.println(”r1, r2, r3, r4, r5 are, respectively:”);r1.draw();r2.draw();r3.draw();r4.draw();r5.draw();

System.out.println(”r2 equals r3 is: ” + r2.equals(r3));System.out.println(”r2 equalsClever r3 is: ” + r2.equalsClever(r3));

System.out.println(”Simplifying r2 makes r2:”);r2.simplify();r2.draw();

System.out.println(”Adding r2 to r3, storing in r1, makes r1:”);r1.assign( r2.add( r3 ));r1.draw();

System.out.println(”r1 equals r3 is: ” + r1.equals(r3));System.out.println(”r1 equalsClever r3 is: ” + r1.equalsClever(r3));

System.out.println(”Simplifying r1 makes r1:”);r1.simplify();r1.draw();}

// main instantiates and uses the objectpublic static void main(String[] args) {RationalDemoMutable rationalDemoMutable = new RationalDemoMutable();rationalDemoMutable.demo();}}

Output:

78

Page 80: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

r1, r2, r3, r4, r5 are, respectively:06/46/42/72/7r2 equals r3 is: truer2 equalsClever r3 is: trueSimplifying r2 makes r2:3/2Adding r2 to r3, storing in r1, makes r1:24/8r1 equals r3 is: falser1 equalsClever r3 is: falseSimplifying r1 makes r1:3Press any key to continue...

Example immutable approach

import javax.swing.∗;class Rat {

private int n;private int d;

public Rat () {n = 0;d = 1;}

public Rat (int n, int d) {if (d == 0) {

JOptionPane.showMessageDialog(null, ”Denominator 0 is not allowed”);} else {

this.n = n;this.d = d;}}

public Rat (Rat r) {n = r.n;d = r.d;}

public Rat add(Rat r) {Rat sum = new Rat();

sum.n = n ∗ r.d + r.n ∗ d;sum.d = d ∗ r.d;

return sum;}

public Rat simplify() { //simplifies Rat value; result assignment necessaryRat simple;int n;

79

Page 81: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

int d;

n = this.n;d = this.d;

int i = 2;while (i <= (int) (Math.min(n, d))){

if ((n%i == 0) && (d%i == 0)) {n = n/i;

d = d/i;}else{

i = i+1;}

}simple = new Rat(n, d);return simple;}

public boolean equalsClever(Rat r){ // works for both immutable and mutableboolean e;e = (this.n ∗ r.d ==this.d ∗ r.n);return e;

}

public boolean equals(Rat r) { // only works for immutableboolean e;Rat s = new Rat();Rat t = new Rat();

s = this;s = s.simplify();

t = r;t = t.simplify();

e = ((s.n == t.n) && (s.d == t.d));return e;

}

void draw() {if (d == 1){

System.out.println(n);}else{

System.out.println(n + ”/” + d);}}

}

class RationalDemoMutable {Rat r1 = new Rat();Rat r2 = new Rat(6, 4);Rat r3 = new Rat(r2);Rat r4 = new Rat();Rat r5 = new Rat();

void demo() {r4 = new Rat(2, 7);

80

Page 82: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

r5 = r4;

System.out.println(”r1, r2, r3, r4, r5 are, respectively:”);r1.draw();r2.draw();r3.draw();r4.draw();r5.draw();

System.out.println(”r2 equals r3 is: ” + r2.equals(r3));System.out.println(”r2 equalsClever r3 is: ” + r2.equalsClever(r3));

System.out.println(”r2.simplify(); leaves r2 untouched:”);r2.simplify();r2.draw();

System.out.println(”r2 = r2.simplify(); makes r2:”);r2 = r2.simplify();r2.draw();

System.out.println(”Adding r2 to r3, storing in r1, makes r1:”);r1 = r2.add( r3 );r1.draw();

System.out.println(”r1 equals r3 is: ” + r1.equals(r3));System.out.println(”r1 equalsClever r3 is: ” + r1.equalsClever(r3));

System.out.println(”Simplifying r1 makes r1:”);r1 = r1.simplify();r1.draw();}

// main instantiates and uses the objectpublic static void main(String[] args) {RationalDemoMutable rationalDemoMutable = new RationalDemoMutable();rationalDemoMutable.demo();}}

Output:

r1, r2, r3, r4, r5 are, respectively:06/46/42/72/7r2 equals r3 is: truer2 equalsClever r3 is: truer2.simplify(); leaves r2 untouched:6/4r2 = r2.simplify(); makes r2:3/2Adding r2 to r3, storing in r1, makes r1:24/8r1 equals r3 is: false

81

Page 83: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

r1 equalsClever r3 is: falseSimplifying r1 makes r1:3Press any key to continue...

The data type String as supplied by Java is in fact an immutable type String.

17.3 Execution model

to be provided

82

Page 84: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 18

User-built data structures – Lessrestricted mutable data

*** Not required for 2008 ***

Idea: in practice, rather than the beautiful user-built data types, data structures are required and used thatdo not prevent aliasing. For example: arrays.

18.1 Aim

We want data structures that are like data types but can be shared between different users, i.e., allowaliasing.

18.2 Means

We use the user-built data type idea but drop the requirements that prevent aliasing. This leaves from thelist of required properties from 17 the following.

1. Variable declaration: naming and creation of variable. OK.

2. Value assignment: both as values for initialisation and as terms containing, e.g., variables or methodreturns. In case of arrays = for the array variable, ALLOWING ALIASING, = for elements of prim-itive type, preventing part-aliasing, = for elements of object-type, ALLOWING PART-ALIASING.

3. No outside change: no change to variable values is possible except through operators of the datatype. Lost.

4. Value-equality operator: equals necessary.

5. Instance variables accessibility: methods of an object can act on instance variables.

6. Method parameters. Lost, address is passed.

7. Method returns. Lost, address is returned.

This means that a data structure can be obtained by using the mutable data approach from 17, but allowingthe assignment and comparison.

83

Page 85: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

1. = for assignment (in stead of assign).

2. == for comparison (in stead of equals).

84

Page 86: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 19

Object recursion

In chapter ??, data duplication required for solving problems via method recursion was achieved dupli-cating the local variables in the method. The same idea is now applied to data in instance variables:duplicating objects using object recursion. The motivation is, that data in local variables cannot be used byother objects whereas data in instance variables can.

An important use is defining dynamically changing user built data types/structures.

An example is a linked list of objects. The linked list is then defined recursively, the resulting data structuregrows when nodes, as required by storage demands, are added to the list and shrinks when nodes aredeleted.

85

Page 87: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

Chapter 20

Class information – Class object

So far, data storage and manipulation have been done through objects, instantiated from classes. Some dataand manipulation is at the level of the class rather than the objects instantiated from it. For this, the classobject is used: it is an object that is created when the file that the class definition is in is executed, i.e., evenbefore any instance object is created.

20.1 Aim

To have a place for data storage and manipulation that is at class level rather than at the level of individualobjects.

20.2 Means

Apart from the description in the class of variables and methods that get instantiated when an object isinstantiated from that class, static variables and methods can be described. Static variables and meth-ods do not belong to any of the objects that are explicitly instantiated from the class, but to a separateclass object that is implicitly, automatically, instantiated when a class is executed. The class object is notidentified by a reference, but by the name of the class it belongs to. Static methods are called through<classname>.<methodname>. main is a special case of such a static method; special in the sense that itis called automatically when the class is executed. Also, this is the only way main can be called (“listencarefully, main only gets called once”).

Example

We want to keep count of the number of animals instantiated. This is clearly not the task of any individualanimal. Also, as the aim is to keep count of all animals created, it would not be correct to make this thetask of the farmer, as, for example, there might be more farmers, each instantiating cows. It is typically atask at the level of the Animal class. We extend the animal class accordingly.

class Animal{static int numberOfAnimals;

static {numberOfAnimals = 0;}

static int getNumberOfAnimals(){return numberOfAnimals;

86

Page 88: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

}

int stomach;

Animal(){stomach = 0;

numberOfAnimals = numberOfAnimals + 1;}

void eat(){stomach=stomach+1;// 1 meal eatenSystem.out.println(”Stomach contains after meal ” + stomach);}}

public class FarmerStatic{Animal animal1;Animal animal2;

void farm(){System.out.println(”Number of animals is ”+ Animal.getNumberOfAnimals());

animal1 = new Animal();System.out.println(”Number of animals is ”+ Animal.getNumberOfAnimals());

animal2 = new Animal();System.out.println(”Number of animals is ”+ Animal.getNumberOfAnimals());}

// main instantiates and uses the objectpublic static void main(String[] args){

FarmerStatic farmerStatic = new FarmerStatic();farmerStatic.farm();}}

The following new lines occur.

static int numberOfAnimals keeps the counting information.

static is the constructor for the class object Animal. By rule it is named static.

numberOfAnimals = numberOfAnimals + 1; in the constructor of Animals increases the an-imal count by 1 each time a new object is instantiated from Animal.

getNumberOfAnimals is the getter method that enables to get the value of the counter.

20.3 Execution model

Thus far, we only modeled the objects that were instantiated from a class. We extend the model with theclass objects. Because class objects are not identified by a reference, we put the name of the class theybelong to to them. Note, that the main is also a static method and therefore belongs in the class object: Wesketch the model.

Example

87

Page 89: Object Oriented Programming – with Javarkuiper/2Z820/book12.pdf · Object Oriented Programming – with Java Kees Huizing Ruurd Kuiper December 24, 2008. Preface Computers are used

FarmerStatic Animal----------------------------------------- ------------------------|main(){ | |numberOfAnimals; |

|-| ... farmerStatic = new FarmerStatic();| | || | farmerStatic.farm(); | |static{...} || |} | | || ---------------------------------------- - |getNumberOfAnimals(){}|| ------------------------|| |--------------------------|v | v---------| | ------------ ------------|animal1;|-|->|stomach; | |stomach; ||animal2;|-| | | | || | |Animal(){}| |Animal(){}||farm(){}| | | | |---------- |eat(){} | |eat(){} |

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

NB The farmerStatic object has referencs to both animal objects animal1 and animal2. There-fore, the farmerobject can call the methods of the animal objects. Static variables and methods of a class,belonging to the class object of that class, can be accessed and called without references being needed. Forexample, the constructor Animal that belongs to the instantion animal1 can update the static variablenumberOfAnimals in the class object for Animal. Also, the static method getNumberOfAnimalsin the class object for Animal can be called from the method farm in the object farmerStatic.

88