Unit 9 Arrays, Strings & StringBuilder Flashcards

1
Q

Arrays:- Write a declaration for an array variable, bank, which can reference an array object whose elements are Account objects.

A

Account [] bank;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Arrays:- In an Array, explain the term component

A

Component –an array object consists of a fixed number of components. Each component is like a variable that can hold a primitive value or a reference to an object, depending on the array’s component type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Arrays:- In an Array, explain the term component type

A

Component type –this is the declared type of an array’s components. Each component of an array object has the same type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Arrays:- In an Array, explain the term element

A

Element –an element is the content of an array component. An array element is either a primitive value or a reference value of the declared component type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Arrays:- Once an array has been declared, is this a legal creation of an array

roster = new String [7];

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Arrays:- Once an array has been declared, is this a legal creation of an array, and what it the last index number

Enter ZERO if illegal

int numOfElements = 7;

roster = new String[numOfElements];

A

Yes it is legal The last index number is 6 Note that, because of zero-based indexing, the length of an array is always one more than its last index. For example, the roster array’s last index is 6, even though its length is 7.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Arrays:- What is the length of this array?

Enter ZERO if it is an illegal creation

String[] roster;

int num = 6;

roster = new String[num + 1];

A

7

This is a legal way of creating an array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Arrays:- If an array is created with length 7 and the first six components are filled, leaving the last component empty, what is the last component’s default value if its component type is :-

  • Reference Type?
  • Numerical primitive types? (double and int)
  • Boolean type?
  • Char? (Unicode value)
A

the references are automatically initialised on creation using default values. If the component type of the array is a reference type then each element is initialised to null;

if the component type is one of the numerical primitive types (double, or int, for example) then each element is initialised to 0.0 or 0 as appropriate.

If the component type is a boolean, the elements are initialised to false, and

if it is a char, the elements are initialised to the null character (the character with Unicode value 0).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Arrays:- Write a single statement that both declares a variable bankBalances, and assigns to it an array object that can hold 52 numbers of type double.

A

double[] bankBalances = new double[52];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Arrays:- Write a single statement that both declares a variable frogPond, and assigns to it an array object that can hold references to three Frog objects.

A

Frog[] frogPond = new Frog[3];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Arrays:- Declare an array variable roster with length 6, and populates it with the String objects referenced by the Strings; Jay, John, Anne, Ali, Agi and Jill.

A

String[] roster = {“Jay”, “John”, “Anne”, “Ali”, “Agi”, “Jill”};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Arrays:- Create an array where 3 elements of frogPond are initialised with a reference to a different newly initialised Frog object. So frogPond can hold and does hold three newly created frogs.

A

Frog[] frogPond = {new Frog(), new Frog(), new Frog()};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Arrays:- Will this compile?

Frog[] frogPond;

frogPond = {new Frog(), new Frog(), new Frog()};

A

No, the second line is not valid this syntax can be used only if the array initialiser is assigned to an array variable in the same statement as the array variable is declared

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Arrays:- Will this compile?

Frog[] frogPond;

frogPond = new Frog[]{new Frog(), new Frog(), new Frog()};

A

Yes This style allows us to use the array initialiser syntax and to separate the declaration of the array variable from the creation and initialisation of the array object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Arrays:- In a single statement, declare an array variable, hours, with a component type of int, and assign to it an array that has each of its five components initialised to 40.

A

int[] hours = {40, 40, 40, 40, 40};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Arrays:- True or false? If an item is assigned to a component that already contains an element, the new item overwrites the original element, just as with a normal variable.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Arrays:- Which statements, if any, are valid, when int num = 2;

Statement one:

weights[num] = 58.3;

Statement two:

weights[num + 1] = 57.5;

A

the statements are both valid

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Arrays:- Write code to generate a dialogue box that requests a user to enter their name (the default answer should be “anonymous”), and assign the response to the first component of an array referenced by roster. Assume that roster has already been declared as an array of strings.

A

roster[0] = OUDialog.request(“Please enter your name”, “anonymous”);

Or, using local variable

response = OUDialog.request(“Please enter your name”, “anonymous”);

roster[0] = response;

Note that ‘first component’ always means the component with index 0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Arrays:- Write a declaration for an array variable, quizAnswer, which can reference an array object whose elements are boolean values.

A

