Introduction to Programming in Java - Volume One

 Sebastian Danicic 


Contents


Introduction

How To Study This Course

This is an introductory programming course in Java. It is intended for students with no previous programming experience. The only way to learn to program is to write lots and lots of programs!

The text is filled with examples and small exercises with solutions. It is essential that you attempt each exercise before looking at the solution in the appendix. After a serious attempt at solving the problem, you should carefully study the solution given. All the examples and exercises given in the text and other useful information will be provided on the web site at http://www.mcs.gold.ac.uk/~ mas01sd/externalcis109.

Useful Java Links

Here is a list of web sites that may help you to learn Java.
java.sun.com
How to Think Like a Computer Scientist (book)(http://greenteapress.com/thinkapjava/)
Sun Java Tutorial http://java.sun.com/docs/books/tutorial/
http://www.ibiblio.org/javafaq/javatutorial.html
http://www.ibiblio.org/javafaq/course/
http://chortle.ccsu.ctstateu.edu/cs151/cs151java.html
A List of lots of Tutorials
Download Java - http://java.sun.com/downloads/

Finding the Example Java Programs on the Web site

In the text we tell you where to find each program. For example Lecture1/Silly3.java is a file called Silly3.java in a directory(folder) called Lecture1. The actual program can therefore be downloaded from http://www.mcs.gold.ac.uk/~ mas01sd/externalcis109/Lecture1/Silly3.java.

Exercises with no Solutions

At the end of some chapters there are some exercises with no solutions. It is suggested that these may be suitable for assignments.

Multiple Choice Questions

In the appendix of both volumes 1 and 2, there are some multiple choice questions with solutions.

Exam Questions

In the appendix B of volume two is a complete exam paper and some further sample questions with solutions.

Topics

The first volume of the Java Subject Guide considers many of the basic concepts of programming. These include: In the second volume, we cover more advanced, but essential topics in Object Oriented Programming. These include:

Books

I refer to a number of books throughout the text, specifically at the beginning of each chapter. Details of these books can be found in the bibliography in Section  1.6. A good book to get to started with is How to Think Like a Computer Scientist by Allen B. Downey. It is free (http://greenteapress.com/thinkapjava/) under the Gnu Free Documentation Licence. Thank you very much Allen B. Downey. I strongly recommend that you read chapters 1 to 13 of the book and do all its exercises.

Compiling and Running Java Programs

Before you can usefully study this course, you need Java installed on your computer. You need
  1. Java 2 Platform, Standard Edition (J2SE) from http://java.sun.com/j2se/1.4.1/download.html. and
  2. Sun Java 2 SDK Documentation from http://java.sun.com/docs/.

If you are using Microsoft Windows you should also download and install TextPad Programmer's Text Editor from http://www.textpad.com for editing compiling and running your java programs. You may prefer to use BlueJ from http://www.bluej.org/.

Please see

http://www.mcs.gold.ac.uk/~ mas01sd/externalcis109
for more information on how to do this.

Preliminaries

Before starting to learn Java, you need to know a few things about using a computer. These are:

It is important that you know how to create directories and subdirectories, copy, delete and move files.

What you will be able to do having completed this subject guide

Having completed this subject guide you will understand programming concepts sufficiently to be able to write Java applications to solve simple programming problems. Topics covered include:

Bibliography

1
David Arnow and Gerald Weiss.
Introduction to Programming using Java.
Addison-Wesley, 1998.

2
Judith Bishop.
Java Gently - Third Edition.
Addison-Wesley, 2001.

3
Quentin Charatan and Aaron Kans.
Java - In Two Semesters.
McGraw-Hill, East London Business School, 2002.

4
Deitel and Deitel.
Java - How to Program.
Prentice Hall International, 2000.

5
Allen B. Downey.
How to Think Like a Computer Scientist - Java Version.
Green Tea Press, 2003.

6
David Flanagan.
Java in a Nutshell.
O'Reilly, 1999.

7
John R Hubbard.
Schaums:OuTlines - Programming with Java.
McGraw-Hill, University of Richmond, 1998.

8
Kenneth A Lambert and Martin Osborne.
Java - A Framework for Programming and Problem Solving.
Brookes-Cole, 2002.


Your First Java Program

Learning Objectives

Having worked on Chapter 2 you will have:

Main Reading

Other Reading

Directory Structure for the Course

I recommend that you create a directory (folder) for each chapter in the book. See Figure 2.1.

Figure 2.1: Directory Structure
\begin{figure}\begin{verbatim}<your home directory or C:>
\vert
___________...
.....
\vert
__________
\vert \vert
HelloWorld.java\end{verbatim}\end{figure}

Throughout the text, we give suggested file names for each program. We put these file names in square brackets. For example, we write [Lecture1/HelloWorld.java]. This means that on http://www.mcs.gold.ac.uk/~ mas01sd/externalcis109 the program can be found in a file called HelloWorld.java in a directory(folder) called Lecture1. I suggest that you also put your first Java program HelloWorld in a file called:
HelloWorld.java
in a directory(folder) called:
Lecture1
in the directory called

 
javacourse

If you do not put the programs where we suggest you may end up with problems since other programs may be looking in particular place for another program.

CLASSPATH

There is a system variable called CLASSPATH that causes problems to beginners in Java.

This variable contains the set of directories(folders) that the Java system looks for classes (you will learn about classes later in the course).

MS-Windows users should add the following line to the file c:\autoexec.bat:

set CLASSPATH=javacourse;\%CLASSPATH%;.
Don't forget the dot at the end.

Unix users should type:-

CLASSPATH=$HOME/javacourse:$CLASSPATH
export CLASSPATH
Read the first chapter of [7] for more details.

Editing, Compiling and Running your First Program

First, either type or download the example [Lecture1/HelloWorld.java]

If you are using Microsoft Windows, I suggest you do this by using Textpad. Having typed it in compile it. To do this using Textpad2.1, you click on compile java under the tools menu. If you have typed it in correctly, nothing will happen. If you have not typed it correctly you will get some error messages from the compiler. If you get error messages, then check that every character you have typed is exactly as it appears in the text. If you still get errors, then try reading Section 2.7. This may help you to find your errors. When you have done this, then compile your program again. Repeat this process until you have no errors and then run your program.

To run your program using Textpad2.2, you click on run java application under the tools menu.

If you are using MS Windows but do not have Textpad, you can compile and run your Java programs from the DOS prompt. Type javac HelloWorld.java at the command line to compile your program and type java HelloWorld to run it.

What happens when you run the program? [Lecture1/Henry.java]

.

Summary

There are three phases in writing programs:
  1. Editing the program
    1. In Windows use Textpad.
    2. in Unix use Nedit.
  2. Compiling the program
    1. In Windows, click on tools followed by compile in Textpad.
    2. in Unix (or Dos) type javac followed by file name. e.g. javac HelloWorld.java.
  3. Running the Program
    1. In Windows, click on tools followed by run Java application in Textpad.
    2. in Unix (or Dos) type java followed by class name. e.g. java HelloWorld.

Analysis of the HelloWorld Program

We now analyse various aspects of the program: [Lecture1/HelloWorld.java] in more detail.


Comments

The very first line // HelloWorld is just a comment. After two forward slashes // you can write anything you like on that line. It will be ignored by the compiler and have no effect on what your program does when it runs. Comments are very important since when your programs get big the comments help to remind how and why you wrote your programs the way you did.

The Other Way of Doing Comments

In section 2.6.1 we saw one way of doing comments. In the program [Lecture1/HelloWorld2.java]

we have included some text between /* and */. This is how we do comments if we want to last more than one line. We can think of /* as meaning ``start comment'' and */ as meaning ``end comment''. It is essential that from the beginning of your programming ``life'' you get into the habit of commenting your programs.

The Program Heading

The next line
class HelloWorld
tells us the name of the program. All Java programs have a class statement very near the beginning. Normally because our program is called HelloWorld we store it in a file called
 
 HelloWorld.java
This is not essential however. We could have called the file anything.java and it would still have worked. Because of the program heading, after we compile it we will end up with a file in the current directory called HelloWorld.class.

Java is Case-Sensitive

This means that it matters if we use small or capital letters. If we had written CLASS instead of class the compiler would give us an error message and we would have to correct it before we would be allowed to run the program. Try it and see!

The Program Body

The rest of the file is the body of the program.

Matching Brackets

It starts with an open curly bracket { and ends with a closing curly bracket }. When you write programs, brackets must always match: For every opening bracket there must be a corresponding closing bracket.

The Main Method

All Java programs have what is called `a main method' which always starts,
public static void main( String[ ] args)
This line is called the heading of the main method. The code inside the next pair of open and closing curly brackets is called the body of the main method.
{
   System.out.println("Hello World");
}

This is where we put what we actually want our Java program to do when we run it. In this example the body of our main method consists of a single statement. In this case, the statement is a call to a method2.3whose name is System.out.println. We have passed this method the argument "HelloWorld". When the System.out.println method is executed the string passed to it is `printed' on the computer screen.

Strings

A string is a sequence of characters, with a double quote at either end. Examples of strings are


Some Compiler Error Messages

In Java all statements end with a semi-colon ;. If we leave the semi-colon out the compiler will complain! Try compiling the program: [Lecture1/bad.java]

When we try to compile this program we get an error message:-

bad.java:6: ';' expected.
        System.out.println("Henry")
                                   ^
1 error
The Java compiler tells us that it got to line 6 when it realised that there was an error. In fact the error is on line 5. It puts a little caret ^ pointing at where the error might be. Another common error is to have the class name different from the file name. This is only a problem if we have the word public2.4before class. If we compile the program [Lecture1/bad1.java]

we will get a compiler error message saying:-

bad1.java:2: Public class Bad1 must be defined in a file called "Bad1.java".
public class  Bad1
              ^
1 error

Correcting Compilation Errors

If your programs do not conform exactly to the rules for the syntax of Java, errors will appear when you try to compile your program. When you start writing programs you will have lots of compilation errors. The best way to correct them is to just correct the first one and then recompile. This is because the first error sometimes makes the compiler think there are lots of other errors which are not really there. Note: Just because your program has no compilation errors it doesn't mean it will do what you want it to do!

Exercise - Printing Your Own Name

Create a new program that prints your own name instead of Henry's. Don't forget to compile and run the new program. [Lecture1/Name.java]

Notice that the first program, HelloWorld.java starts with

  class HelloWorld
and the second program, Name.java starts with
  class Name

Notice that there is a file in your directory called HelloWorld.class.

Exercise

Delete the file called HelloWorld.class. Now try to run it. What happens? answer:

Print your Name Three Times

Write a Program that prints your name 3 times. Once per Line. [Lecture1/answers/three.java]

Print your Name Ten Times

Write a program that prints your name 10 times. [Lecture1/answers/ten.java]

Print your Name a Hundred Times

Write a program that prints your name 100 times.

Print your Name a Thousand Times

Write a program that prints your name 1000 times. In Chapter 7 on For Loops you will learn a shorter way of programming this!

print vs. println

As you have seen, every time we call the System.out.println method it prints its actual parameter (the bit in the brackets after the word System.out.println or and then goes on to the next line. The output to the program above is
Sebastian Danicic
Sebastian Danicic
Sebastian Danicic
If we had written:-
public class Name
{
	public static void main(String[] args)
	{
		System.out.print("Sebastian Danicic");
		System.out.print("Sebastian Danicic");
		System.out.print("Sebastian Danicic");
	}
}
The output would have been:
Sebastian DanicicSebastian DanicicSebastian Danicic
So, as we have seen, System.out.println prints its argument followed by a newline character which makes the cursor go onto the next line.

Summary

Having worked on Chapter 2 you will have:

Further Exercises - No Solutions

  1. Write a program that Prints out your name and address.
  2. Write a program that prints a big A like this:
                # 
                # 
                ###
                ######
                #    #####
                          #### 
                          ## #### 
                          ##     #####
                          ##         ##### 
                          ##            #####
                          ##          ############
                          ##      ##############
                          ##   ##############
                          ############## 
                #      ###############
                #  ###############
                #############
                ##########
                ######
                ##
                #
    


Arithmetic Expressions

Learning Objectives

Having worked on Chapter 3 you will have:

Reading

Arithmetic Expressions are a way of telling a computer to do calculations. Compile and run the program [Lecture1/OnePlusOne.java]

1+1 is an example of an arithmetic expression. When we call System.out.println(1+1) the arithmetic expression 1+1 first evaluated to produce 2. When we run this program it prints 2.

Quotes make all the difference

What is the output of [Lecture1/QuoteOnePlusOne.java]

Answer:- 1+1 The quotes round 1+1 make it into a string. Without the quotes 1+1 is an integer. As we will see in Figure 4, Integers are called int in Java.

Multiplication is Written with an Asterisk *

I am going to America and taking 250 pounds sterling with me. I want to know how much this is in US Dollars. There are 1.51 dollars in each pound. [Lecture1/PoundstoDollars.java]

As you can see, 1*2 means 1 times 2.


Division is Written with a Forward Slash: /

Write a program which prints out how many pounds there are in one dollar assuming 1.51 dollars in a pound. [Lecture1/DollarsToPounds.java]

As you can see, 1/2 means 1 divided by 2.

Converting Centigrade to Fahrenheit

Here is a program to print a Centigrade to Fahrenheit conversion table where $x$ degrees centigrade is $32 + x*9/5$ degrees Fahrenheit. [Lecture1/CentigradeToFahrenheit.java]

The output of this program is


More About Division

Integer Division

If both the numerator and denominator are integers then Java does integer division. [Lecture1/div1.java]

prints 1 when we run it. This is because

Notice also that 3/(-2) would give -1.

The general rule for integer division is to work out the largest integer which is less than the absolute value of the expression.

Non -Integer Division

To represent real numbers we simply include a decimal point and at least one digit to the right of the decimal point. For example 1.0 or 1.51. If either the numerator or denominator are real the division is `what we would expect'. The following programs all print 1.5

[Lecture1/div2.java]

[Lecture1/div3.java]

[Lecture1/div4.java]


Concatenating Strings

As well as for adding numbers, the plus sign can be used for concatenating strings. For example "Hello" + "fred" gives "Hellofred"
and "Hello " + "fred" gives "Hello fred" (Note the space at the end of the first String).
The program DollarsToPounds.java in section 3.5 could have been written in a neater way as:- [Lecture1/BetterDollarsToPounds.java]


Exercises

Pence to Dollars

Write a program that works out how many pence in 250 dollars [Lecture1/DollarsToPence.java]

Height of Everest in Inches

Write a program that works out the height of Mount Everest in inches assuming that Everest is 29124 feet high. There are 12 inches in one foot. [Lecture1/Everest.java]

Inches to the Moon

Write a program that works out how many inches between the earth and the moon. Assume the distance from the Earth to the Moon is 251,000 miles. There are 3 feet in one yard and 1760 yards in a mile. [Lecture1/Moon.java]

Height of Everest in Millimetres

Write a program to work out the height of Mount Everest in millimetres. Assume there are 2.54 centimetres in an inch and 10 millimetres in a centimetre. [Lecture1/Everest1.java]

Ten Times Table

Write a program that prints out the 10 times table. [Lecture1/TenTimesTable.java]

One Hundred and Thirty Seven Times Table

Write a program that prints out the 137 times table. [Lecture1/OneThreeSevenTimesTable.java]

Operator Precedence

What is the output of [Lecture1/Precedence.java]

The answer is 6. This is because when the system works out 5*1+1 it does the multiplication before it does the addition. We write ``times binds more tightly than plus'' or . ``* binds more tightly than +''.

Brackets

How would we make the system do the plus first? answer:use brackets. 5*(1+1) would give 10.

Exercises

Write some programs to test the order in which expressions are evaluated in Java.

Forget About Operator Precedence!

You never need to remember operator precedence. Just use brackets to get the expression you want. Expressions inside brackets are always calculated first. For example (3+5)*2 evaluates to 16.

See Java in a Nutshell page 33 for a list of all operators. or [4] page 53.

Further Exercises(No Solutions provided)

To make the following programs work, you have to write the numbers as real numbers with a decimal point. That is for two write 2.0. For one million write 1000000.0 etc. This will be explained in Volume 2. Write programs to:-
  1. Work out the number of seconds in 365 days.
  2. Work out the number of months in a millennium (1000.0 years).
  3. Work out the number of bits in a megabyte. (A byte is 8 bits and a megabyte is $2.0^{20}$ bytes) To work out $2.0^{10}$ for now simply write

    \begin{displaymath}2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0\end{displaymath}

    Eventually you will learn a better way of achieving this!
  4. Work out the number of bits in a gigabyte. (A gigabyte is $2.0^{10}$ megabytes)
  5. Assume light travels 186,000.0 miles a second, and the star Proxima Centauri is 4.2 light years away. My snail goes at 30.0 inches an hour. How many years will it take my snail to get to Proxima Centauri and back?
  6. My snail eats two grams of lettuce a day. How many metric tons of lettuce will it have to take with it to Proxima Centauri? There are a million grams in a metric ton.

Summary

Having worked on Chapter 3 you will have:


Variables

Learning Objectives

Having worked on Chapter 4 you will have:

Reading

Introduction

Variables are very important in all programming languages. Variables are used to store values that we have calculated. In order to use a variable, we first declare it with a variable declaration and then store a value in it using an assignment statement.

Consider [LectureVariables/Hello1.java]

Declaring Variables

In Hello1.java, first we declare the variable called s. The value 124 is then stored in this variable s. The contents of the variable s i.e 124 will be printed. When we run this program we will see
124
on the screen of our computer. We will not see s appearing on the computer screen. s is the name of the variable, not its contents.

Whenever we declare a variable we must give its type. The type of s, in this case, is int. This means that the only sorts of things we can store in s are integers.

Other Types

Other basic types (usually called primitive types) in java include
boolean
char
byte
short
long
float
double
Variables of different types are for holding different sorts of values.

Examples of legal declarations are:

boolean b; //A boolean variable called b.
char c,d; //Two char variables called c and d.
byte k; //A byte variable called k.
short silly; // A short variable called silly.
int m,n,p; //Three int variables called m,d and p.
long lilliput;// A long variable called lilliput.
float f1,g1,h; //Three float variables called f1,g1 and h.
double q,r; //Two double variables called q and r.

Variable Names

Any sequence of letters and digits that starts with a letter is a legal variable name. Examples of legal variable names are <4779>>tex2html_deferred<< There is absolutely no difference in the behaviour of
int x = 1543;
System.out.print(x);
and
int bananasplit = 1543;
System.out.print(bananasplit);
and
int BorisYeltsin54 = 1543;
System.out.print(BorisYeltsin54);
In each of the three program fragments we store the integer 1543 in a variable and then print out the contents of the variable. In all three
1543
will be printed out.

Important Fact about Replacing Variable Names

If we replace every occurrence of a variable name in a program by another that doesn't occur already in the program then the program will behave exactly the same.

Exercise - Boris Yeltsin's Pet Rabbit

Rewrite all the programs in this chapter that contain a variable in such a way as to not change their behaviour but so they all have a variable called BorisYesltsinAndHisPetRabbit.
[LectureVariables/Hello1Boris.java]

Exercise

What is the output of [LectureVariables/Hello1Boris.java]

If you think the answer is BorisYesltsinAndHisPetRabbit then please re-read this chapter. If you think the answer is 1543, then carry on reading!

Wrong Assignments

Consider the program [LectureVariables/WrongType.java]

When we try to compile this program we get the following error message:

WrongType.java:7: Incompatible type for =. Can't convert int to java.lang.String.
          s = 1;          // assignment statement
            ^
1 error
This is because we are trying to assign a value of 1 to a String variable but 1 is not a String, but 1 is an integer (called int in Java). If we put double quotes round the 1 i.e. "1" it becomes a String.

Now consider Hello2.java

This program prints 1568

So does Hello3.java

So does Hello4.java

Executing Assignment Statements

When an assignment is executed, first the expression on the right hand side is calculated and the result is put into the variable on the left hand side of the assignment. So in Hello4.java when executing the assignment statement s = s + 25; first the expression s + 25 is calculated to give 1568. The result is then stored in the variable s.

A Common Mistake

Consider [LectureVariables/Hello5.java]

What does it output? The answer is s. It does not print 30 because we are asking the system to print the String value "s" not the value contained in the integer variable s. It is very important that you understand this! The "s" is NOT the same as s. Again, the quotes make all the difference.


Another Common Mistake

A common mistake made by beginners is to declare the same variable more than once inside the main method (or as we shall see later, in any method). Java does not allow this.

Consider [LectureVariables/Dec2.java]

When we try to compile this program we get:-

Dec2.java:6: Variable 's' is already defined in this method.
	     int s = 53;
	         ^
1 error

Assigning to the same variable more than once

It is allowed to assign to the same variable more than once so the following program compiles with no errors.

[LectureVariables/TwoAssign.java]

Th output of the program above is

26
because the value 1453 stored in variable s has been overwritten by the value 26. A new assignment to the same variable always causes the previous value in that variable to be thrown away and replaced with the new value.

A Common Mistake - Forgetting to Declare Variables

A very common mistake is to forget to define variables.

See, for example, [LectureVariables/Undeclared.java]

The compiler complains with

Undeclared.java:5: Undefined variable: s
          s = 55;
          ^
Undeclared.java:6: Undefined variable: s
          System.out.println(s);
                             ^
2 errors
The solution is simply to add the declaration int s; as in [LectureVariables/Declared.java]

and now there are no errors. Another possible solution is

[LectureVariables/Declared1.java]

.

Exercises on Assignment Statements

  1. What is the output of [LectureVariables/AddOne.java]

    Answer: 2

  2. What is the output of [LectureVariables/DoubleDouble.java]

    Answer: 4

  3. What is the output of [LectureVariables/p1.java]

    Answer: 14

  4. What is the output of [LectureVariables/p2.java]

    Answer: hello hello

  5. What is the output of [LectureVariables/p3.java]

    Answer: hello 5

  6. What is the output of [LectureVariables/p4.java]

    Answer: 2

  7. What is the output of [LectureVariables/p5.java]

    Answer: 2.2

  8. What is the output of [LectureVariables/p6.java]

    answer:

Summary

Having worked on Chapter 4 you will have:


Keyboard Input

Learning Objectives

Having worked on Chapter 5 you will have:

Reading


Introduction

Most useful programs allow the user of the program to input information to it. One way to input data to a computer program is through the keyboard of the computer. Often input is achieved simply by typing and then pressing the Enter key. We now learn how to write programs which accept input from the keyboard and then behave in different ways depending on the input. In Java there are a few things we must remember to do if our program is to accept input. Study the program: [Lecture2/Echo.java]

This program is waiting for you to type something in although it doesn't tell you. When eventually you do type something in the program simply copies what the user typed in to the screen. Try running the program. When you type something in remember to press the Return or Enter key when you have finished.

At this point in the course, do not try to understand everything about this program. The following facts may help your understanding:

The useful thing to remember is that when the method readLine() is called, the program waits for the user to press some keys (ending with the Enter key). The key sequence is converted into a string, preserving the order in which the characters were typed (not including the Enter key). This string is returned by the method readLine() and the program execution continues. In program Lecture2/Echo.java, the program waits for the user to type something in. Whatever the user types in is then stored in String variable s. This is done using the assignment statement String s = in.readLine();. The final statement of the program System.out.println(s);, simply displays on the screen the value of the String s, which contains what the user typed in before the enter key was pressed.

Prompting the User For Input

In Lecture2/Echo.java in Section 5.3, the user will not know that he is expected to type something in. It is usual, therefore, to display a message first, asking the user to type something in. This is called Prompting for Input. Consider the program: [Lecture2/EchoWithPrompt.java]

After the user has pressed Enter the computer replies you typed in followed by whatever the user input. This is achieved using System.out.println("you typed in "+s);. Here, the string "you typed in" and the String contained in the variable s are concatenated .

Now we give an example where the user is prompted for two strings, a first name and a last name. [Lecture2/BothNames.java]

In order to read two values here we simply call z.readLine() twice and store the results in different variables. (Here we have used s and t.)

Suppose we wanted to print the surname first and then the first name. We would do this by changing the order of s and t in the final System.out.println statement, as in

[Lecture2/BothNamesRev.java]

What is wrong with the following example: [Lecture2/BothNamesRevDec2.java]

The answer is that we have declared the same variable twice (recall Section 4.7.3).

Inputing Integers

So far, the only type we have seen a user input is a String. What if the user wants to input a number to a computer program? In Java, the way to do this is to still input the data as a string, but to then convert it to an integer using a method called Integer.parseInt.


Integer.parseInt

Every method in Java belongs to a class. You will learn a lot more about how to use methods in Chapter 8. Integer.parseInt belongs to the class called Integer. Look up this class in Java in a Nutshell page 350.

Study the program, [Lecture2/Add1.java]

First, the user's input is read into the String, s. This is achieved by using the statement:

String s=in.readLine();
This value is then converted into an int and stored in the int variable x. This is achieved by using the statement:
int x=Integer.parseInt(s);

The value of the arithmetic expression x+1 is finally printed out by the program. What happens if you don't enter an integer? Try it! Enter a string like assd. The Java interpreter gives the following error message:

Exception in thread "main" java.lang.NumberFormatException: assd
	at java.lang.Integer.parseInt(Integer.java:405)
	at java.lang.Integer.parseInt(Integer.java:454)
	at Add1.main(Add1.java:11)
The parseInt method has thrown a ``Number Format Exception'' because we did not enter a String that it could convert to an int. A similar error message would occur if the user entered a real number like 14.5. An Exception is thrown when an error occurs. Exceptions will be covered in more detail in Volume 2.

Exercises on Simple I/O

Double it

Write a program which asks the user to enter a number and it prints out double the number. answer: [Lecture2/answers/Double.java]

Add Two Numbers

Write a program which asks the user to enter two numbers. The computer adds them up and prints out the answer. [Lecture2/answers/AddTwo.java]

Average

Write a program which asks the user to enter three numbers and then prints out their average. [Lecture2/answers/Average3.java]

or [Lecture2/answers/Average4.java]

.

What would have happened if we had written 3 instead of 3.0? Remember integer division? See Section 3.7.

Summary

Having worked on Chapter 5 you will have:


Conditional Statements

Learning Objectives

Having worked on Chapter 6 you will have learned about:

Reading

Introduction

A lot of work in programming involves the programmer making decisions depending on variables in the program having certain values.

For example, suppose that you had been asked to write a program which asks the user to enter two numbers which prints out only the larger of the two numbers entered. You could not write such a program with just the statements you've seen so far. You need a conditional statement. There are at least two kinds of conditional statement:

Example of the if - else statement

This is how you make programs do different things depending on different conditions. Here is an example:

[LectureConditionals/BiggestOfTwo.java]

The program reads two integers into variables x and y and then if x>y it prints out the value of x, and if x$\leq$ y it prints out y.

Example of the if statement

An if statement is like an if - else statement except there is no else part.

[LectureConditionals/SimpleIf.java]

The program above, reads in an integer typed in by the user and prints out

the number you entered was too big
if this number is greater than 100. If. on the other hand, the number entered is not less than 100, then this program does nothing at all.

Syntax and Semantics

Before, we go any further in our discussion on the conditional statement we explain two important concepts in computing. syntax and semantics.

Syntax

The syntax of a statement or a program simply means what it looks like when it is written down. For example the syntax of an assignment statement consists of a variable name, like x or borisyeltsinspetrabbit followed by an equal sign (=), and on the right hand side of the equals sign is some form of expression. To fully describe what an expression is would take a lot more rules. We will not do it here. An expression could be something simple like the constant 1 or the variable y, or it could be something more complicated like x+1*100-5/2+(x-1).

Semantics

The semantics of a statement or program means what it does when it is run. For example the semantics of the assignment statement x=e is to first evaluate the expression e and then store the result in the variable x.

The semantics of System.out.print(e) is first to evaluate e and then to display this value on the computer screen. Before we talk about the syntax and semantics of conditional statements, we look at one more example.


Biggest of Three

A program that finds the biggest of three numbers.

[LectureConditionals/BiggestOfThree.java]

Notice the symbols, <= is how you write $\leq$ (less than or equal) in Java. What this program does is first reads in three integers into variables, x, y and z and then prints out the value of the biggest. How does it decide which is the biggest? If x $\ge$ y and x $\ge$ z then it prints out the value of the variable x since x is the biggest. (Notice that && means and.) If x is not the biggest, it checks whether y is the biggest and if so prints the value of y. If neither (x nor y is the biggest, the program just prints out the value of z.

Question

What would happen if all the numbers entered by the user were the same? For example if the user entered the number 20 three times. The answer is that the program would output
 
Biggest is 20


The Syntax of the if - else Statements

The if - else statement is the first example of a structured statement that we have seen. The reason that it is called structured is that it can contain more statements itself. The syntax of a if - else is given by
if (<boolean expression>) <statement> else <statement>
This means that a conditional consists of a boolean expression in brackets (we call this the guard) and a statement, (called the true part) followed by the word else and then another statement (called the false part).

The true part and the false part can be as complicated as you want them to be. In the previous example, the true part is System.out.println(x); and the false part was itself the conditional statement:-

if (y>=x && y>=z) System.out.println(y);
else System.out.println(z);

The Semantics of the if - else Statement

The semantics of an if - else statement is easy to define: When the computer executes a conditional statement, it first works out (evaluates) the guard. If the guard evaluates to be true it then executes the true part. If on the other hand the guard evaluates to be false then the computer executes the false part of the conditional. Consider the following program: [LectureConditionals/TestCond1.java]

Let us focus on the code

if (x>y) ;
else System.out.println(y);
Here, the true part of the conditional is the empty statement (The empty statement is discussed in greater detail in Section 6.6.1.) In this case if x is greater than y the program will do nothing.


The Empty Statement

Look at this program called Silly.java

It will compile correctly because it doesn't have any errors. But when we run it it doesn't do anything. The body of the main method has five empty statements. The empty statement is very important. This is surprising as the empty statement does nothing!

Another way of writing the empty statement is {} in the program [Lecture1/Silly1.java]

also does nothing as does [Lecture1/Silly2.java]

and [Lecture1/Silly3.java]

Programs that do Nothing

Make up some more Java programs that do nothing. What is the longest Java program that does nothing? answer:There isn't one.-Prove it!

The Sequential Statement

A very important type of statement that you have already come across without knowing that it had a name is the sequential statement. The syntax of a sequential statement is simply a sequence of zero or more statements enclosed in curly brackets. The semantics of a sequential statement is to execute each of its component statements from left to right (ie. sequentially). It is very important to realise that a sequential statement is a single statement. You can see a sequential statement in the conditional statements in the solutions to the exercises 6.8. Consider for example, the conditional statement
if (y>z) {
           System.out.println(y);System.out.println(z);
         }			
else     {
           System.out.println(z);System.out.println(y);
         }
The syntax of if then else tells us that both the true part and the false part must be statements. Here they are both sequential statements.


A common mistake is to leave out Curlies

Quite often, novice programmers will make the following mistake:-
if (y>z) 
           System.out.println(y);System.out.println(z);
         			
else     {
           System.out.println(z);System.out.println(y);
         }
The compiler gives an error. The reason that the compiler gives an error is that we are always allowed only a single statement between the guard (y>z) and the else. In the case above, there are two statements: System.out.println(y); and System.out.println(z);. To make it into a single statement we simply enclose it in curly brackets like this:
{System.out.println(y);System.out.println(z);}
We have created a single statement (a sequential statement ) from two statements.

Try compiling [LectureConditionals/ErrorCurlies.java]

and watch the compiler complain with

 
ErrorCurlies.java:22: 'else' without 'if'.
                         else     {
                         ^
1 error
The precise reason for this error message will be explained in Section 6.16.1.

Exercise

Put back the curly brackets and check that the program compiles with no errors. Does it?

Reminder

IF YOU WANT TO DO MORE THAN ONE THING IN EITHER THE TRUE OR FALSE PART OF AN IF THEN ELSE STATEMENT DON'T FORGET THE CURLY BRACKETS.


Exercises

Sorting Two Numbers

Write a program which asks the user to enter two numbers which then prints them out in
  1. ascending order answer:[LectureConditionals/AscendingTwo.java]

  2. descending order answer:[LectureConditionals/DescendingTwo.java]

Sorting Three Numbers

Write a program which asks the user to enter three numbers which then prints them out in
  1. ascending order
  2. descending order answer:[LectureConditionals/DescendingThree.java]

Notes on these Exercises

Note that && is java for and. Similarly || is java for or.

Program Layout

In the solutions to the exercises 6.8 you see how complicated programs should be laid out. Every closing curly bracket should lie directly underneath the corresponding opening bracket with nothing else in the way. In other words, you should be able to look vertically down the page from an opening curly bracket and the next thing you should see is the corresponding closing curly bracket. It is essential that you do this so that your programs are readable by other humans. Also the layout of conditionals should be of the form:
if (....)
    ....
    ....
    ....
else
    ....
    ....
    ....

if Statements

if Statements are simply a shorthand form of the if - else statement, where the false part is empty. But because the false part to a conditional is the empty statement, we can leave out the the word else as well. So instead of
if (n<0)
   {
     x=1;
     y=2;
   }
else ;
can be written more simply as:
if (n<0)
   {
     x=1;
     y=2;
   }


The Syntax of the if Statement

The syntax of a if is given by
if (<boolean expression>) <statement>
This means that a conditional consists of a boolean expression (we call this the guard) and a statement, (called the true part).

The Semantics of the if Statement

When the computer executes an if statement, it first works out (evaluates) the guard. If the guard evaluates to be true it then executes the true part. If on the other hand the guard evaluates to be false then the computer does nothing.

Boolean Expressions

The type boolean

There is a type in Java called boolean. There are only two values of this type Consider [LectureConditionals/Bool1.java]

If we compile and run this program, it simply prints out true.

The Simplest Boolean Expressions

The simplest boolean expressions are true and false.
What is the output of [LectureConditionals/Bool2.java]

The answer is hello
Here we have a conditional statement whose guard evaluates to true. This is because the boolean expression, true evaluates to true. Hence the program executes the true part. What is the output of [LectureConditionals/Bool3.java]

The answer is goodbye

Combining Boolean Expressions using Logical Operators

New boolean expressions can be created from old ones using , logical operators: and(&&), or(||), and not(!) The program [LectureConditionals/Bool4.java]

outputs false. Since not(true) equals false.

Exercise

What is the output of [LectureConditionals/Bool5.java]

answer: true

Truth Tables

Truth Tables are a simple way of defining the behaviour of logical connectives like and,or and =>.

Exercises Producing Truth Tables

AND

Write a program that prints out the truth table for and like this:
p      |    q    |  p and q
--------------------------
true   |   true  |   true
true   |   false |   false
false  |   true  |   false
false  |   false |   false
answer:[LectureConditionals/TTAnd.java]

OR

Write a program that prints out the truth table for or like this:
p      |    q    |  p or q
-------------------------
true   |   true  |   true
true   |   false |   true
false  |   true  |   true
false  |   false |   false
answer:[LectureConditionals/TTOr.java]

Implication

Write a program that prints out the truth table for implication. Use the fact that
$p$ implies $q$ = $(\neg p)$ or $q$.
answer:[LectureConditionals/TTImplies.java]

Further Exercises

Validating One Input

Write a program that asks the user to enter an exam mark. This mark must be between zero and 100. If they do then print out the number. If they don't, say "Wrong!". answer:[LectureConditionals/Exam1.java]

Validating Two Inputs

Write a program that asks the user to enter an exam mark. This mark must be between zero and 100. If the user does not do this say ``Wrong exam'' and exit the program. If the user does this correctly, then ask for a coursework mark which must also be between zero and 100. If this is also correct then write out the average of the two marks otherwise say "Wrong coursework". answer:[LectureConditionals/Exam2.java]


Programming Assignment: Sorting Four Numbers

Write a program which asks the user to enter four ints which then prints them out in ascending order. Later, we will see how this is easier using loops.


Leaving out the Curlies

So if we mistakenly leave out the curly brackets (see section 6.7.1) as in:-
if (n<0)
   
     x=1;
     y=2;
   
else ;
The compiler will first see the if then statement
if (n<0)  x=1;
and then see the assignment statement
     y=2;
Then it will come across
else ;
on its own and get confused and say
.......: 'else' without 'if'.
                         else  ;   
                         ^
1 error

Summary

Having worked on Chapter 6 you will have learned about:


Simple Loops

Learning Objectives

Having worked on Chapter 7 you will have learned about:

Reading

Introduction

If we want the computer to repeat a task a number of times, the best way to do it is using a loop. One form of loop in Java is called to for loop. Compile and run the program, [Lecture4/LineOfTenStars.java]

When we run this program, it produces

*
*
*
*
*
*
*
*
*
*

Exercise

Re-write the above program so it prints 100 stars. [Lecture4/LineOfAHundredStars.java]

Syntax of ForLoops

A for loop consists of the word for followed by an expression, then a boolean expression and then another expression. These three expressions are enclosed in round brackets separated by semicolons. After this comes the body of the for loop which is a statement. So the structure of a for loop is

for (<initialisation expression>;<guard>;<increment expression>) <body>

The first statement expression we call the initialisation expression. The boolean expression in the middle we call the guard and the final statement in the brackets is called the increment expression. Any or all of theses components can be empty. So an extreme, but syntactically correct for loop is
for (;;);

Exercise

Make up a program with for (;;); in it and check that it compiles. The body of the for loop can be any statement however complex. In
 for(int i=0;i<10;i=i+1) System.out.println("*");

The Semantics of the for loop

In this section we describe how a for loop is executed.
  1. Execute the initialisation expression.
  2. Evaluate the guard. If it is false then leave the loop and go on to the next statement. If it is true go to 3.
  3. Execute the body.
  4. Execute the increment expression.
  5. Go to 2.

Example

 
for(int i=0;i<3;i=i+1) System.out.println("*");

The following steps happen:-

So altogether 3 asterisks have been printed.

So what would

 for(int i=1;i<3;i=i+1) System.out.println("*");
do? It would print just two asterisks

Exercises

For each for the following for loop s, say how many asterisks are printed.
  1.  for(int i=0;i<5;i=i+1) System.out.println("*");
    
    answer:5
  2.  for(int i=1;i<3;i=i+1) System.out.println("*");
    
    answer:2
  3.  for(int i=-1;i<3;i=i+1) System.out.println("*");
    
    answer:4
  4.  for(int i=0;i<3;i=i+2) System.out.println("*");
    
    answer:2
  5.  for(int i=0;i<3000;i=i+2) System.out.println("*");
    
    answer:1500

  6.  for(int i=0;i>=0;i=i+1) System.out.println("*");
    
    answer:This one goes on for ever! Why?
  7.  for(int i=m;i>=n;i=i+1) System.out.println("*");
    
    You can assume that $n-m > 0$. answer:$0$
  8.  for(int i=m;i>=n;i=i+1) System.out.println("*");
    
    Where $n-m < 0$. answer:This one goes on for ever.

Number of Iterations Depending on User Input

So far, all the for loops have gone round a fixed number of times.
Now consider [Lecture4/VerticalLineOfStars.java]

This program first asks the user to enter a number. This number is stored in the variable x. This variable is then also used in the guard, i<x, of the for loop . So here, we will go round the loop exactly the number of times that the user entered. Compile and run Lecture4/VerticalLineOfStars.java. What happens if you enter -5? Why?

Compile and run [Lecture4/NumbersUpTo.java]


Exercises

One to Ten

Change Lecture4/NumbersUpToJava so that if you enter 10, instead of printing out 0 to 9 it prints 1 to 10. [Lecture4/OtherNumbersUpTo.java]

Descending Sequence from ten to one

Write a program NumersDownTo.java which is like Lecture4/NumbersUpToJava but prints the numbers in descending order. [Lecture4/NumbersDownTo.java]

Even Numbers

Write a program Evens.java such that if you enter the number $n$ it outputs the first $n$ even numbers. For example if you enter $5$, the output would be:
0
2
4
6
8
[Lecture4/Evens.java]

Odd Numbers

Write a similar program called Odds.java. You must be able to read my mind to work out what it does! [Lecture4/Odds.java]

Ten Times Table

Write a similar program that does the ten times table as in section 3.8, question 3.8.5 using a for loop . [Lecture4/TenTimesTable.java]

Multiples of Three

Write a program MultiplesOFThree.java such that if you enter the number $n$ it outputs the first $n$ multiples of 3. For example if you enter $4$, the output would be
0
3
6
9
[Lecture4/MultiplesOFThree.java]

Multiples

Write a program UserEntersMultiple.java where the user enters the multiple and the number. So if the user enters 3 and 7 the output will be
0
7
14
and if the user enters 4 and 101 the output would be
0
101
202
303
[Lecture4/UserEntersMultiple.java]

Simple Times Table

Write a program SimpleTimesTable.java, such that if the user enters a number $n$, the program prints out the times table for $n$. For example if the user enters 4 and 5, the program outputs
1 times 5 = 5
2 times 5 = 10
3 times 5 = 15
4 times 5 = 20
or if the user entered 3 and 19 the program outputs
1 times 19 = 19
2 times 19 = 38
3 times 19 = 57
[Lecture4/SimpleTimesTable.java]

Largest of Ten

Write a program that asks the user to enter 10 integers and then prints out the largest. [Lecture4/LargestOfTen.java]

Largest - User First says how many

Generalise this so the program first asks the user how many numbers he is going to enter. [Lecture4/Largest.java]

Largest of As Many Numbers as Until Zero is Input

This time do not ask the user how many numbers they will enter, but allow them to enter as many as they like until they enter a zero. [Lecture4/LargestEndWithZero.java]

Notice that we have used a boolean variable more in the guard of the loop. A common mistake would be to forget to change the value of more in the loop. This would cause the loop to go on for ever. Initially this variable is set to true when the user enters zero it is set to false. The guard of the loop is the variable, more, so the program will leave the loop only when more is set to false.


A Guessing Game

Write a program that implements the following game: The computer has thought of a number (245). The computer says ``try to guess the number I'm thinking of: '' The user must try to guess this number by typing in a number. If the number the user types in is less than the number the computer thought of it says ``too high - guess again: '' and repeats the process. If the number the user types in is greater than the number the computer thought of it says ``too low - guess again: '' and repeats the process. If the user guesses the correctly, the computer says ``Correct! The number of guesses you made was ...'' and the program finishes. This is the only way to finish the program. So if the user never guesses correctly the game should go on for ever!

[Lecture4/guess.java]

Here we go round the main loop while ! found is true, that is while found is false.

Factorial

Write a program that asks the user to enter a number and outputs its factorial. The factorial of $n$ is 1 times 2 times $\cdots$ times $n$. The factorial of 0 is 1. [Lecture4/Factorial.java]

What happens if the user enters a negative integer?

Exercise - No Solution Provided

Example Assignments

Write a program that tries to guess the number thought of by the user. The number is between 0 and 1000. If the computer's guess is too high, the user should enter 2. If the computer's guess is too low, the user should enter 1. If the computer's guess is correct, the user should enter any integer except 1 or 2. If the computer takes more than ten guesses then the computer loses otherwise the user loses. Marking is as follows:
  1. A program that plays the game properly will gain marks.
  2. If your program cannot lose you will gain marks
  3. If your program is properly indented and has comments you will gain marks.
  4. You will gain marks if you detect cheating by the user.
  5. You will gain marks for the simplicity of your solution.
  6. You will lose marks if your program never guesses the answer.
  7. You will lose marks if the program does not know whether it has won or lost or if it makes the same guess more than once.

Summary

Having worked on Chapter 7 you will have learned about:


Calling Methods

Learning Objectives

Having worked on Chapter 8 you will have:

Reading

Introduction

Java provides many useful methods for helping us achieve desired results in our programming. In this chapter we explain just a very few of them. It is very important that as a programmer you get to know the sorts of method that are likely to be provided and how to look them up.

What is a Method

A Method is a chunk of program code (also called a procedure or function or sub-routine) that performs a particular task. To make a method perform a task simply ``call it''. Very importantly: We don't need to understand or even see the code of the method in order to be able to use it. It may have been written by someone much cleverer and more experienced than ourselves. This chapter shows how to call methods. Later on in the course, but not in this chapter, you will learn how to write your own methods.


How to Call a Method

We simply give its name together with a (possibly empty) list of actual parameters in round brackets. We have already seen a few Method calls in the programs that we have written: Examples of these are:-

Different Uses of Method Calls

Method Calls as Statements

Often methods are called as Statements. Examples of these include
System.out.println("hello" + " fred");;

Method Calls as Expressions

Sometimes calling a method gives a value which we then do something else with. An example of this is
String s=in.readLine();

Here in.readLine() is returning a value which we are using in an assignment statement. It would be wrong and meaningless to write

int y=System.out.println();
This is because System.out.println() does not return a value. So there is no value that can be assigned to the variable y.

Method Signatures

The Class java.lang.Math

Look up the class, java.lang.math, in [6] page 352, There you will see a long list of methods that may be useful to you. These methods include:-
public static  int abs(int a)

This is called a method signature. Ignoring for the moment, the bit that says, public static this tells that the method abs takes a single integer parameter and returns an integer. So whenever we call it we get back an integer. Try [LectureUsefulMethods/abs.java]

This program contains two calls to Math.abs. In the first call , the actual parameter is -5 and in the second call the actual parameter is 5.

The output of this program is

5
5
What do you think abs does?

public static float abs(float a)
This says that there is a version of the method abs that takes a single float parameter and returns a float. So whenever we call it we get back a float. Try [LectureUsefulMethods/abs1.java]

The output of this program is

5.375
5.824

public static int round(int float)

This says the method round takes a single float parameter and returns an integer.

So whenever we call it we get back an integer. Try [LectureUsefulMethods/round.java]

The output of this program is

-5
6
6
What do you think round does? I am not telling you. You must find out yourself!

Method Overloading

Notice that we have more than one method with the same name but different signatures. This is called Method Overloading.

Exercise - Signatures

Write down the signatures of all the methods in java.lang.Math public static int abs(int)
public static long abs(long)
public static float abs(float)
public static double abs(double)
public static double acos(double)
public static double asin(double)
Notice I have left out the parameter name. It is acceptable to do this.

Notice I have left out the parameter name. It is acceptable to do this. Instead of writing

public static int abs(int n)
we write
public static int abs(int)
The name n of the formal parameter is not important. The type of the formal parameter(s) and the return type of the method are important.

More Useful Methods in The Class java.lang.Math

int max(int,int)

This method returns the maximum of two ints. We could rewrite the program to find the biggest of three numbers (section 6.4.3) as [LectureUsefulMethods/BiggestOfThreeFirst.java]

So first we work out the maximum of x and y and store the result in a. We then print out the maximum of a and z. So we didn't need the conditional statement after all!

In fact, we don't need the variable a either: [LectureUsefulMethods/BiggestOfThree.java]

The maximum of x,y and z is the maximum of x and the maximum of y and z.

double random()-

This method produces a random number between 0 and 1. Run this a few times:

[LectureUsefulMethods/random1.java]

We can use this method in the program where the computer guesses a number in exercise 7.7 question 7.7.12. To make the computer guess a different value each time. We do this by generating a random (double) number between zero and one using Math.random(), multiplying it by 1000 to give a random double between 0 and 1000 and then rounding it to give us a random integer between 0 and 1000. [LectureUsefulMethods/guess.java]

Static vs Instance Methods

Every instance method (ie one which doesn't say static in its definition) will be called using dot notation.

If public int f(int) is defined in a class called C then every call to f will be of the form v.f(e), where v is an expression of type C, (i.e. v evaluates to an object of type C.) and e is an expression of type int.

The Class java.lang.String

Look up the Class java.lang.String in Java in a Nutshell page 563.

Instances of Objects

So far the only instances of Objects we have come across are Strings. Every time we write something like "hello" in our program we are creating a new instance of an Object of type String. Each instance like "hello" has its own collection of instance methods. So, for example there is now a new "hello.charAt()" method and a new "hello.length()" method but not a new valueOf() method, since that is declared as static in java.lang.String. So every time we use a string of characters with double quotes at either end like "hello", we are not only creating the String "hello", but also copies of all the instance methods such as "hello.charAt()", etc.

length()

The signature of length is int String.length().
The length() method can be used to find the length of a string. If s is a String, the expression, s.length() will be the length (ie. the number of characters in the String s). So "fred".length() will return 4 and "".length() will return zero. You may ask why don't we write length(s) for the length of string s. This should become clearer later. Consider the program:

[LectureUsefulMethods/LongestOfThree.java]

The user is asked to enter three strings and the longest one is printed out.

charAt()

The signature of charAt() is char String.charAt(int).
The charAt() method returns the character at a particular position in a string. So "hello".charAt(0) gives the character 'h' and "hello".charAt(1) gives the character 'e' and "hello".charAt(4) gives the character 'o'. Here is a program that asks the user to enter her name and then it prints it out backwards. [LectureUsefulMethods/Reverse.java]

Notice here we have written i-. This has the same effect as i=i-1

compareTo()

The signature of compareTo() is int String.compareTo(String).
Try running [LectureUsefulMethods/AlphabeticOf2.java]

to find out the behaviour of compareTo(). See how it treats upper case characters and digits.

Exercise

Give the signatures of all the methods in java.lang.String.

Exercise

Write a program based on the one in Exercises 6.8 question 2 which asks the user to enter 3 strings and then prints them in reverse dictionary order. That is, the word that would come nearest the end of the dictionary is printed out first and the one that comes nearest the beginning of the dictionary is printed last. [LectureUsefulMethods/DescendingThree.java]

Type Checking

When we call a method, we can call it with any expressions as actual parameters, provided they are of the right type. It is very important to understand this. So, for example, "hello" + " dog" is a String so we can apply the length() method to this expression like this
("hello" + " dog").length()
This gives us back the int, 9. Notice there is a single space character before the 'd' in " dog". We can therefore use the expression ("hello" + " dog").length() in any place that an int is expected. So for example we can write:

("hello" + " dog").length()*5
and it will return 45 or
Math.max(("hello" + " dog").length(),5)-.

What value does this return? Answer: 8 because the maximum of 9 and 5 is 9.

We can check whether things are right by checking the signatures of the methods we call in the expressions. The compiler does this for us when we compile our programs.

Exercises - Type Checking

For each expression say whether it type checks correctly and, if possible, give its value. Write a program if necessary.
  1. Math.abs("hello")
    No. The argument to Math.abs is not a String
  2. Math.abs("hello".length())
    Yes. "hello".length() is an int so can be passed to Math.abs(). The value of this expression is 5
  3. Math.abs("hello".length())+5
    Yes. The answer is 10.
  4. "fruit".charAt( Math.abs("hello".length())-3)
    Yes. "fruit" is a String, Math.abs("hello".length())-3 is an int (2). So the result is the character at position 2 in fruit namely, 'u'.
  5. "boy".compareTo(6)
    No. Compare to expects two Strings, not a String and an int
  6. "boy".compareTo("girl")
    Yes
  7. "boy".compareTo("6")
    Yes. "6" is a String
  8. "boy".compareTo("6")+17
    Yes. "boy".compareTo("6") returns an int so we can add it to 17.
  9. "boy".replace('b',"soup".charAt(0))
    Yes. replace has signature String.replace(char,char) and "soup".charAt(0) returns a char.
  10. ("boy".replace('b',"soup".charAt(0))).length()
    yes

Exercises

  1. Write programs to investigate the behaviour of the following methods:
    1. String substring(int)
    2. String substring(int, int)
    3. String replace(char, char)
    [LectureUsefulMethods/Test.java]

  2. Describe their behaviour.
  3. Write a program that asks the user to enter a string and then outputs the number of occurrences of the character 'a' in the string the user entered. For example, if the user entered "hello" the output would be 0, but if the user entered "abracadabra", the answer would be 5. [LectureUsefulMethods/NumberOfas.java]

  4. The program LectureUsefulMethods/NumOfas.java produces grammatically incorrect output if the user enters a string with exactly one 'a'. It outputs:-
    ``Your string has 1 occurrences of the character 'a' ''.

    Correct this. [LectureUsefulMethods/NumberOfasBetter.java]

Parsing Methods

Integer.parseInt()

You will see among the list of method headings:
public static int parseInt(String s) throws NumberFormatException;
For the moment, the important part of this definition is
............. int parseInt(String  ) .............................
This says that the method parseInt takes a single parameter of type String and returns an int. This is called the signature of the method. We sometimes say the parseInt method has signature int (String). Notice there is another incarnation of parseInt in the class Integer. Its signature is int ( String,int). It takes two parameters. First a String and then an int and returns an int.

Exercise

For each method in the class Integer give its signature. answer: Integer decode(String)
Integer getInteger(String)
. . .

There are similar methods for parsing other sorts of numbers, for example, Double.parseDouble().

Exercises - No Solution

Dictionary Order

Write a program based on LectureUsefulMethods/DescendingThree.java which asks the user to enter 3 strings and then prints them in dictionary order. That is, the word that would come earliest in the dictionary is printed out first and the one that comes latest in the dictionary is printed last. An added complication of your program is that it should not distinguish between upper and lower case letters. i.e "dog" and "Dog" should be considered the same as far as comparison is concerned. Convert everything to lower case before comparing. (see toLowerCase() in java.lang.String)
Big hint: (x.toLowerCase()).compareTo(y.toLowerCase())

Summary

Having worked on Chapter 8 you will have:


One Dimensional Arrays

Learning Objectives

Having worked on Chapter 9 you will have:

Reading

Introduction

An array is a ``place'' in the memory of the computer to store lots of data items, all of the same type. For example, remember the program [Lecture4/LargestOfTen.java]

This program ask the user to enter ten numbers and then prints out the largest. Once a new number is read in, the previous number is lost because the input is achieved through a single variable.

Suppose we wanted to store all the numbers the user entered and then print them out in the opposite order to which they were entered. Without arrays, this could be achieved using ten separate variables. A better alternative is to store the numbers in an array:

[LectureArrays1D/ReverseTen.java]

First we declare an array variable called a:

 int [ ] a;
We then give it space to hold ten integers by:
a = new int[10];
The array a now looks like this:-

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

The ten elements of the array, a are called a[0],a[1],a[2] up to a[9]. The first element of a is called a[0]. If we wanted to put 5 into the third element of the array a we would write

 
 a[2]=5;
The array would then look like:

5
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]



We could also have written
 
 a[1+1]=5;
or
int i=2;
a[i]=5;
If we wanted to fill the whole array up with sevens we could write:
for (int i=0;i<10;i++) a[i]=7;

The array a would then look like:

7 7 7 7 7 7 7 7 7 7
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]



If we wanted to populate the array a with ten values entered by the user we would write:

for(int i=0;i<10;i++)  
{ 
    String s =in.readLine();
    a[i]=Integer.parseInt(s);
}
The first time round the loop, the variable i has the value 0 and each time round the loop, one is added to i. The final value of i inside the loop is 9 (it is 10 when the program leaves the loop). This has the same effect as:
s =in.readLine();a[0]=Integer.parseInt(s);
s =in.readLine();a[1]=Integer.parseInt(s);
s =in.readLine();a[2]=Integer.parseInt(s);
s =in.readLine();a[3]=Integer.parseInt(s);
s =in.readLine();a[4]=Integer.parseInt(s);
s =in.readLine();a[5]=Integer.parseInt(s);
s =in.readLine();a[6]=Integer.parseInt(s);
s =in.readLine();a[7]=Integer.parseInt(s);
s =in.readLine();a[8]=Integer.parseInt(s);
s =in.readLine();a[9]=Integer.parseInt(s);
If we then wanted to print out the values input by the user in the reverse order that they were typed in, we would simply print first a[9] then a[8] and,..., lastly a[0], like this:
 

for(int i=9;i>=0;i--) System.out.println(a[i]);
The first time round the loop the variable i has the value 9. Each time round the loop, one is subtracted from i. The last value that i has in the loop is zero. So, this has the same effect as:
System.out.println(a[9]);
System.out.println(a[8]);
System.out.println(a[7]);
System.out.println(a[6]);
System.out.println(a[5]);
System.out.println(a[4]);
System.out.println(a[3]);
System.out.println(a[2]);
System.out.println(a[1]);
System.out.println(a[0]);

Exercises

  1. Consider the following program:

    [LectureArrays1D/Array1.java]

    What does it output?
    Answer:

    0
    1
    2
    3
    4
    
    num is declared to be an array of 5 ints. The first loop has the following effect:

    0 1 2 3 4
    nums[0] nums[1] nums[2] nums[3] nums[4]



  2. Write a program similar to LectureArrays1D/ReverseTen.java but first ask the user how many numbers she will enter. [LectureArrays1D/Reverse.java]

    If n is the number of ints the user will enter then our array must be big enough to hold n ints and the program must go round each loop n times.

  3. Remember the program [Lecture4/Largest.java]

    Rewrite it using an array. [LectureArrays1D/Largest.java]

Array Index Out of Bounds

Try running [LectureArrays1D/OutOfBounds.java]

It gives the error:

The reason for this is that num is defined here to have length 2. The error is that there is no such element of the array num as num[79]. Any other value apart from 0 and 1 will give this error. So num[712] will give the same error, but num[1] will be OK. Note that this error is not detected by the compiler, but occurs only when we run the program. It is called a run time error. Other run time errors that we have already come across is division by zero.

Exercises Using Arrays

Alter [LectureArrays1D/Crash.java]

to see if you can make it have a run time error! When a program has a run time error we say

``the program has crashed''.

Exercises

Bad input

In [LectureArrays1D/Input1.java]

if the user enters 0, the program does not behave well. Correct it. [LectureArrays1D/Input1Answer.java]


Array largest, smallest, sum and average

Write a program which reads some numbers into an array and prints out:-
  1. the largest
  2. the smallest
  3. the sum
  4. the average
[LectureArrays1D/All.java]

Could we do this without an array?

Array Limitations

Remember the program Lecture4/LargestEndWithZero where we carry on allowing the user to enter as many values as she likes until she enters zero. We could try to do this using an array: [LectureArrays1D/LargestEndWithZero.java]

but this does work, because if the user enters more than 1000 numbers the program will crash. Notice that we have used the final value of i to tell us exactly how many numbers were entered. Also, notice that in order to do this we had to declare i globally i.e. Not inside the loop. This will be explained in greater detail in Volume 2.

Backwards

Write a program that asks the user to enter some numbers (first the user says how many) and then prints them out in the opposite order to which they were entered. and then prints them out in the same order they were entered. For example, if the user types 1 4 3 5 the output should be 5 3 4 1 1 4 3 5. [LectureArrays1D/BackwardForward.java]

Occurrences

Write a program where first the user enters some numbers and then the program asks the user to pick a number. The program tells the user how many of these numbers the user entered. For example if the user entered 7 4 4 3 1 7 and then the number chosen was 7, then the program would output 2, because the user entered two sevens. If the number chosen by the user was 8, then the program would output 0. [LectureArrays1D/Occs.java]

Longest String

Write a program where the user types in a number of Strings which are stored in an array of Strings and then the program prints out all the longest Strings entered by the user. [LectureArrays1D/Longest.java]


Exercise - No Solution

Write a program where the user types in a number of Strings stored in an array of Strings and then the program prints out all the Strings that have the most occurrences of the character 'a'. answer: This one is for you to struggle with!

Summary

Having worked on Chapter 9 you will have:


Nested Loops

Learning Objectives

Having worked on Chapter 10 you will have:

Reading

Squares and Rectangles

As we said earlier, the body of a loop can be any Java statement. It is quite usual for the body of a loop to contain another loop. Consider [Lecture5/FullSquareOfStars.java]

In this program there is an outer loop:

	for(int j=0;j<x;j++)
		{	
                   ...
		}
The body of this loop contains two statements, a for loop (the inner loop) and a print statement. The body of outer loop will be executed x times where x is the value typed in by the user. The body of the inner loop prints a horizontal line of x stars and then moves the cursor onto the next line (System.out.println()). So, the outer loop will print x horizontal lines each containing x stars. In other words, it will draw a square10.1 of stars. The reason that it is a square rather than a rectangle is that the same value x is used to define the number of times to go round the outer loop and also the number of times round the inner loop.

Exercise

A trace of the values of i and j as the program is executed if the user enters 3 is given below:
j i
0 0
1
2
3
1
0
1
2
3
2
0
1
2
3
3

If these two values were different, then a rectangle would be printed:

[Lecture5/FullRectangleOfStars.java]

Here, the user enters two values, the height y, and the width, x. Clearly the number of times round the outer loop will govern the height of the shape and the number of times round the inner loop will govern the width. The guard of the outer loop should depend on y and the guard of the inner loop should depend on x.

Exercise

Trace the values of i and j as the program is executed if the user enters 2 for the height and 3 for the width.
j i
0 0
1
2
3
1
0
1
2
3
2

Non-Rectangular Shapes

We now further investigate loops within loops using shapes. We will only get a rectangle if the number of times gone round the inner loop is constant. If we vary the number of times round the inner loop, we will not get a rectangle. For example to get a right angle triangle with the right angle at the bottom left:
*
**
***
****
*****
the number of times through the inner loop starts at one and goes up by one each time. A program that achieves this is

[Lecture5/LeftBottomTriangle.java]

Notice that the number of times round the inner loop depends on j, the outer loop counter i.e the first time we go once round the inner loop, the second time twice etc. If we trace the values of i and j when the user enters 3 we will get:
j i
1 0
1
2
0
1
2
3
0
1
2
3
4

Exercise: Left Top Triangles

Write a program that prints this
****
***
**
*
if the user enters 4, and
*****
****
***
**
*
if the user enters 5, etc. In this case, the number of times to go round the inner loop starts at x and goes down by one each time. So, the jth time round the inner loop we want to go round it x-j times, for all values of j from 0 to x-1. [Lecture5/LeftTopTriangle.java]

Study the differences between this program and Lecture5/LeftBottomTriangle.java. The only difference is the guard of the inner loop.

Exercise: Right Top Triangles

Write a program that prints this
****
 ***
  **
   *
if the user enters 4 and
*****
 ****
  ***
   **
    *
if the user enters 5, etc.

In this case, the number of stars on each line is identical to the number of stars on each line in the previous program: Lecture5/LeftTopTriangle.java. The difference is that on each line we have to print some spaces before we start doing stars. The zeroth line has zero spaces before the stars, the first line has one space before the stars, the second line has two spaces before the stars, etc. The program goes once round the outer loop for each horizontal line that is drawn. The outer loop will contain two inner loops: the first to do the spaces and the second to do the stars. For the $j$th time round the outer loop we want $j$ spaces and $x-j$ stars. [Lecture5/RightTopTriangle.java]

Exercise: Hollow Squares

Write a program that does this
****
*  *
*  *
****
if the user enters 4 and
*****
*   *
*   *
*   *
*****
if the user enters 5 etc.

This time, the zeroth and last line (the $x-1$th) are different from all the others. They are complete lines of $x$ stars. All the other lines, from the first to the $x-2$nd, have a single star followed by $x-2$ spaces followed by another single star. Another, neater way of thinking of the problem is that if we are at the boundary of the square we print a star and otherwise we print a space. We are at the boundary of the square, at the zeroth and last time of the outer loop and the zeroth and last times of the inner loop. [Lecture5/HollowSquareOfStars.java]

Here, the body of the inner loop first contains a conditional statement. The guard of this conditional is

(i==0||i==x-1|| j==0 || j==x-1)
Remembering that || means or, this condition is true if when at the boundary of the square.

Exercises about Shapes

Write the following programs:-

RightBottomTriangle.java

[Lecture5/RightBottomTriangle.java]

HollowRectangleOfStars.java

[Lecture5/HollowRectangleOfStars.java]

HollowLeftBottomTriangle.java

[Lecture5/HollowLeftBottomTriangle.java]

HollowLeftTopTriangle.java

[Lecture5/HollowLeftTopTriangle.java]

HollowRightTopTriangle.java

[Lecture5/HollowRightTopTriangle.java]

HollowBottomRightTriangle.java

[Lecture5/HollowRightBottomTriangle.java]


Exercises on Producing Multiplication Tables

Write a program to print out all the times tables. The user should enter how many tables and also how many to go up to for each table. For example:-
How Many Numbers for each table? 7
Up to which times table 3
1 times 1 = 1
2 times 1 = 2
3 times 1 = 3
4 times 1 = 4
5 times 1 = 5
6 times 1 = 6
7 times 1 = 7

1 times 2 = 2
2 times 2 = 4
3 times 2 = 6
4 times 2 = 8
5 times 2 = 10
6 times 2 = 12
7 times 2 = 14

1 times 3 = 3
2 times 3 = 6
3 times 3 = 9
4 times 3 = 12
5 times 3 = 15
6 times 3 = 18
7 times 3 = 21

[Lecture5/TimesTable.java]


Exercise on Multiplication and Exponentiation in Terms of Addition

Multiplication in Terms of Addition

Suppose Java didn't have multiplication. Write a program that asks the user to enter two whole integers $m$ and $n$ which outputs $m$ times $n$. Your program should use a loop and not contain a multiplication sign, *, anywhere! [Lecture5/Multiply.java]


Exponentiation in Terms of Addition

Suppose Java didn't have multiplication. Write a program that asks the user to enter two whole numbers $m$ and $n$, and outputs $m^n$ ($m$ to the power of $n$). Your program should use a loop within a loop. [Lecture5/Power.java]

Summary

Having worked on Chapter 10 you will have:


Static Methods

Learning Objectives

Having worked on Chapter 11 you will have:

Reading

Introduction

You are now going to learn how to write your own (static) methods. Successfully writing and using methods is one of the keys to being able to program effectively. As we have already seen, methods are useful collections of statements that can be called over and over again. The usefulness of methods has already been illustrated in Chapter 8.

We refer again to the shapes that we were drawing in Chapter 10. We often used loops to draw horizontal lines of different numbers of stars.

The first method we are are going to define will be for drawing such a line of stars. The method Lines.lineOfStars will have one int parameter, which enables us to use the method to draw horizontal lines of different numbers of stars.

The Purpose of Parameters

Parameters allow us to use the same general method to perform different tasks.

Lines.lineOfStars(5) will draw 5 stars, Lines.lineOfStars(52) will draw 52 stars and Lines.lineOfStars(1000) will draw 1000 stars in a line etc.

Our program to draw the square is now [Lecture6/FullSquareOfStars.java]

We have put the method definition in a different file called Lines.java and it looks like this: [Lecture6/Lines1.java]

When we call our method lineOfStars we also have to tell the Java system where to find it. We say Lines.lineOfStars because we have put our method in a class called Lines . For convenience we have put our method in a file called Lines.java. We will put all useful methods for drawing shapes in this file.

The Structure of a Method Definition

Let us study the code for the definition of lineOfStars in a bit more detail. The first line:

The Method Heading

static void LineOfStars(int n)
is called the heading of the method. It gives us the signature of the method and tells us whether it is static or not. The return type void means it doesn't return anything: it just does something (i.e draw a line of stars).

The Formal Parameters

The method heading tells us that this method has one formal parameter called n of type int. Later we will see methods with more than one parameter. Methods do not have to have parameters. In this case, there will be nothing written between the brackets at the end of the heading.

The Body of the Method

Everything apart from the first line is called the body of the method. The body looks very familiar. It is just the same old loop for drawing some stars in a horizontal line.

How to Use the Parameters

But how many stars does it do? How many times does it go round the loop? Clearly it goes n times round the loop. It is very important that we have used the same identifier n both for the formal parameter and for the boolean in the guard of the loop. This is why calling the method with different values will give different results. When we call the method by saying Lines.lineOfStars(5) it is as if the formal parameter n is replaced by the actual parameter 5 and then the body of the method is executed (calling methods has already been discussed in Section 8.5 Chapter 8). So in this case it is as if the body is
for (int i=0;i<5;i++)System.out.print("*");
The n has been replaced by 5, so 5 stars will be drawn.

Calling Methods

Having defined our LineOfStars method we can now use it. [Lecture6/SimpleCall.java]

There are four calls to the method Lines.LineOfStars, each with a different actual parameter. Notice that the actual parameter can be any expression that evaluates to an int. This is because in the method heading, the formal parameter was declared to be of type int. Having defined a method, it can be called as often as we require.

The output of this program is:

*****
****
**************
******

We can also use the method to draw rectangles of stars:

[Lecture6/FullRectangleOfStars.java]

Exercises using Methods

Left Bottom Triangle of Stars

Rewrite the program Lecture5/LeftBottomTriangle.java so it uses Lines.lineOfStars. [Lecture6/LeftBottomTriangle.java]

Left Top Triangle of Stars

Rewrite the program Lecture5/LeftTopTriangle.java so it uses Lines.lineOfStars. [Lecture6/LeftTopTriangle.java]

Hollow Lines of Stars

Let us rethink how to draw a hollow shape, say, for example, a hollow square. We always have a loop where each time round the loop we draw a horizontal line of the hollow shape. The zeroth and last time round the loop, we will draw a solid line of stars and all the other times round the loop we draw a hollow line of stars. A hollow line consists of a star at either end with spaces in between. We can write a method for drawing a hollow line (of Stars) like this:
static void HollowLineOfStars(int n)
{
  for (int i=0;i<n;i++) 
  if (i==0 || i==n-1) System.out.print("*"); 
  else System.out.print(" ");
}
We can add this method to our class Lines in file Lines.java so it now looks like

[Lecture6/Lines2.java]

and the program to draw the hollow square of stars is

[Lecture6/HollowSquareOfStars.java]

The zeroth and last time round the loop we call Lines.LineOfStars and all the other times we call Lines.HollowLineOfStars.

Some Nice Things about Methods

Readability

Using methods make our programs more readable and understandable, both by us and other people. This is only true if we use methods sensibly and give them sensible names that reflect what they actually do.

Re-Use

If we have defined a useful method then it will be used both by us and other people over and over again.

Breaking down problems into smaller ones

If we think using methods, then we can describe a big problem in terms of slightly smaller problems each of which we can break down further.

Exercises on Hollow Shapes

Hollow Left Bottom Triangle

Rewrite the program to draw a Hollow Left Bottom Triangle of Stars using methods.
[Lecture6/HollowLeftBottomTriangle.java]

Hollow Left Top Triangle

Rewrite the program to draw a Hollow Left Bottom Triangle of Stars using methods.
[Lecture6/HollowLeftTopTriangle.java]

Right Triangles using Methods

In order to write methods to print triangles with their right angle on the right, we need to print spaces before we start doing stars. So we add a method for drawing $n$ spaces to our ever growing portfolio of methods in Lines.java.
static void LineOfSpaces(int n)
{
  for (int i=0;i<n;i++)System.out.print(" ");	
}

Exercises doing Right Triangles using Methods

Right Bottom Triangle

Rewrite the program to draw a Right Bottom Triangle of Stars using methods.
[Lecture6/RightBottomTriangle.java]

Right Top Triangle

Rewrite the program to draw a Right Bottom Triangle of Stars using methods.
[Lecture6/RightTopTriangle.java]

Hollow Right Bottom Triangle

Rewrite the program to draw a Right Bottom Triangle of Stars using methods.
[Lecture6/HollowRightBottomTriangle.java]

Hollow Right Top Triangle

Rewrite the program to draw a Right Bottom Triangle of Stars using methods.
[Lecture6/HollowRightTopTriangle.java]

Methods Calling Other Methods

In order to break problems down into smaller and smaller ones it is usual for methods A to call method B and method B to call Method C etc. The following exercise illustrates this.

Easy Exercise

What is the output of [Lecture6/Easy1.java]

cat dog Rabbit cat dog

Methods Calling Other Methods

We can make each shape into a method and put them in a class called Shapes:
[Lecture6/Shapes.java]

Notice how FullSquareOfStars is defined in terms of FullRectangleOfStars. A square is simply a rectangle where the width and height are the same.

Exercises on Methods Calling Methods

Complete Shapes

Add static methods for all the other (hollow shapes) to the class Shapes.

Use Shapes

Write a program using shapes that asks the user to enter an integer and then draws a solid bottom right triangle of the size they enter. [Lecture6/DrawRBT.java]

Re-do Times Table Exercise

Redo the question in section  10.6 using methods. [Lecture6/TimesTable.java]

The Names of Methods

Notice, that if the method is defined in the same class that we are calling it in, we do not need to use the class name in front of the method name when we call it. We have written timestable(x,j) instead of TimesTable.timestable(x,j).

The Names of Formal Parameters

Although methods f and g, below, have different names for their formal parameters, there is absolutely no difference in behaviour between methods f and g
static void f(int n)
{
  System.out.print(n+1);
}

static void g(int banana)
{
  System.out.print(banana+1);
}

Further Example

The calls f(5); and g(5); will both print 6 . As will the program fragments:

int apple=5;
f(apple);

int apple=5;
g(apple);

int n=5;
f(n);

int n=5;
g(n);

int banana=5;
f(banana);

int banana=5;
g(banana);

The names of formal parameter are usually chosen to be as suggestive of their use as possible.

Question

What will the following program fragment output?
int banana=5;
g(banana);
System.out.println(banana);
Answer:
65
The call to g does not affect the value of its parameter.

Hard Exercise Drawing a Hollow Diamond

[Lecture6/HollowDiamond.java]


Non - Void Static Methods

So far all the methods we have written have return type void. Their headings have all started with
static void
This means that they don't return a value. In this section we will look at methods that return values, i.e. their return type is not void. Consider [Lecture6/Easy2.java]

Here, we have declared a method called Bake. It's signature is String Bake(String). This means it has one parameter of type String and it's return type is String. This means we can put a call to Bake in our program wherever we would use a String.

This program prints

fish pie
Why? Simply because Bake("fish") returns the string "fish pie" which we then print out.

Consider [Lecture6/Easy3.java]

This program does nothing. There is no print statement so when we execute the program we will not see anything although the Bake method is called.

In Bake, we have used a return statement. The return statement does two things.

  1. It tells Java what value to return after the method is called.
  2. When the return statement is encountered, the system leaves the method containing it and goes back to the place where the method was called from. Any code not yet reached in a method after the return statement will not get executed in this call.

Differences between void and non-Void Methods

The main differences between void and non-void is that calls to non-void methods can be used in place of expressions and void methods can't. Calls to both can be used in place of statements. If a call to a non-void method is used in place of a statement, then the return value of the method is simply ignored. (As in Lecture6/Easy3.java above.)

It is very important that the reader understands what is an expression and what is a statement. An easy way to remember is that:

In general, a statement does something and an expression returns a value (although an expression can also do something as a side-effect.)

Consider

[LectureNonVoidMethods/Factorial.java]

Example - factorial

The method, factorial, is a non-void method that has signature. int factorial (int). In other words it takes an integer and returns an integer. If we have programmed it properly it will return the factorial of the integer we give it. We use a call to factorial in the print statement so it prints out the factorial of the input in the correct place.

Exercises

Addall

Write a program which asks the user to enter a number $n$, say, and it outputs $1+\cdots+n$. For example, if the user entered 4, the output would be 10. [LectureNonVoidMethods/Addall.java]

Another possible answer you may give if you know the formula is

[LectureNonVoidMethods/Addall1.java]

Array methods

Write non void methods to work out:
  1. The sum of all the elements in an array
  2. The largest of all the elements in an array
  3. The smallest of all the elements in an array
  4. The average of all the elements in an array
Put all the methods in a class called ArrayUseful.

[LectureNonVoidMethods/ArrayUseful.java]

Rewrite Array Sum Average etc

Rewrite the exercise in Section 9.6.2 using the methods you have just defined.

[LectureNonVoidMethods/All.java]

Rewrite Array Assignment

Remember the assignment (section 9.7): Write a program where the user types in a number of strings stored in an array of strings and then the program prints out all the Strings that have the most occurrences of the character 'a'. This is much easier using methods.

[LectureNonVoidMethods/numberOfAs.java]

Mult in Terms of Add

Redo exercise  10.7 using methods.

[LectureNonVoidMethods/Multiply.java]

Power in Terms of Add

Redo exercise  10.7.2 using methods. [LectureNonVoidMethods/Power.java]

Greatest Common Divisor

Euclid's algorithm for finding the GCD of two positive integers $n$ and $m$ is as follows:
  1. if $n=m$ then return $n$
  2. if $n>m$ then subtract $m$ from $n$ and go to 1
  3. if $m>n$ then subtract $n$ from $m$ and go to 1
Write a method GCD for finding the greatest common divisor of two integers.

[LectureNonVoidMethods/GCD.java]

Note the missing components of the for loop

An aside:- while Loops

Notice that in LectureNonVoidMethods/GCD.java we have used a for loop where the initialisation expression and the increment expression are empty. The only bit that is non-empty is the guard. This is called a while loop. We could have written the same program like [LectureNonVoidMethods/GCD1.java]

Clearly, in Java we don't really need both for loops and while loops, as we didn't need both if-else and ifs. Having both forms just makes our programs more readable.

Recursion

Read Chapter 4 of How to Think Like a Computer Scientist [5].

A recursive method is one that calls itself.

Exercises

  1. Write a program fibonacci

    such that java fibonacci n prints out the $n$th fibonacci number. The fibonacci sequence goes 1,1,2,3,5,8,13,21,34,55,89,$\cdots$.

  2. Multiplication of non-negative integers can be defined recursively in terms of addition:-
    mult($n$,0) = 0
    mult($n$,$m+1$) = n+mult($n$,$m$)

    Write a class mult

    which has a method times which implements such a function.

  3. Exponentiation of non-negative integers can be defined recursively in terms of Multiplication:-
    $n^0$ = 1
    ($n^{m+1}$) = n*($n^m$)
    Write a class power

    which has a method power which implements such a function.

  4. Without using vectors or arrays write a program reverse.java

    which reads in characters from the keyboard and prints them out in the opposite order to which they were typed in.


Course work

The Syracuse Sequence starting with 14 goes like this:-
14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1


The rule is if $n$ is even then the next number in the sequence is $n/2$ and if $n$ is odd the next number is $3n+1$.
The sequence stops at 1.

Using recursion, write a program syr.java

which does not contain the word "while", such that for all positive integers, $n$, java syr n prints out the Syracuse sequence starting with $n$.
(try running syr.class to see how your program should behave).

Summary

Being able to define and use methods is a key to successful programming. Having worked on Chapter 11 you will have:


Command Line Arguments

Introduction

Now, at last, you will learn the purpose of the line
public static void main(String [ ] args)
The name args is a formal parameter to the main method. The parameter args is of type array of string. The use of args is straightforward: If we run our program fred.class normally we type java fred, but if we like, we can write anything else we like after java fred, For example:
  1. java fred hello
    

    or

  2. java fred 1 2 3 4
    

    or

  3. java fred fred.java
    

The Strings that we type after java fred are called command line arguments. The command line arguments are passed to the program in the String array parameter of the main method, namely, args. (We could have called args anything we liked. Let's stick to args though.)
In 1., above, there is one command line argument args[0] and its value is the String "hello". In 2, There are four command line arguments:
name value
args[0] "0"
args[1] "1"
args[2] "2"
args[3] "3"

Note: "0","1","2", and "3" are all of type String If we want to add them up we first have to convert them to integers using the method Integer.parseInt().
In 3., there is one command line argument args[0] and its value is the String "fred.java".

The Number of Command Line Arguments

Since args is an array, the number of command line arguments is simply given by the expression args.length. (Recall that, if a is an array then a.length is the number of elements of a.)

Exercises

Add One

Write a program which prints out one more than its command line argument. For example, java AddOne 5 should output 6, etc. [LectureCommandLine/AddOne.java]

Add

Write a program which adds its two command line arguments i.e. java Add 5 6 should output 11. [LectureCommandLine/Add.java]

Backwards

Write a program that allows you to enter as many words as you like as command line arguments and the program prints them out in reverse order. [LectureCommandLine/Backwards.java]

Add All

Write a program that allows you to enter as many integers as you like as command line arguments and the program prints out their sum. [LectureCommandLine/AddAll.java]

Add All Real

Write a program that allows you to enter as many real numbers as you like as command line arguments and the program prints out their sum. [LectureCommandLine/AddAllReal.java]

Exercises - No Solutions

  1. Write a program that prints out the average of all its command line arguments.

  2. Write a program that prints out all the longest of all its command line arguments.

  3. Write a program that prints all its command line arguments backwards. So java back Fred Bloggs should output derf sggolB

Conclusion

You have now come to the end of the first volume of the Java Subject Guide. By now you should be familiar with a lot of the basic concepts of programming. These include: In the second volume, we will be covering more advanced, but essential topics in Object Oriented Programming. These include:

latex

Appendices

Multiple Choice Questions

QUESTION 1



Consider the following program:-

import java.io.*;
public class Echo
{
    public static void main(String[] args) throws IOException
    {
       BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
       String s =in.readLine();
       System.out.println(s);
    }
}
(a)
The program prints hello
(b)
The program waits forever for the user to input something and then outputs whatever they typed in.
(c)
The program waits forever for the user to input something and then gives an error message.
(d)
The program prints s
(e)
None of the above.

QUESTION 2



Consider the following program:-

import java.io.*;
public class Add1
{
   public static void main(String[] args) throws IOException
   {
    BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
    String s =in.readLine();
    System.out.println(x+1);
   }
}
This program has a compilation error.
The error is:-
(a)
Missing '}'
(b)
Variable x is not declared
(c)
Undefined variable, class, or package name: System.out.println(x+1);
(d)
Undeclared variable: s
(e)
None of the above.

QUESTION 3



Consider the following program:-

public class A
{
  public static void main(String[] args) 
  {
   System.out.println("35" + 1);
  }
}
(a)
This program crashes
(b)
This program compiles correctly and outputs nothing
(c)
This program compiles correctly and outputs 36
(d)
This program compiles correctly and outputs 351
(e)
None of the above.

QUESTION 4



Consider the following program:-

import java.io.*;
public class B
{
  public static void main(String[] args) throws IOException
  {
   BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
   String s =in.readLine();
   int x=Integer.parseInt(s);
   System.out.println("Finished");
  }
}

(a)
The program will print hello
(b)
If the user inputs 23 the program will crash.
(c)
If the user inputs hello the program will crash.
(d)
If the user inputs hello the program will print Finished
(e)
None of the above.

QUESTION 5



What is the value of the following expression:- (1<2 && (2<1 || 3==4))

(a)
1
(b)
true
(c)
2
(d)
false
(e)
None of the above.

QUESTION 6



Consider the following statement:-

boolean b = (3==4);

Which of the following is true?

(a)
This produces a compilation error
(b)
The value of b will be true
(c)
The value of b will be false
(d)
The value of b will be 3
(e)
The value of b will be 4





QUESTION 7



Consider the following statement:-

boolean b=3=4;

Which of the following statements is true?

(a)
This produces a compilation error
(b)
The value of b will be true
(c)
The value of b will be false
(d)
The value of b will be 3
(e)
The value of b will be 4

QUESTION 8



Consider the following program:-

import java.io.*;
public class C
{
   public static void main(String[] args) throws IOException
   {
    BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Number>");
    String s =in.readLine();
    int x=Integer.parseInt(s);
    for(int i=1;i<x;i++) System.out.print("*");
    System.out.println();
   }
}
Which of the following best describes its behaviour.
(a)
A horizontal line of n stars will be displayed, where n is the number entered by the user.
(b)
A vertical line of n stars will be displayed, where $n$ is the number entered by the user.
(c)
A vertical line of n+1 stars will be displayed, where $n$ is the number entered by the user.
(d)
A horizontal line of n-1 stars will be displayed, where n is the number entered by the user.
(e)
None of the above.

QUESTION 9



Consider the following program:-

import java.io.*;
public class D
{
   public static void main(String[] args) throws IOException
   {
    BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Number>");
    String s =in.readLine();
    int x=Integer.parseInt(s);
    int t=0;
    for(int i=0;i<x;i++) t=t+i;
    System.out.println(t);
   }
}
The above program has no compilation errors. Which of the following describes its behaviour when the user enters 3.
(a)
The program will output
1
2
3

click here if you think this one is right

(b)
The program will output
0
1
2
click here if you think this one is right
(c)
The program will output
0
1

click here if you think this one is right

(d)
The program will output
6
click here if you think this one is right
(e)
None of the above.

click here if you think this one is right

QUESTION 10



Consider the following program:-

import java.io.*;
public class D
{
   public static void main(String[] args) throws IOException
   {
    BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Number>");
    String s =in.readLine();
    int x=Integer.parseInt(s);
    int t=0;
    if (t==0 && t==3) System.out.println("hello");
   }
}
Which of the following describes its behaviour when the user enters 3.
(a)
The program will output hello
(b)
The program will output nothing at all
(c)
The program will output 0
(d)
The program will not compile
(e)
None of the above.

QUESTION 11



Consider the following program:-

public class T
{
   public static void main(String[] args) 
   { x=4;
     for(int j=1;j<=x;j++)
     {  for(int i=0;i<ZZZ;i++) System.out.print("*");
        System.out.println();
     }
   }
}
What expression should we replace ZZZ by so the program outputs
*
**
***
****

(a)
i
(b)
j
(c)
j+1
(d)
4
(e)
None of the above.
b

QUESTION 12



Consider the method p.

static void p(int n)
{System.out.print(n+1);	
}
Which of the following is a legal call to p?

(a)
p();
(b)
p(3+1);
(c)
p(3,2);
(d)
p("hello")
(e)
None of the above.

QUESTION 13



What is the output of the following program?

public class F
{
  static void L(int n)
  {for (int i=0;i<n;i++)System.out.print("*");	
  }

  public static void main(String[] args) 
  {
   L(4);
  }
}

(a)
***
(b)
4
(c)
It will not compile
(d)
****
****
****
****
click here if you think this one is right
(e)
None of the above.

QUESTION 14



Consider the following program:-

class Array1
{
   public static void main(String[] args)
   {
    int[] nums =new int[3];
    nums[0]=1; nums[1]=1; nums[2]=2;
   }
}
Which of the following statements is correct:-
(a)
The program will not compile
(b)
The program will compile but when it is run it will crash with an `array out of bounds' exception.
(c)
The program will compile and run but output nothing.
(d)
The program will compile and run and output 0 1 2
(e)
None of the above.

QUESTION 15



Consider the following program:-

class Array2
{
   public static void main(String[] args)
   {
    int[] nums =new int[2];
    nums[0]=1; nums[1]=1; nums[2]=2;
   }
}
Which one of the following statements is correct:-
(a)
The program will not compile
(b)
The program will compile but when it is run it will crash with an `array out of bounds' exception.
(c)
The program will compile and run but output nothing.
(d)
The program will compile and run and output 0 1 2
(e)
None of the above.

QUESTION 16



Consider the following program

class Array3
{ 
    public static void main(String[] args)
   {  int k=5;
     int[] nums= new int[k];
     for(int i=0;i<k;i++)nums[i]=i+1;
     for(int i=0;i<k;i++)System.out.println(nums[i]);     
   }
}
Which of the following statements is correct:-
(a)
The program will not compile
(b)
The program will compile but when it is run it will crash with an `array out of bounds' exception.
(c)
The program will compile and run but output nothing.
(d)
The program will compile and run and output
0
1 
2
3
4
5
click here if you think this one is right
(e)
None of the above.

Answers to Exercises

  1. [Lecture1/Henry.java]

  2. [Lecture1/Name.java]

  3. answer:

  4. [Lecture1/answers/three.java]

  5. [Lecture1/answers/ten.java]

  6. Answer:- 1+1

  7. [Lecture1/DollarsToPence.java]

  8. [Lecture1/Everest.java]

  9. [Lecture1/Moon.java]

  10. [Lecture1/Everest1.java]

  11. [Lecture1/TenTimesTable.java]

  12. [Lecture1/OneThreeSevenTimesTable.java]

  13. [LectureVariables/Hello1Boris.java]

  14. Answer: 2

  15. Answer: 4

  16. Answer: 14

  17. Answer: hello hello

  18. Answer: hello 5

  19. Answer: 2

  20. Answer: 2.2

  21. answer:

  22. answer: [Lecture2/answers/Double.java]

  23. [Lecture2/answers/AddTwo.java]

  24. [Lecture2/answers/Average3.java]

  25. [Lecture2/answers/Average4.java]

  26. answer:There isn't one.-Prove it!

  27. answer:[LectureConditionals/AscendingTwo.java]

  28. answer:[LectureConditionals/DescendingTwo.java]

  29. answer:[LectureConditionals/DescendingThree.java]

  30. answer: true

  31. answer:[LectureConditionals/TTAnd.java]

  32. answer:[LectureConditionals/TTOr.java]

  33. answer:[LectureConditionals/TTImplies.java]

  34. answer:[LectureConditionals/Exam1.java]

  35. answer:[LectureConditionals/Exam2.java]

  36. [Lecture4/LineOfAHundredStars.java]

  37. It would print just two asterisks

  38. answer:5

  39. answer:2

  40. answer:4

  41. answer:2

  42. answer:1500

  43. answer:This one goes on for ever! Why?

  44. answer:$0$

  45. answer:This one goes on for ever.

  46. answer: It prints all integers from 0 to 4 inclusive.

  47. answer: nothing

  48. answer: It prints all integers from 0 to 99 inclusive.

  49. answer: nothing

  50. [Lecture4/OtherNumbersUpTo.java]

  51. [Lecture4/NumbersDownTo.java]

  52. [Lecture4/Evens.java]

  53. [Lecture4/Odds.java]

  54. [Lecture4/TenTimesTable.java]

  55. [Lecture4/MultiplesOFThree.java]

  56. [Lecture4/UserEntersMultiple.java]

  57. [Lecture4/SimpleTimesTable.java]

  58. [Lecture4/LargestOfTen.java]

  59. [Lecture4/Largest.java]

  60. [Lecture4/LargestEndWithZero.java]

  61. [Lecture4/guess.java]

    Here we go round the main loop while ! found is true, that is while found is false.

  62. [Lecture4/Factorial.java]

  63. public static int abs(int)
    public static long abs(long)
    public static float abs(float)
    public static double abs(double)
    public static double acos(double)
    public static double asin(double)
    Notice I have left out the parameter name. It is acceptable to do this.

  64. [LectureUsefulMethods/DescendingThree.java]

  65. No. The argument to Math.abs is not a String

  66. Yes. "hello".length() is an int so can be passed to Math.abs(). The value of this expression is 5

  67. Yes. The answer is 10.

  68. Yes. "fruit" is a String, Math.abs("hello".length())-3 is an int (2). So the result is the character at position 2 in fruit namely, 'u'.

  69. No. Compare to expects two Strings, not a String and an int

  70. Yes

  71. Yes. "6" is a String

  72. Yes. "boy".compareTo("6") returns an int so we can add it to 17.

  73. yes

  74. [LectureUsefulMethods/Test.java]

  75. [LectureUsefulMethods/NumberOfas.java]

  76. [LectureUsefulMethods/NumberOfasBetter.java]

  77. answer: Integer decode(String)
    Integer getInteger(String)
    . . .

  78. [LectureArrays1D/Reverse.java]

  79. [LectureArrays1D/Largest.java]

  80. [LectureArrays1D/Input1Answer.java]

  81. [LectureArrays1D/All.java]

  82. [LectureArrays1D/BackwardForward.java]

  83. [LectureArrays1D/Occs.java]

  84. [LectureArrays1D/Longest.java]

  85. j i
    0 0
      1
      2
      3
    1  
      0
      1
      2
      3
    2  

  86. [Lecture5/LeftTopTriangle.java]

  87. [Lecture5/RightTopTriangle.java]

  88. [Lecture5/HollowSquareOfStars.java]

  89. [Lecture5/RightBottomTriangle.java]

  90. [Lecture5/HollowRectangleOfStars.java]

  91. [Lecture5/HollowLeftBottomTriangle.java]

  92. [Lecture5/HollowLeftTopTriangle.java]

  93. [Lecture5/HollowRightTopTriangle.java]

  94. [Lecture5/HollowRightBottomTriangle.java]

  95. [Lecture5/TimesTable.java]

  96. [Lecture5/Multiply.java]

  97. [Lecture5/Power.java]

  98. [Lecture6/LeftBottomTriangle.java]

  99. [Lecture6/LeftTopTriangle.java]

  100. cat dog Rabbit cat dog

  101. [Lecture6/DrawRBT.java]

  102. [Lecture6/TimesTable.java]

  103. [Lecture6/HollowDiamond.java]

  104. [LectureNonVoidMethods/Addall.java]

  105. [LectureNonVoidMethods/ArrayUseful.java]

  106. [LectureNonVoidMethods/All.java]

  107. [LectureNonVoidMethods/numberOfAs.java]

  108. [LectureNonVoidMethods/Multiply.java]

  109. [LectureNonVoidMethods/Power.java]

  110. [LectureNonVoidMethods/GCD.java]

    Note the missing components of the for loop

  111. [LectureCommandLine/AddOne.java]

  112. [LectureCommandLine/Add.java]

  113. [LectureCommandLine/Backwards.java]

  114. [LectureCommandLine/AddAll.java]

  115. [LectureCommandLine/AddAllReal.java]

  116. b

  117. b

  118. d

  119. c

  120. d

  121. c

  122. a

  123. d

  124. e

  125. b

  126. b

  127. b

  128. e

  129. c

  130. b

  131. e

About this document ...

Introduction to Programming in Java - Volume One

This document was generated using the LaTeX2HTML translator Version 99.2beta8 (1.43)

Copyright © 1993, 1994, 1995, 1996, Nikos Drakos, Computer Based Learning Unit, University of Leeds.
Copyright © 1997, 1998, 1999, Ross Moore, Mathematics Department, Macquarie University, Sydney.

The command line arguments were:
latex2html -split 0 -no_navigation sem1.tex

The translation was initiated by sebastian danicic on 2003-06-26


Footnotes

... Textpad2.1
If you are using Unix to compile your programs simply type javac HelloWorld.java at the command line.
... Textpad2.2
If you are using Unix to run your program simply type java HelloWorld at the command line.
...method2.3
Methods will be studied in more detail in Chapters  11, 8 and 11.16.
...public2.4
The use of the word public will be explained later in the course.
...square10.1
We call it a square because the number of horizontal and vertical stars is the same. In fact because the horizontal and vertical spacing is not the same, it will not look like a square because the true height and width are different.


sebastian danicic 2003-06-26