Beruflich Dokumente
Kultur Dokumente
Context
The purpose of this unit is to investigate array data structures and string objects.
Objectives
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.
Study Planning
You should expect to spend approximately 9 hours studying this unit. You may find it
convenient to break up your study as follows:
Equipment/software required
1. Java: how to program. H. M. Deitel and P. J. Deitel, 3rd edition, Prentice-Hall, ISBN:
0-13-012507-5
Online Resources:
1. Frequently-asked questions
2. Additional Source Code Examples
Introduction to Unit 5
arrays
string objects — instances of the String class
As with the previous unit, the concepts in this unit are not all explicitly about object-
oriented programming. However, such concepts as arrays of objects, and objects of the
String class illustrate how the concepts introduced in this unit are important for working
with different kinds of non-primitive variable types, and also for the implementation of
methods that process each member of an array.
The sequence of the topics in this unit is by design — you will understand strings much
easier if you have grasped the concepts of Java character arrays first.
Both of these concepts are related, since the words (and the spaces between them) below
could be represented either as an array or an instance of the String class:
What is an array?
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).
The figure below illustrates an array deliveries, which stores 5 elements, each of type int.
Each element of the array represents how many deliveries were made by a courier in a
working week.
deliveries[]
element value
deliveries[0] 14
deliveries[1] 17
deliveries[2] 22
deliveries[3] 9
deliveries[4] 16
Notice how each of the 5 variables stored in this array (the 5 elements of the array) are
referred to by a combination of the array identifier and the element number (index) inside
square brackets. Also notice how the first element of the array has index 0, rather than 1.
Forgetting this feature of arrays leads to many simple errors when learning to use them.
To declare an array, one must state the type of variables that will be stored within it, and
the identifier of the array.
Imagine we are developing a software system for a restaurant, and we need to be able
to store the number of people who have pre-booked for each evening. For example, if we
wish to store all the bookings for the coming week, we need to store and work with 7
intvariables. Rather than have seven different variables, we can work with an array of 7
intvariables. We shall call this array bookings. For example, the following line:
int bookings[];
declares an array with the identifier bookings, that can refer to a sequence of
intvariables.
Once declared, an array needs to have its size defined. For example, we can define our
bookingsarray to store 7 intvariables as follows:
bookings = new int[7];
To refer to a particular element (variable) in an array, we need to specify the array
identifier and the index of the array element in which we are interested. So, for example
we display the first booking as follows:
System.out.println( booking[0] );
double januarySales;
double februarySales;
//...
double decemberSales;
All the monthly totals can be added together to give an annual total like this:
double annualSales = januarySales + februarySales + marchSales +
aprilSales
+ /* other months */ + decemberSales;
While this strategy is just about viable when there are twelve variables, what would
happen with, say, 2,000 variables? The program would be extremely long and ugly, and
it would be easy to make a mistake and refer to the wrong variable.
An alternative approach is to define an array to store the monthly totals. There are twelve
months in the year, so we need an array with 12 elements. In Java:
januarySales = 1234;
februarySales = 2345;
//... etc
We would write
monthlySales[0] = 1234;
monthlySales[1] = 2345;
// ... etc
We have assumed here that January is month number 0, February is number 1, and so
on, up to December which is number 11. This brings out an extremely important point:
array elements in Java are always numbered from 0, not from 1. This means that if
an array has 100 elements, the last element is numbered 99, not 100, as the first is 0, not
1.
This very often causes confusion for novice programmers; if your Java program reports
errors like "arrayBoundsException" then this mistake is very likely to be the cause.
So how do we add the monthly totals to give an annual total now? Here is the Java:
double annualTotal = 0;
for(int i = 0; i < 12; i++)
annualTotal = annualTotal + monthlySales[i];
In this example we aere using a variable to refer to the appropriate array element, that is,
rather than something like :
monthlySales[0]
we am writing:
monthlySales[i]
This means that if i has the value 3, we are then referring to the monthlySales values for
April. In general, as the value of i changes, we can look at the monthly sales figures for
that month (the i'th month). This ability to use a variable to select a particular array
element is an extremely powerful feature, and is found in almost all programming
languages.
Note the following important points about declaring and defining arrays:
Declaring an array is stating that an array exists, and that it has a particular name
and data type
Defining an array is making an array available of a particular size (a particular
dimension)
The distinction is important, particularly when arrays are passed between
methods.
Declaring arrays
<type> <identifier>;
Examples of array declaration include:
int shoeSizes[];
char initials[];
String names[];
Date appointments[];
All an array declaration does is to state that a particular identifier can refer to an array of
variables of the declared type. No array is set up at this state, just the variable itself. So
we can illustrate this for array initials after declaration as follows:
char initials []
element value
Defining the dimensions of an array
<array_identifier> = <type>[<dimension>];
Examples of arrays having their dimension defined include:
intials = new char[3];
appointments = new Date[365];
No values are placed into the array when it is defined, however, an array element is
created to store each variable of the defined type. So, for example, the array initials
after definition of size 3 can be illustrated as follows:
char initials []
element value
initials [0] ''
initials [1] ''
initials [2] ''
We can place values into these array elements with variable assignment statements. So
for example, to place the characters 'I', 'N' and 'T' into this array we could use the following
statements:
initials[0] = 'I';
initials[1] = 'N';
initials[2] = 'T';
The of these problems is illustrated with the example applet ArrayDefinition below:
import java.applet.Applet;
import java.applet.Applet;
// methods go here
The general form for combining the declaration and definition of arrays is as follows:
Array size
Java arrays provide a value to tell the program the size (number of elements) an array
has been defined with. If arr is an array (of any type) then arr.length is the length of the
array.
Array index
The number that identifies a particular element in an array is called the index. If the
number is actually a variable, then this is called an index variable. An index must be an
integer (i.e. of type int), because it refers to a particular element in an array — i.e.
element 3 or element 0 or element 2000, never anything like element 2.5!
import java.applet.Applet;
class ArrayIndex
{
double x[] = new double[100];
public void init()
{
x[0.0] = 100.0;
}
}
The error produced is:
This is because "0.0" (zero point zero) is not the same to the compiler as "0" (zero). "0.0"
is a floating point number, while "0" is an integer.
The following six sets of Java statements all have the same effect: they set the variable
x equal to the 3rd element of the array array1 (don't forget: the third element has index 2,
not 3):
int x = array1[2];
int x = array1[5-3];
int index = 2;
int x = array1[index];
int index = 5;
int x = array1[index - 3];
int index = 5 - 3;
int x = array1[index];
You should look at each of these lines and ensure that you understand why it produces
the result that it does. The last line introduces something you may not have used before:
the use of a data type (in this case int) before an item of a different type (in this case
the number 2.0, which is a double).
As you may recall from a previous unitt, this form of expression is called a cast. It is an
instruction to the compiler to treat evaluate an expression to a value of the stated type —
converting from some other type. In this case, an array index has to be an integer, so we
tell the compiler to treat 2.0 as an integer. What do you think would happen if we said:
int x = y[(int)2.5];
Of course, 2.5 can't be an integer. In fact what happens in this case is that the compiler
chops off the decimal part of the number, and makes it 2.
An aside about casting
You can't use the cast to convert anything to anything else. For example,
the compiler will produce an error message if you try to compile
int x = (int)"hello";
because "hello" simply cannot be converted to an integer.
A very common way to process all the elements of an array, is to use a loop variable for
the array index.
The loop variable must start at 0, and go up to the <array>.length value. However, we
must be careful not to attempt to retrieve an element with index of <array>.length , since
array index values go from 0 .. (<array>.length - 1).
For example, to total all the values of a double array purchases, we could write the
following loop, without having to know how the array was defined:
double total = 0;
int index ;
element value
purchases[0] 10.11
purchases[1] 5.0
purchases[2] 2.5
3 3 < 3 = false
loop terminates
An error will occur if an index is given for an array, which is either negative, or greater
than the index of the last element of the array (i.e. a value of <array>.lengthor greater).
Such an error is called an array bounds exception.
The program must not attempt to read or change the value of an array element that does
not exist. For example, no array can have an element whose index is less than zero
int y = -1;
myArray[y] = 0;
Note that the compiler does not detect these errors; the error is not noted until the program
is executed. This is true even of the first line, which is manifestly incorrect.
Consider the following application:
class ArrayBoundsException
{
double myArray[] = new double[100];
ArrayBoundsException()
{
myArray[-1] = 0;
}
}
Read section 10.1 - 10.5, 10.11 and 10.13 pp 456-467, 478-477 and 479-481
respectively from Chapter 10 of Deitel and Deitel
We have already met and used strings. Consider this application program:
class ProgramMessage
{
public static void main( String args[])
{
System.out.println("This application is running");
}
}
The following output is produced:
import java.applet.Applet;
import java.awt.*;
As you may have found in the first part of this unit, arrays of characters can be a little
fiddly to deal with, since each character element has to be dealt with individually.
The text "hello" could be seen as a kind of array. It has 5 elements. Element 0 is the
character "h", element 1 is the "e" and so on. This can be written in Java like this:
However, this is not a very useful way of manipulating text except when we need to
process individual characters. Normally we would use a String object to work with such
text.
The String class, provided as 'built-in' by the developers of the Java language, makes
working with sequences of characters much easier. The String class defines methods for
many actions, including:
Strings as objects
An object of class String (note the capital 'S' since this is a class identifier) stores a
sequence of characters. New String objects can be created to have the value of the joining
together of two or more existing strings. New String objects can also be created to have
the value of some modified existing String object. Strings are objects (not primitive data
types) — and so one must think in object terms of Classes, instance objects, methods
and messages
In the same way that numbers like 2 and 3 are assumed to be integers, and numbers like
2.1 and 3.6 are assumed to be floating point numbers (with an integer and a fractional
part), anything in double quotes is assumed by the Java compiler to be a String. So we
can write:
We can also concatenate ('add') strings together to form a new String object, so this
line:
Since Strings are objects, normally they are manipulated by means of methods (described
in the next unit). So, for example, this line:
There are many other methods that can be carried out on Strings; see Deitel & Deitel and
the Java documentation for full details.
String objects are not arrays, therefore we cannot use the square bracket notation to refer
to or change a particular character in a String.
However, we can use the String class method charAt() which allows us to find out what
character is at a particular position in a String object.
So although the String class is very versatile, what we cannot do is something like the
following:
For the same reason, if "text" is a String object, we can't get its length by writing
The reason for this is that the class String provides a length() method, whereas .length
is how we find out the length of an array.
Such differences between [1] and charAt(1), and length verses length() are things
are often confusing when first encountered. However, as you progress in Java
programming you will come to understand why these seemingly arbitrary distinctions
occur.
Computer-based Activities
Activities
Activity 1 – Applet to display and total array elements
(1) Write an applet creates an int array called capacity , which records for 4 machines
how many products they can produce each hour:
(2) add a loop to your applet, so the contents of the array are displayed in the applets
window.
(3) add a loop to your applet that calculates the total capacity of all 4 machines
capacity[0] = 55;
capacity[1] = 34;
capacity[2] = 80l
capacity[3] = 101;
The array should have the values as follows after such actions:
capacity[]
element value
capacity[0] 55
capacity[1] 34
capacity[2] 80
capacity[3] 101
(2) Drawing, by convention, takes place in the Paint() method. So we shall be adding
lines to that method.
We need to display several pieces of text onto the applets graphic area, so we shall
introduce 2 variables to store the current X and Y position of text to be drawn:
We display the class name in the applets window as usual, this time using variables x
and y (and we add 25 to the Y value, so the next text is displayed lower down the window):
A for loop (or we could use a counter controlled while loop) can be used to iterate through
each element of the array. We introduce an integer variable index which will be used to
refer to the index of the current element at any point during the loop.
int index;
The loop needs to start at 0 (since element 0 is the first in an array), and need to go up
to the length of the array (which we can find using the array variable capacity.length ).
Once the value of index reaches capacity.length we should exit the loop (we should not
process the element whose index is capacity.length (i.e. 4) since this would be an array
bounds exception).
{
g.drawString("capacity[" + index + "] = "
+ capacity[index], x, y );
y = y + 20;
}
(3) To calculate the total is quite straightfoward. We need an integer variable in which to
store the total:
int total = 0;
To keep things neat, we shall do the calculation inside the init() method, and the display
of the total inside the paint() method. Since the variable total will need to be referred to
in both these methods, this variable must be declared as an instance variable (i.e. not
local to just a single method).
We can use a for loop, once again, to iterate through each element. In this case the
action for ach element is to simply add its value to our total variable.
// calculate total
int index;
for( index = 0; index < capacity.length; index++)
total = total + capacity[ index ];
At the end of our paint() method we can add a line to display the total in the window:
// display total
g.drawString("Total of values is: " + total, x, y);
10.5
9.01
16.67
11.22
88.33
5.55
(2) Modify your applet to display the values of these variables in the applet's window
(3) Modify your applet to also display the highest value in this array
(1) We need to declare and define a double array sales with 6 elements:
We can place the values into the array inside the init() method as follows:
sales[0] = 10.5;
sales[1] = 9.01;
sales[2] = 16.17;
sales[3] = 11.22;
sales[4] = 88.33;
sales[5] = 5.55;
The array should have the values as follows after such actions:
sales[]
element value
sales[0] 10.5
sales[1] 9.01
sales[2] 16.67
sales[3] 11.22
sales[4] 88.33
sales[5] 5.55
In our paint() method we'll add variables for the (X, Y) position of text, and display the
name of this class:
(2) Just as for the previous activity, we can introduce a for loop, and an index variable.
For each iteration of the loop we should display the value inside the corresponding array
element, and increase the Y position for the next piece of text to be displayed:
(3) Just as for the previous activity, we can add a new instance variable, we'll call it
maximum this time:
double maximum = 0;
We also need to add a statement to display this maximum value inside our paint()
method.
(1) Write an applet that displays a char array called forward containing the letters:
(2) Modify your applet so that a second char array, called backward, is created, that
processes the elements of array forward, and places the reverse values into array
backward.
You should write this code to be general enough so that if the length or values inside
forward are changed, your loop to put values into backward does not need to be changed.
The screen should look as follows when executed:
(3) Test how general your code is, by changing the characters that forward is initialised
to.
char forward[] =
{ 'I', 'N', 'T', '4', '1', '2', '0', ' ', 'J', 'a', 'v', 'a' };
(1) We need to declare and define a char array forward with 5 elements:
We can place the values into the array inside the init() method as follows:
forward[0] = 'h';
forward[1] = 'e';
forward[2] = 'l';
forward[3] = 'l';
forward[4] = 'o';
In fact, we can combine the declaration, definition and initialization of array forward as
follows:
The Java compiler will count how many characappear between the braces to determine
the size of the array.
Whichever way we set up our array, it should have the values as follows after such
actions:
forward[]
element value
forward[0] 'h'
forward[1] 'e'
forward[2] 'l'
forward[3] 'l'
forward[4] 'o'
To display these letters, rather than looping and displaying each character one by one,
we can use the Graphics method drawChars() as follows:
Note, when we display the char array, we indent it slightly on screen by displaying at (x +
10, y) rather than just (x, y).
You may wish to refer to the full listing of ReverseArrayApplet.java — version 1
(2) To create an array backward, which contains the characters of array forward in reverse
order, we must first declare and define an array backward to be the same length as array
forward.
char backward[];
Now, we need to add some more code in out init() method, to loop through the elements
of array forward, and place them in their appropriate locations in array backward.
What we wish to achieve, for example when array forward contains 'h', 'e', 'l', 'l', 'o', is
the following:
forward[] backward[]
So
Thus, the loop we need to write in method init() to create our backward array is:
To display the char array backward, we can use the Graphics method drawChars again:
y = y + 30;
// Display "char array 'backward' contains:" in window
g.drawString("char array 'backward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( backward, 0, backward.length, x + 10, y );
(3) Apart from the changed line initialising array forward, no other changes should be
necessary !
Write a Java applet that counts the number of spaces in the string of text "the cat sat on
the mat". It should do this by using a String variable and a loop.
First we need to declare and initialise out String object (we'll call it text):
we will also need an int variable to count the integer number of spaces. This we shall
call numberOfSpaces and we will initialise it to zero (since at this point no spaces have
been counted):
int numberOfSpaces = 0;
We will need loop through each position of the String text. For this we can use a for
loop, and a counter (which will refer to the position of the character in the String being
looked at for the current loop iteration). A Java programming convention is to call the int
counter i if the code is so simple it should be obvious what i is in the loop statements
(short variables names make code shorter, but must be weighed with writing code that is
hard to understand).
Our loop counter i should start at 0 (the position of the first character in the String object),
and should end at text.length(). We must write our code so the loop terminates when I
reaches XX, there is no character in the String at position text.length() — the characters
are from 0 .. text.length() - 1 :
For each iteration of our loop, we need to test (we'll use an if statement) whether the
current character in the String object is a space or not. If the character is a space, then
we should add 1 to our numberOfSpaces variable.
numberOfSpaces++;
One the loop has terminated, we can draw a message in the applet's window, stating how
many spaces were found:
You may wish to view the complete listing for this solution: CountSpaces1.java.
For example, given the name "Mary Smith" it should display "htimS yraM".
Use only String objects (i.e. not arrays of characters) in your applet.
The screen should look something similar to the following when executed:
Reversing a string
We need to work with (at least) two String objects, let's call them forwards and backwards.
We can initialize the forward String object with the text to be reversed, for example
"hello":
The solution we shall adopt is to create a loop, that will retrieve the characters from the
forwards String in reverse order. The location of the last character in String forwards is
forwards.length() - 1, since the first character is at position 0. We shall create an int
variable called lastCharPos to store this value, to make our loop easier to read:
In our loop, we shall use an int variable i to refer to the position of the character we are
currently working with, so our loop starts as follows:
int i;
Notice the use of the decrement operator --, this means that after each execution of the
loop the value of variable i is reduced by 1. Also note that the loop will continue while i
>= 0 — the loop will terminate as soon as i becomes less than zero.
All that remains is the action to perform within the loop. We wish to retrieve a character
at a time from the forwards String, and append (stick it on the end) of the a new String
we are creating for variable backwards. Strings cannot be changed once created — they
are immutable. However, a String variable, such as backwards can be made to refer to a
different object. For each iteration of the loop we shall create a new String object, formed
by appending (also called concatenating) the existing String referred to by the backwards
variable, with the current character in the forwards String:
NOTE:
There is, in fact, a more concise way to write the loop statement that concatenates
backwards with the character from forwards:
since the + is actually a String operator that will automatically create a new String object
as the evaulation of the expression.
In fact, we could make this expression even shorted, by using the += concatenation
operator:
backwards += forwards.charAt( i ) ;
Exercises
(1) The following line of code will declare a variable with the identifier (variable name) of
surName, that is able to refer to an array of char variables:
char surName[];
(2) To declare our ages array, able to refer to an array of int variables:
int ages[];
(3) To declare our things array, able to refer to an array of Object variables:
Object thingsp[];
(4) The following will now define array surName to have a size of 20 char variables:
(5) The following will now define array ages to have a size of 5 int variables:
(6) The following will now define array things to have a size of 1000 Object variables:
(7) We can combine the statements for declaring an identifier that can refer to an array of
a certain type of variables, and the definition of how many of that type of variables the
array is to store. The following line declares an array address to be able to store 55 char
variables:
What is it about the way the compiler works than means that it can't detect array bounds
exception errors?
Discussion of Exercise 2
The compiler only checks the syntax of the program, not its logic. The Java syntax rules
simply say that the array index must be an integer. That the integer must be greater than
or equal to zero is not an issue of syntax, but of logic. The compiler is not designed to
detect logical errors. If the computer could do this, we wouldn't need programmers!
Complete the following statements that summarize the concepts explored in the 'Arrays'
section of this unit:
Arrays are used to represent a sequence of _________ (possibly a large number) all of
the same type, when we don't want to assign an identifier to each variable.
Arrays are very often used in conjunction with _____, so that some action can be
performed upon every variable in the array.
Discussion of Exercise 3
Arrays Summary
Arrays are very often used in conjunction with loops, so that some action
can be performed upon every variable in the array.
Complete exercises 7.8, 7.12 from Chapter 7 of Deitel and Deitel pp 305-306.
Complete the following statements that summarise the concepts explored in the 'Arrays'
section of this unit:
Strings are _______ (not _________ data types) — and so one must think in object
terms of _______, instances, _______ and messages
New String objects can be created to have the value of the _____________ (joining
together) of two or more existing strings.
Discussion of Exercise 5
Strings Summary
Strings are objects (not primitive data types) — and so one must think in
object terms of Classes, instances, methods and messages
New String objects can be created to have the value of the concatenating
(joining together) of two or more existing strings.
Arrays
Review Question 1
What is an 'array bounds exception'? What array indexes will always produce and array
bounds exception, however large the array is?
An array bounds exception is the error generated when a program tries to read or write
an element of an array and the index is beyond the size of the array. Any negative number
used as an array index will produce an array bounds exception. For example:
x[-1] = 0;
will always produce an array bounds exception, however large the array `x' is.
Likewise, an index of <array>.length or greater will also always created an array bounds
exception.
Review Question 2
Assuming I have a way of storing the daily temperatures in the array, how could I work
out the average annual temperature? Write a few lines of Java to do this (not a whole
program).
double total = 0;
for (int i = 0; i < 365; i++)
total = total + dailyTemperature[i];
double average = total / 365;
Strings
Review Question 3
string s1 = "Java";
string s2 = "is";
string s3 = "easy";
System.out.println( s1 + s2 + s3 );
Javaiseasy
Many students assume that when words are concatenated (joined) together, spaces are
inserted automatically. However, this is not true. If you want spaces you have to put them
in yourself, for example:
Review Question 4
String s = "abc";
System.out.println(s[1]);
The error is due the fact that s is a String object, not an array. We can't use the square
bracket notation on objects.
To access the first character of String s we need the charAt() method instead.
String s = "abc";
System.out.println(s.charAt(1));
Review Question 5
If two Strings contain the same text, then we would expect them to be equal in some
sense. For example, consider this section of Java:
Because both contain the word "hello". In fact, neither line is printed; Java does not think
the "hello" is equal to "hello"! This may seem rather odd at first. If x and y were integers,
and both had the value 2 , thJava would think x and y were equal. So why does Java
treat Strings and integers differently in this respect?
(Hint: what is different in the way these data types are implemented).
There is a short answer to this question, and a longer one which takes into account the
philosophy behind the answer (i.e. why Java works this way).
If we can't use == to test whether two strings have the same text, how can we do it?
Integers are primitive data types. There is only one way that integers can be equal: they
have the same number. Strings, however, are objects.
When are two objects equal? This is a rather difficult point. Here is an example. Kevin
owns a lap-top computer, a Dell Inspiron 3000. The Dell corporation has made many
thousands of these computers; perhaps you own one as well. If you do, is your Dell
Inspiron 3000 equal to Kevin's Dell Inspiron 3000? It may be identical in every respect,
but it is not the same machine. This is the key concept. In Java, for two things to be equal,
they must refer to the same thing, rather than referring to things that have the same value.
Another example could be that there are 2 copies of the same book in a library. These
two objects are not the same object, so Fred could borrow copy 1 and Yolanda could
borrow copy 2. Most likely a librarian will number the copies so that each can be referred
to individually. It is the same with Java, each object has a unique reference (i.e. its location
in memory). Two objects might have the same values, but if they are stored at different
locations in memory then Java will not consider them to be the same object. However,
two variables could both refer to the same object (i.e. the same location in memory), in
which case these two variables would both be referring to the same object, and Java
would consider them to be equal.
Just because string1 and string2 contain the same text, this does not make them the
same string, anymore than your computer is the same computer as Kevin's computer just
because it is the same model.
To test whether two strings have the same text values, we can write:
If( string1.equals(string2) )
{
System.out.println("strings 1 and 2 are equal");
}
Discussion Topics
There are many new concepts in this unit. If you want to discuss with your colleagues or
make comments about the concepts to them, use the on-line facilities.
Discussion Topic 1
Arrays provide an effective way to process text character by character. Strings provide
an effective way to process text as units — for example 5 lines of text could be stored in
5 Strings, or in fact all in a single String.
The developers of Java recognised that for different software systems text needs to be
dealt with in both ways. They therefore provided the array type and the String class, and
appropriate operators and methods to make the writing of programs to handle text
straightforard.
Discussion Topic 2 — Why use the UNICODE rather than ASCII character set?
Most computer programming languages use something called the ASCII coding scheme
to do this. In this scheme, for example, the letter `A' is number 65, `B' is 66 and so on.
This scheme has a maximum of 256 symbols (because this is the largest number that
can be stored in one byte). Java, on the other hand, uses the UNICODE coding scheme,
where each symbol has a number between 0 and 65535 (two bytes). This means that a
text string in Java requires twice as much memory as it would in most other languages.
Why did the Java developers make this decision? What are the advantages and
disadvantages?
Contribution for Discussion Topic 2
By choosing an international standard the Java character set is both well defined and
understood. Also UNICODE requires two bytes because of the very large range of
international characters and symbols it provides — UNICODE supports many different
alphabets, well beyond the European symbols supported by ASCII.
In your Learning Journal write up your experience of your learning on this unit. Say what
you thought was good or bad, what you had difficulty understanding, and how you
resolved your problems.
Code listings
Listing of CountSpace.java (See the comment for the program it's for reverses
a text
string )
// CountSpace1.java
// A program that reverses a text string.
// Note that there are many ways to do this; this program only
demonstrates one way
// Kevin Boone, August 1999
import java.applet.Applet;
import java.awt.*;
public class Reverse1 extends Applet
{
public void paint (Graphics g)
{
// 'text' is the String to be reversed
String text = "Fred Bloggs";
// Start by creating a character array of exactly the same
// length as `text'.
// This is because Java allows individual elements of an array
// to be changed,
// but not individual characters of a String
char reversedText[] = new char[text.length()];
// Now move each character in `text' to the right place in
// `reversedText'
for (int i = 0; i < text.length(); i++)
reversedText[i] = text.charAt(text.length() - i - 1);
// `reversedText' is an array; Java will not allow us to use
//`drawString' to
// print an array (it can only print Strings). So we create a new
//String
// that has exactly the same text as `reversedtext'
String reversedTextString = new String(reversedText);
// Now print the String
g.drawString (reversedTextString, 20, 40);
}
}
}
} // class
// methods
public void init()
{
// nothing needed here for version 1 !
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Reverse Array Applet - version 1", x, y );
y = y + 20;
// Display "char array 'forward' contains:" in window
g.drawString("char array 'forward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( forward, 0, forward.length, x + 10, y );
}
} // class
Listing of CountSpace1.java
/ / CountSpace1.java
// A program that counts the spaces in a text string
// Kevin Boone, August 1999
// modified Matt Smith, Sep 1999
// <APPLET code="CountSpace1.class" width=275 height=200></APPLET>
import java.applet.Applet;
import java.awt.*;
public class CountSpace1 extends Applet
{
public void paint (Graphics g)
{
int numberOfSpaces = 0;
String text = "The cat sat on the mat";
g.drawString ("Counting spaces in '" + text + "'", 20, 20);
Listing of StringReverse.java
// StringReverse.java
// Create a String object whose characters are the reverse of another String
object
// <APPLET code="StringReverse.class" width=275 height=200></APPLET>
import java.applet.Applet;
import java.awt.*;
(Airline Reservations System) A small airline has just purchased a computer for its new
automated reservations system. You have been asked to program the new system. You
are to write a program to assign seats on each flight of the airline’s only plane (capacity
10 seats).
If the person types 1, your program should assign a set in the smoking section (seats 1-
5). If the person types 2, you program should assign a seat in the non-smoking section
(seats 6-10). Your program should then print a boarding pass indicating the person’s
seat number and whether it is in the smoking or non-smoking section of the plane.
Use a single dimensional array to represent the seating chart of the plane. Initialise all
the elements of the array to 0 to indicate that the seats are empty. As each seat is
assigned, set the corresponding elements of the array to 1 to indicate that the seat is no
longer available. Your program, should of course, never assign a seat that has already
been assigned. When the smoking section is full, your program should ask the person if
it is acceptable to be placed in the non-smoking section (and vice versa). If yes, make
the appropriate seat assignment. If no, print the message “Next flight leaves in 3 hours”.
(This is Exercise 7.18 p 308 , Chapter 7 of Deitel and Deitel)
Additional Activit y 2