boolean[] quizAnswer;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Arrays:- Suppose that we declared a variable frogPond and initialised it to reference an array of Frog objects, as follows:

Frog[] frogPond = new Frog[3];

Here is one way we could assign a newly initialised Frog object to the component of the array at index 0:

frogPond[0] = new Frog();

Now, using a “temp” variable to reference the new Frog object, change a frog’s position to 2 and colour RED and then assign it to frogPond’s second component.

A

Frog temp;

temp = new Frog();

temp.setPosition(2);

temp.setColour(OUColour.RED);

frogPond[1] = temp;

  • frogPond[0] is a newly created frog, position one, colour green
  • frogPond[1] is now position 2 and red
  • FrogPond[2] is still ‘null’

temp.right(); and temp.brown(); Will effect frogPond[1] and temp as they are one in the same.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Arrays:-

Are Arrays substitutable?

A

Substitutability means a subclass type is compatible with a superclass type

Frog kermit = new HoverFrog();

Arrays are the same

frogPond[2] = new HoverFrog();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Arrays:- Is the following a valid declaration and initialisation of an array?

Object[] anArray = {new HoverFrog(), new HoverFrog()};

A

Yes, anArray has been declared with component type Object, which is a superclass of HoverFrog.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Arrays:-

  1. Create a new array object, referenced by nameArray, that can hold references to six String objects.
  2. Write a statement that will assign the length of nameArray to a variable called len.
  3. Assign the following strings to the components of nameArray (in the given order, starting at index 0). “Ann” “Rob” “Kin” “Sue” “Fethi” “Jo”.
  4. Replace the string element “Sue”, that is stored in nameArray, with “Lin”.
  5. Replace the name at index 2 of nameArray with a name entered by the user using a dialogue box.
  6. Create an array referenced by intArray that contains the integers 10, 5, 7, 2, 9, 8, 1 and 12 (in this order).
  7. Create an array frogPond that can hold references to three Frog objects, and assign a new Frog object to each component (the Frog objects should be in their initial state).
A
  1. String[] nameArray = new String[6];
  2. int len = nameArray.length;

will assign the length of the array to an int variable len.

3.

nameArray[0] = “Ann”;

nameArray[1] = “Rob”;

nameArray[2] = “Kin”;

nameArray[3] = “Sue”;

nameArray[4] = “Fethi”;

nameArray[5] = “Jo”;

  1. nameArray[3] = “Lin”;
  2. nameArray[2] = OUDialog.request(“Enter your name”, “anonymous”);
  3. int[] intArray = {10, 5, 7, 2, 9, 8, 1, 12};

7.

Frog[] frogPond = new Frog[3];

frogPond[0] = new Frog();

frogPond[1] = new Frog();

frogPond[2] = new Frog();

Alternatively you could have written:

Frog[] frogPond = {new Frog(), new Frog(), new Frog()};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Arrays:- Given the array roster, created as follows:

String[] roster = {“Jay”, “John”, “Anne”, “Ali”, “Agi”, “Jill”};

Write down what would result from executing the following statements.

  1. System.out.println(roster[1]);
  2. String name = roster[5].toUpperCase();
  3. OUDialog.alert(roster[roster.length -2]);
