You are on page 1of 32

Object-Oriented Software

Development

Tutorial 3
Objectives
• Understand the Control of Execution;
• Understand and able to use array and Strings in
Java programs.
• Explain the difference (and similarities) between
strings and arrays of characters.
• Declare an array, define, interrogate and change
individual elements of an array.
• Declare and work with instances of the String
class.
• Implement Java programs illustrating the
manipulation of arrays and strings.
2
Branch of execution
Branch of execution is also called control
statement.
There are 3 kinds of control statements:
1. method calling;
2. Selection – if .. else and switch .. case;
3. Iteration - looping.

3
1. Method calling
Example:
int lengthOfString = text.length;
//the class String provides a length() method,
whereas .length is how we find out the
length of an array.

4
2. Selection: IF…ELSE
• If (test)
statement to execute if test was true
else
statement to execute if test was false
• If (temperature > 78)
{
soundAlarm( );
displayFlashingLight(red);
}
else
displayFlashingLight(green);

5
3. Iteration in Java
There are three forms of iteration statement
implemented in Java:
• While
• For
• Do…while

6
Iteration: WHILE
• The statement repeated until the test is false.
counter = 0;
while (counter < 5)
{
System.out.println( counter );
counter = counter + 1;
}
7
Iteration: FOR
• Particularly useful for concisely writing counter
controlled loops.
// FOR loop
int counter;
for (counter = 0; counter < 10; counter = counter + 1)
{
<action1>
<action2>
}
8
What is an array?
• Read section 7.1-7.4 pp 314-328 of Chapter 7
Deitel and Deitel.
• An array is a way of storing, retrieving and
changing a sequence (i.e. ordered collection) of
variables that are all the same type.
• An array has an identifier (name), stores elements
all of the same type, and has an unchanging size
(dimension).

9
array
• If we wish to store all the booking for the coming
week, we need to store and work with 7 int
variables. Rather than have seven different variables,
we can work with an array of 7 int variables.
int bookings[];
• Once declared, an array needs to have its size
defined.
Bookings = new int[7];
• To refer to a particular element in an array, we need
to specify the array identifier and the index of the
array element in which we are interested.
System.out.println(booking[1]);

10
Motivation for using arrays
• There are twelve months in the year, so we need
an array with 12 elements:
double monthlySales[] = new double[12];
• Then instead of writing
januarySales = 1234;
februarySales = 2345;
• We would write
monthlySales[0] = 1234;
monthlySales[1] = 2345;
11
Array elements
• We have assumed that January is month
number 0, February is number 1, and so on,
up to December which is number 11.
• Array elements in Java are always
numbered from 0, not from 1.
• If an array has 100 elements, the last
element is number 99, not 100, as the first is
0, not 1.

12
Add the monthly totals
Double annualTotal = 0;
For (int i = 0; i < 12; i++)
annualTotal = annualTotal + monthlySales[i];
If i has the value of 3, it is referred to April.
It is a powerful feature to use a variable to select
a particular array element.

13
Declaring arrays
• State that an array exists, and that it has a
particular name and data type.
• The general form of an array declaration is:
<type> <identifier>;
• Examples of array declaration include:
int shoeSizes[];
char initials[];
String names[];
Date appointments[];
14
Defining the dimensions of an array
• The general form of defining an array dimension
is:
<array_identifier> = <type>[<dimension>];
• Example:
initials = new char[3];
appointments = new Date[365];
• We can place values into these array elements:
initials[0] = “I”;
initials[0] = “N”;
initials[0] = “T”;
15
Common errors
• Having a different type when declaring and
defining an array;
• Forgetting the double square brackets “[“
“]” when declaring and defining an array.

16
Array errors
import java.applet.Applet;
class ArrayDefinition extends Applet
{
double monthlySales[];
public void init()
{
monthlySales = new int[12];
}
}
// The error is that the array monthlySales has been
declared as an array of type double, but it is
defined as int when the dimension is defined.
17
Second common array error
import java.applet.Applet;
class ArrayDeclaration extends Applet
{
double dailyCosts;
public void init()
{
dailyCosts = new double[31];
}
}
// The line double dailyCosts;
is valid, but it only declares dailyCosts to be the
identifier of one double variable – not as an array.
18
Combining declaration and definition error
import java.applet.Applet;
class SalesArray extends Applet
{
double monthlySales[12];
//methods go here
}
// Java insists on separating declaration and definition
of array. However, you can combine them as:
double monthlySales[] = new double[12];
The general form is:
<type> <identifier> = new <type>[<dimension>];

19
Array size
• If arr is an array then arr.length is the length
of the array.
int arr = new int[100];
System.out.println(arr.length);
//Will print out the number 100 as there are
100 elements in array arr.

20
Array index
• The number that identifies a particular
element in an array is called the index.
• An index must be an integer.
• Example: int x = array1[(int)2.0];
is valid. This form of expression is called a
cast.

21
Looping with the array index
double total = 0;
int index;
for (index = 0; index < purchases.length; index++)
total = total + purchases[index];
//If purchases[0] = 10.11,
purchases[1] = 5.0, and
purchases[2] = 2.5,
the value of total after the loop terminates is 15.61.

22
Array bounds exceptions
• An error will occur if an array index is negative,
or greater than the index.
• Example:
double myArray[] = new double[100];
• All the following lines will cause a run time error:
myArray[] = 0;
myArray[100] = 0;
myArray[200] = 0;

int y = -1;
myArray[y] = 0;
23
strings
• Read section 10.1-10.5,10.11 and 10.13 pp 537-547,
555-557 and 559-560 respectively from Chapter 10 of
Deitel and Deitel.
• Strings – sequences of characters treated as an object.
Class ProgramMessage
{
Public static void main(String args[])
{
System.out.println(“This application is running.”);
}
}
//String objects are instance of the String class.

24
The String class
• Defines methods for many actions:
• Finding the length of a string;
• Locating a character or sub-string within a
string;
• Concatenating two strings together to create
a new String object;
• Converting primitive types to Strings;
• Comparing the values inside String objects.
25
Strings as objects
• Anything in double quotes is assumed by the Java
compiler to be a String.
String text = “hello”;
Or
String text = new String(“hello”);
• String objects can be concatenated:
String text = new String(“hello”+” ”+”there”);
Will set the String object, text, to “hello there”.

26
String method
Example:
newText = text.substring(1,3);
• Will make the string, newText, equal to the
first, second and third characters from the
String text.

27
Individual characters in String
objects: charAt()
Example:
String text = “hello”;
Char x = text.charAt(1);
//x = “h”.

28
Length of String objects
Example:
int lengthOfString = text.length;
//it will return an integer value.
//the class String provides a length() method,
whereas .length is how we find out the
length of an array.

29
Review Question 1

• What keywords are associated with iteration


(repetition or looping) in the Java language?

Hint: there are 5 in total, but some of them


are concerned with stopping a loop and have
not been mentioned in this unit, although they
are commonly used and are discussed in
Deitel & Deitel
30
Review Question 2
• What keywords are associated with
selection in the Java language?

31
Discussion 1 – case-sensitivity
issues
• Misspelling of identifier names is a major source of error for novice
(and other) programmers. For example, if I write
• System.out.Println("hello");
• where I really meant
• System.out.println("hello");
• then this is an error, and the compiler will display an error message.
Note that it does not say:
• 'You have `Println'
• it says:
• ``method `Println(String)' not found
in class ... ''
32

You might also like