A
  1. The string “John” will be displayed via the default output device (in the OUWorkspace this would be the Display Pane).
  2. The message toUpperCase() is sent to the String object at index 5, and the message answer “JILL” is assigned to name.
  3. An alert dialogue displays the string “Agi”. (Here is why: roster.length evaluates to 6, then 2 is subtracted from this to give 4; so the string at index 4 of roster is used as the argument to the alert() method.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Arrays:- Given the following code:

double[] doubleArray = {2.5, 3.5, 2.0, 2.0};

describe the effect of evaluating each of the following (assume that the array is initialised as above before each expression or statement is evaluated):

  1. (doubleArray[1] + doubleArray[0]) / doubleArray[3]
  2. doubleArray[3] = doubleArray[0] + doubleArray[1] + doubleArray[2];
  3. (Given index [3] returns to original value) (int) doubleArray[0] > (int) doubleArray[3]
A
  1. (3.5 + 2.5) / 2.0 is evaluated and the result is 3.0.
  2. (2.5 + 3.5 + 2.0) is evaluated and the result is 8.0. This is assigned to the component at index 3 of doubleArray.
  3. The value of doubleArray[0] is cast to an int, which gives the result 2. The value of doubleArray[3] is cast to an int, which gives the result 2. Finally 2 > 2 is evaluated, and the result is false.
26
Q

Arrays:- Given an array, frogPond, containing references to three Frog objects, write down statements or expressions that achieve the following tasks.

(a) Prints the colour of the Frog object at index 2.
(b) Displays the position of the Frog object at index 0 in an alert dialogue box.
(c) Sets the colour of the Frog object at index 1 to be the same as the colour of the Frog object at index 2.
(d) An expression that evaluates to true if the two Frog objects at index 1 and index 2 have the same position, and false otherwise.

A

(a)  System.out.println(frogPond[2].getColour());
(b)  OUDialog.alert(String.valueOf(frogPond[0].getPosition()));   

(Recall that you must convert an int value to a string before it can be used as an argument to the alert method.)

(c)  frogPond[1].sameColourAs(frogPond[2]);
(d)  frogPond[1].getPosition() == frogPond[2].getPosition()

27
Q

Arrays:- Given

String[] nameArray = {“Ann”, “Rob”, “Kin”, “Sue”, “Fethi”, “Jo”};

Write code to

  1. Display the name referenced by the component at index 4 of nameArray in a dialogue box.
  2. Compare the strings referenced by the components at index 0 and index 1 of nameArray for equality.
  3. Declare a variable, tempString, to be of the same type as the component type of nameArray, and assign to it the name referenced by the component at index 1 of nameArray.
  4. Swap the positions of the strings at index 1 and index 4 in nameArray. Inspect nameArray. (Hint: you have already got a reference to the name at index 1 of the array in tempString from part 3, so you can overwrite this in the array without losing the original string.)
A
  1. OUDialog.alert(nameArray[4]);
  2. nameArray[0].equals(nameArray[1]);

Recall that the message equals() (and not the operator ==) should be used when checking if two strings represent the same sequence of characters. In practice we would want to use the returned value in some way.

  1. String tempString = nameArray[1];

4.

String tempString = nameArray[1];

nameArray[1] = nameArray[4];

nameArray[4] = tempString;

In part 3 you assigned the string at index 1 to the variable tempString. Here (in part 4) the second line assigns the element at index 4 to the component at index 1 (overwriting it). The last line assigns the String object referenced by tempString to the component at index 4.

28
Q

Arrays:- Given

int[] intArray = {10, 5, 7, 2, 9, 8, 1, 12};

Write code

(a) intArray[0] + intArray[6]
(b) intArray[7] / intArray[2]
(c) intArray[0] + intArray[4] * intArray[3]
(d) intArray[4] / 2.0
(e) Replace the element at index 7 of intArray with a value twice its current value.
(f) Replace the element at index 3 of intArray with the sum of the elements at indexes 1 and 2.

A

The values of the expressions are:

(a) 11
(b) 1
(c) 28
(d) 4.5

The statements required are:

(e) intArray[7] = intArray[7] * 2;
(f) intArray[3] = intArray[1] + intArray[2];

29
Q

Arrays:- Given

Frog[] frogPond = {new Frog(), new Frog(), new Frog()};

  1. Change the colour of the Frog object at index 2 of frogPond to red.
  2. Cause the Frog object at index 0 of frogPond to move right.
  3. Change the colour of the Frog object at index 0 of frogPond to be the same as the colour of the Frog object at index 2 of frogPond.
  4. Add 3 to the current position of the Frog object at index 2 of frogPond.
  5. Swap the Frog object at index 1 with the Frog object at index 0 of frogPond. (You will need to declare a temporary variable to do this.)
A
  1. frogPond[2].setColour(OUColour.RED);

frogPond[2] references the Frog at index 2, and it is sent the message setColour(OUColour.RED).

  1. frogPond[0].right();

frogPond[0] references the Frog at index 0, and it is sent the message right().

  1. frogPond[0].sameColourAs(frogPond[2]);

frogPond[0] references the Frog at index 0, and it is sent the message sameColourAs() with the argument being the Frog object at index 2.

  1. frogPond[2].setPosition(frogPond[2].getPosition() + 3);

The argument of the message setPosition() is formed by getting the position of the Frog object at index 2 and adding 3 to it. The resulting setPosition() message is sent to the Frog object at index 2.

5.

Frog tempFrog = frogPond[1];

frogPond[1] = frogPond[0];

frogPond[0] = tempFrog;

note that the variable tempFrog must be declared to be of the same type as the component type of the array (which here is Frog).

30
Q

Arrays:- Using paper and pencil, write the code to declare and create an array called hoursWorked that can hold 52 double values, and initialise each component to 40.0

A

double[] hoursWorked = new double[52];

for(int i=0; I < hoursWorked.length; i++)

{

hoursWorked[i] = 40.0;

}

31
Q

Arrays:-

What effect does the following code have?

Frog[] frogPond = new Frog[10];

for (int i=1; i < frogPond.length -1; 1++)

{

frogPond[i] =new Frog();

}

A

The first line of the code declares and creates an array variable frogPond that can hold references to ten Frog objects. The for loop then assigns a new Frog object (using the Frog constructor) to the component at each index between 1 and 8. (The elements at indexes 0 and 9 will both contain the value null after this code has been executed.)

32
Q

Arrays:-

On paper, write some code to find and display the total of all the int values in an array called intArray. Hint: you don’t know how many elements to loop, so don’t use a For statement.

A

int runningTotal = 0;

for (int eachInt : intArray)

{

runningTotal = runningTotal + eachInt;

}

System.out.println(runningTotal);

In this loop, eachInt is assigned each element in intArray in turn. The loop body maintains a running total in the variable runningTotal, which was initialised to 0 on declaration. After the loop body, runningTotal will contain the sum of all the values in intArray.

33
Q

Arrays:- A novice programmer tries to display every element of an array using the following for loop.

What is wrong with their code?

for (int i=1; i <= myArray.length; i++)

{

System.out.println(myArray[i]);

}

A

The code has two problems. The loop variable i is initialised to 1 instead of 0, and so the element at index 0 will not be displayed. The Boolean condition controlling the loop (i <= myArray.length) will allow the loop body to be executed when i is 2000. But myArray does not have an index 2000 so this will cause an ArrayIndexOutOfBounds exception.

34
Q

Arrays:- An array called bank contains Account object references. Write some code to process the array so that the balance of each Account object is increased by £50. You will need to use the credit() message.

A

The following code will do the job:

for (Account anAccount : bank)

{

anAccount.credit(50);

}

35
Q

Arrays:- Using paper and pencil write the code that finds the average balance of Account objects referenced by the components of an array, bank, and reports it in an alert dialogue box. You can assume that the array is full so there are no null elements in the array. The average required is the total balance divided by the number of accounts.

A

The following code can be used to find the average of all the balances in the bank array:

double total = 0;

double average = 0;

for (Account eachAccount : bank)

{

total = total + eachAccount.getBalance();

}

average = (total / bank.length);

OUDialog.alert(“The average balance is “ + average);

You may have achieved this without the variable average; however, it is important to initialise total to 0 before the for-each loop as it is used in the calculation within the loop. The for-each statement assigns each Account reference in the array to the variable eachAccount in turn, and the loop body uses eachAccount as a receiver for a getBalance() message.

The value returned by getBalance() is added to a running total. In the calculation for average the answer is a double because although bank.length is an int, total has been declared as a double. In the final line the concatenation operator, +, converts the value of average to a String and the result is displayed in a dialogue box, as required.

36
Q

Arrays:- To find first half of year weeklyTakings the following code is used

double total = 0;

for (int i=0; i < 26; i++)

{

total = total + weeklyTakings[i];

}

Note that the last value of i we require is 25, as this is the index at which the 26th element of the array is located.

Question:- Write a loop fragment to calculate the total takings for the second half of the year, given the array weeklyTakings.

A

double total = 0;

for (int i=26; i < 52; i++)

{

total = total + weeklyTakings[i];

}

37
Q

Arrays:- Searching arrays for a searchValue…

Complete the incomplete code.

Assuming that the array anArray contains primitive values, and the primitive value (of a compatible type) being searched for is held in searchValue:

int i = 0;

boolean found = _____;

while ((i < anArray.length) && (!found))

{

if (anArray[i] == searchValue)

{

found = true;

}

else

{

i++;

}

}

A

int i = 0;

boolean found = false;

while ((i < anArray.length) && (!found))

{

if (anArray[i] == searchValue)

{

found = true;

}

else

{

i++;

}

}

38
Q

Arrays:- Suppose that searchValue is found in an array using the following code:-

int i = 0;

boolean found = false;

while ((i < anArray.length) && (!found))

{

if (anArray[i] == searchValue)

{

found = true;

}

else

{

i++;

}

}

Does the programmer know where in the array the sought for value was found once the loop has exited?

A

Yes! The variable i will hold the last index processed (the one where the value was found). Note, though, that this code will find only the first occurrence of the value in the array, there may be others.

39
Q

Arrays:- intArray is an array that holds the integers {10, 5, 7, 2, 9, 8, 1, 12}

Display the textual representation of each element in intArray, one to a line, in the Display Pane.

A

A suitable display can be achieved by using:

for (int anInt : intArray)

{

System.out.println(anInt);

}

Here anInt is assigned, one at a time, the value of each element of intArray.

40
Q

Arrays:- intArray is an array that holds the integers {10, 5, 7, 2, 9, 8, 1, 12}

Display the total of all the elements of intArray in a dialogue box.

A

To display the total of the elements in a dialogue box:

int sum = 0;

for (int anInt : intArray)

{

sum = sum + anInt;

}

OUDialog.alert(“sum is “ + sum);

The variable sum must be initialised to 0 before the for-each statement. A running total is calculated within the loop body. Using the suggested test data, sum should hold the value 54.

41
Q

Arrays:- intArray is an array that holds the integers {10, 5, 7, 2, 9, 8, 1, 12}

Find all the elements in intArray that are greater than 8 and replace each of them by 0.

A

The task of finding and replacing can be achieved by using:

for (int i = 0; i > 8)

{

intArray[i] = 0;

}

Here a for loop is needed (rather than a for-each loop) because the processing requires the primitive values held in the array components to be changed. Each array element in turn is compared to 8. If it is greater than 8 the array element is overwritten by 0, i.e. the component at the current index is assigned 0.

42
Q

Arrays:- intArray is an array that holds the integers {10, 5, 7, 2, 9, 8, 1, 12}

Create a second array, intArrayCopy, that is an exact copy of intArray.

A

To create a copy of intArray use:

int[] intArrayCopy = new int[intArray.length];

for (int i = 0; i < intArray.length; i++)

{

intArrayCopy[i] =intArray[i];

}

The first line creates a new array, intArrayCopy,which is the same length as the existing intArray. Within the loop body each element of intArray is assigned to the corresponding component of intArrayCopy.

Note that here we have to use a for loop (rather than a for-each statement)because we need to change the existing elements of intArrayCopy (which have been initialised to the default value of 0 ).

You might have tried intArrayCopy = intArray but this does not create a new array, rather it provides a second reference, intArrayCopy, for the array referenced by intArray. You can verify this by evaluating intArrayCopy == intArray which will return true, showing that they reference the same object.

43
Q

Arrays:-

Find the first occurrence of a red frog in an array of Frog objects called frogPond.

Display a dialogue box that either gives the index at which the first red frog is found, or announces that no red frogs exist in the pond.

Code to create new frogs (position 1, GREEN)

Frog[] frogPond = { new Frog(), new Frog(), new Frog() };

A

We use a while loop to iterate through the array until either a red frog is found, or there are no more components.

int i = 0;

boolean found = false;

while (i < frogPond.length && !found)

{

if (frogPond[i].getColour().equals(OUColour.RED))

{

found =true;

}

else

{

i++;

}

}

if (found)

{

OUDialog.alert(“Red frog found at index “+ i);

}

else

{

OUDialog.alert(“No red frogs found here”);

}

44
Q

Strings:-

String aString = “Brian Aldridge”;

String bString = “Ed Grundy”;

String cString = “brian aldridge”;

String dString = “   a string with leading and trailing spaces   ”;

What will be the output when the following code is executed?

aString.charAt(4);

bString.charAt(0);

A

The first message returns the value ‘n’ and the second returns ‘E’. The message charAt(int) returns the character at the index indicated by the int argument.

45
Q

Strings:-

String aString = “Brian Aldridge”;

String bString = “Ed Grundy”;

String cString = “brian aldridge”;

String dString = “   a string with leading and trailing spaces   ”;

The following statements, when executed, all return an integer; do not worry about the size of the integer, just its sign (whether it is + or −).

(a). aString.compareTo(bString);

(b). bString.compareTo(aString);

(c). aString.compareTo(cString);

(d). aString.compareToIgnoreCase(cString);

A

The message compareTo(String) compares the receiver string to the argument string. If the receiver string comes before the argument string alphabetically the message answer is a negative int (notice that an upper-case letter comes before the same alphabetical lower-case letter) otherwise the message answer is a positive int. If the two strings are exactly equal, 0 is answered. The size of the answer (positive or negative) tells you how far apart in the character sequence the first unequal characters are.

(a) So, in the first expression the answer is −3 because ‘B’ in the receiver has a value that is 3 less than ‘E’ in the argument (the first dissimilar character in the argument). (b) And statement two; the vale is reversed to positive 3
(c) The third expression evaluates to −32 because the ‘B’ in the receiver has a value that is 32 less than ‘b’ in the argument.
(d) The fourth message expression uses the compareToIgnoreCase(String) message, and answers 0. As the name of the message suggests, it ignores the case of the characters and so the two strings aString and cString are deemed to be equal.

46
Q

Strings:-

String aString = “Brian Aldridge”;

String bString = “Ed Grundy”;

String cString = “brian aldridge”;

String dString = “   a string with leading and trailing spaces   ”;

The following statements, when executed, all return an integer; do not worry about the size of the integer, just its sign (whether it is + or −).

1) . aString.indexOf(‘i’);
2) . bString.indexOf(‘G’);
3) . cString.indexOf(‘B’);
4) . aString.indexOf(“Ald”);
5) . bString.indexOf(“ward”);
6) . aString.replace(‘i’, ‘*’);
7) . bString.replace(“run”, “walk”);
8) . dString.trim();
9) . aString.length();
10) . aString.substring(4);
11) . bString.substring(6);
12) . cString.substring(3, 5);

A

1) . 2
2) . 3.
3) . -1. The message indexOf(char) returns the index within the receiver string of the first occurrence of the character argument. If the character is not found, -1 is returned.
4) . 6
5) . -1. If the string argument of the indexOf() method occurs as a substring within the receiver string, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
6) . The message answer is “Br*an Aldr*dge”
7) . The message answer is “Em Grunmy”. The message replace(char, char) returns a new string in which all the occurrences of the first char argument in the receiver string have been replaced by the second char argument. The receiver itself is not changed. If the first character does not occur in the receiver, a string with the same state as the receiver is returned.
8) . The following string is returned: “a string with leading and trailing spaces”. The effect of the message trim() is to return a copy of the receiver string with any leading and trailing white space removed, or the receiver if it has no leading or trailing white space. In either case, the receiver is unchanged.
9) . The message answer is 14, the number of characters in the receiver string. Note that strings have a method length() whereas arrays have an instance variable length.
10) . The substring(4) expression returns “n Aldridge”,
11) . Substring(6) returns “ndy”
12) . Substring(3,5) returns “an”. The substring() method with a single int argument returns a new string that is the substring of the receiver string beginning with the character at the index indicated by the argument and extending to the end of the receiver. An IndexOutOfBoundsException is thrown if the argument is negative or greater than the length of the string. The substring() method with two int arguments returns a new string that is the substring of the receiver beginning at the index specified by the first int argument and extending to the character at an index one less than the second int argument (so the length of the substring is the difference between the two int arguments). An IndexOutOfBoundsException is thrown if the first argument is negative, or if it is bigger than the second argument, or if the second argument is larger than the length of the receiver string.

47
Q

Strings:-

String string1 = “Brian”;

String string2 = “brian”;

String string3 = “Brian”;

True or false:-

1) . string1.equals(string3);
2) . string2.equals(string1);
3) . string1 == string3;

A

1) . true because string1 and string3 contain the same characters in the same order. Note that an upper-case character and a lower-case character are considered to be different,
2) . so string2.equals(string1) would return false.
3) . You might be surprised, however, to learn that executing string1 == string3 also returns true. You will recall that the == operator (when used with objects) tests to see if the two operands (here string1 and string3) reference the same object, so this result tells us that although the code appeared to create two different String objects (that happened to have the same state), we, in fact, created a single String object, referenced by two different variables; we say that string1 and string3 have the same identity.

The compiler is able to deduce that it can reuse an existing string literal, a second reference to the original String object is created instead. This means that only one copy of a particular string literal needs to be kept in the system at any one time. Each time a string literal is created the Java compiler looks to see if it already exists. The reason for this is one of efficiency. There is no point in having more than one string literal in the system with exactly the same character sequence, it is more efficient to share a single String object.

This feature of the language is called string interning.

The situation is different if a string is constructed while a program is being executed (that is, at run-time). In this case the new string becomes a distinct object, even if there is a string with the same character sequence already in the system.

48
Q

Strings:-

String name1 = “Jo”;

String name2 = “Lo”;

String name3 = “JoLo”;

String name4 = name1 + name2;

String name5 = “Jo” + “Lo”;

String name6 = new String(“JoLo”);

Which two names (at run-time) reference the same String object, as these strings have an identical sequence of characters and have both been created using literals?

A

answer:- name3 and name5

name4 has the same state as the string referenced by name3; however, name4 would reference a distinct object to name3 because the name4 string is created when the program is executing. (We can tell this because the right-hand side of the assignment contains variables and not literal values.) Similarly, name6 and name3 reference distinct objects because name6 is not assigned a literal string, but a string created using a String constructor taking a String argument at run-time. you should be aware that strings created using a String constructor (or otherwise created at run-time) are distinct objects, so that comparing their identity (using ==) will evaluate to false. This is why we have stressed that you should use the equals() message to compare string state –the equals() message will compare string contents regardless of how the strings were created.

49
Q

Strings:- Suppose you create two String objects, aString and bString, as follows:

String aString = new String(“hello”);

String bString = new String(“hello”);

What values will each of the following expressions have when they are executed?

1). aString.equals(bString)

2). aString == bString

A

The expression aString.equals(bString) will return true because aString and bString reference String objects with the same state.

The expression aString == bString will return false because aString and bString do not refer to the same instance of String; they have been created as distinct objects as opposed to using the same string literal.

50
Q

Strings:- Suppose you create two String objects, aString and bString, as follows:

String aString = new String(“hello”);

String bString = new String(“hello”);

aString = bString;

What values will each of the following expressions have when they are executed?

1). aString.equals(bString)

2). aString == bString

A

The expression aString.equals(bString) will return true because aString and bString refer to objects of the same class with the same state (actually it is the same object!).

The expression aString == bString will return true because the assignment statement copied the reference held by bString into aString. The two variables now reference the same instance of String.

51
Q

String name1 = “Lee”;

String name2 = “Ann”;

String name3 = “LeeAnn”;

String name4 = name1 + name2;

String name5 = “Lee” + “Ann”;

Once they have all been executed, what is the result of evaluating each of the following?

1). name3.equals(name4);

2). name3 == name5;

3). name3 == name4;

A

1) . true name3 and name4 both have the same state, “LeeAnn”.
2) . true name3 and name5 reference the same object, the single copy of the string “LeeAnn”. You may find this surprising. However, recall that because name5 is computed from two literals, its value can be determined at compile time. Thus, the compiler can arrange for name5 to refer to the unique existing copy of the string “LeeAnn”.
3) . false By contrast, the value of name4 could not be determined at compile time and was created at run-time. Thus it references a distinct object (even though a string with the same state already exists in the system).

52
Q

StringBuilder:-

Is a StringBuilder object mutable or immutable?

A

In some situations the StringBuilder class provides a better alternative to the class String because a StringBuilder object can be changed – it is mutable.

53
Q

String:-

Is a String mutable or immutable?

A

Immutable

When a String looks like it has been altered, in fact a new String has been created and the original unreferenced String is picked up in a garbage collection.

54
Q

StringBuilder:-

How many characters has the StringBuilder object sb? StringBuilder sb = new StringBuilder(“Hello”);

A

The code declares a StringBuilder variable referenced by sb, and assigns to it a new instance of StringBuilder with the character sequence ‘H’ ‘e’ ‘l’ ‘l’ ‘o’, but with space for an additional 16 characters (giving the potential for the object referenced by sb to contain 21 characters in total).

55
Q

StringBuilder:-

What is the capacity of the StringBuilder object myStringBuilder?

StringBuilder myStringBuilder = new StringBuilder(200);

A

200 the capacity of the buffer, which is the number of characters a StringBuilder object can potentially hold. For example, this code creates a new StringBuilder object that has a capacity of 200 characters and assigns it to the variable myStringBuilder: Note that the capacity of a StringBuilder object is different from its length. As with a String object, the length of a StringBuilder object is the number of characters in the sequence. The capacity is the potential number of characters an existing StringBuilder object can hold. StringBuilder objects understand the message capacity(), which returns the capacity of the StringBuilder object.

56
Q

StringBuilder:-

What happens when a StringBuilder buffer becomes full.

A

The answer is that if the buffer has reached its capacity and an attempt is made to insert or append more characters, a new and larger underlying character sequence is created, and the existing character sequence is automatically copied into it. The original sequence is then garbage collected. It is of course better to simply create a StringBuilder object that is a suitable size for your purposes in the first place.

57
Q

StringBuilder:-

Do the messages with the signature indexOf(String), substring(int) and substring(int, int) have the same effect when sent to a StringBuilder object as to a String object?

A

Yes if the message with the signature indexOf(String) is sent to an instance of StringBuilder and the argument occurs as a substring within that instance of StringBuilder, then the index of the first character of the first such substring found is returned, just as occurs when such a message is sent to a String object. The messages with the signatures substring(int) and substring(int, int) also have the same effect when sent to a StringBuilder object as to a String object.

58
Q

StringBuilder:-

StringBuilder aSB = new StringBuilder(“Bob”);

A) If you execute each of the following statements, one by one, note the value that is returned by the message-send in each case.

B) Try to determine what effect the message has had each time. If you are not sure try out some different examples.

1) . aSB.length();
2) . aSB.capacity();
3) . aSB.append(“ is “);
4) . aSB.append(50);
5) . aSB.length();
6) . aSB.capacity();
7) . aSB.deleteCharAt(0);
8) . aSB.insert(0, ‘R’);
9) . aSB.reverse();
10) . aSB.toString();

A

The default constructor creates a StringBuilder object that has the sequence of 3 characters that appear in the String argument followed by a buffer that can hold an additional 16 characters.

1). 3

The message length() returns the number of characters in the receiver StringBuilder object.

2). 19

the message capacity() returns the total number of characters the StringBuilder object can potentially hold

3). ‘B’ ‘o’ ‘b’ ‘ ‘ ‘i’ ‘s’ ‘ ‘

the message with the signature append(String) results in the character sequence in the String argument being appended to the end of the character sequence in the receiver StringBuilder object. The receiver is returned in its new state,

4). ‘B’ ‘o’ ‘b’ ‘ ‘ ‘i’ ‘s’ ‘ ‘ ‘5’ ‘0’

The second message, with the signature append(int), results in the characters ‘5’ and ‘0’ , corresponding to its int argument, being appended to the receiver StringBuilder object.

5) . The message length() returns 9 (there are 9 characters, including the two blank characters).
6) . The message capacity() remains 19 (the receiver StringBuilder object can potentially hold 19 characters when created).
7) . ‘o’ ‘b’ ‘ ‘ ‘i’ ‘s’ ‘ ‘ ‘5’ ‘0’ The message answer is a reference to the receiver in its new state.
8) . ‘R’ ‘o’ ‘b’ ‘ ‘ ‘i’ ‘s’ ‘ ‘ ‘5’ ‘0’ The message with the signature deleteCharAt(int) removes from the receiver the character at the position indicated by the message’s argument. The message answer is a reference to the receiver in its new state. It has been modified by inserting the character ‘R’ at index 0.
9) . ‘0’ ‘5’ ‘ ‘ ‘s’ ‘i’ ‘ ‘ ‘b’ ‘o’ ‘R’ The message with the signature insert(int, char) results in the character given by the second argument being inserted in the receiver at the index given by the first argument. The message answer is a reference to the receiver in its new state, which has been modified by reversing the character sequence.
10) . The message answer is a new String object “05 si boR” with a character sequence identical to that of the receiver StringBuilder object.

59
Q

___________ is a fixed size, homogeneous indexed collection that can hold either primitive values or references to objects.

A

An array

60
Q

When an array variable is declared, eg, String [] roster; the type of primitive or object reference to be stored in the array must be stated. This is called the a) Component Type or b) Element Type of the array?

A

a) Component

which can be, for example,

String, int, double, Boolean, char etc

61
Q

When an array object is created, the number of items that the array is going to store must be stated. This is called the a) length or b) index of the array.

A

a) length

int [] intArray = {7, 9, 3};

intArray.length( );

………Index is 0,1,2 however the length returns 3

62
Q

In Java, what is the first index number of an Array?

A

Zero

arrays are zero-based, which means that the first index is 0, so the length of an array is always one more than the last index.