Computer Program Reading Comprehension Project
U of T Computer Program Reading Comprehension Project
String Fumble Example
The following program excerpt is an exercise about String operations. The program tries to compare, compare (ignoring case difference) and copy Strings. Please refer to the comments for the motivation. However, there are some mistakes, which may make the program inconsistent with the intention of the programmer. Please try your best to find these mistakes before reading the questions.

Download files: StringFumbles.java
Areas: if statements.


StringFumbles.java
1/** This Java code contains some common errors.
2 *  Can you find the errors and correct them?
3 */
4
5     String firstStr = "I am Canadian";
6     String secondStr = "Canadian";
7
8     String thirdStr = "I am " + secondStr;
9     System.out.println("thirdStr is " + thirdStr);
10
Displaying 10 of 56 lines
View full source


Question 1
Is there a problem if we change the first line of code to the following String initialization?
String firstStr = 'I am Canadian';
If so, what is it?
Hints Solution

Question 2
After thirdStr is assigned a value, what is the String in thirdStr?
Hints Solution

Question 3
Do firstStr and thirdStr have the same character String after the assignment statement for thirdStr?
Solution

Question 4
Does the following comparison tell us whether the character strings are the same?
if (firstStr == thirdStr)
Hints Solution

Question 5
What is the output of the first if statement?
Solution

Question 6
How should we correct the following comparison?
if (firstStr == thirdStr)
Hints Solution

Question 7
What does the following code do?
String fourthStr = new String(firstStr);
Hints Solution

Question 8
What is the output of the second if statement?
Hints Solution

Question 9
What does the following code do?
String fifthStr = firstStr;
Solution

Question 10
What is the output of the third if statement?
Solution

Question 11
Does the following String comparison have the intended effect?
if (0==firstStr.compareTo(thirdStr))
Hints Solution

Question 12
Aside from the problem discussed in the above question, there is another problem in the last if statement. Can you find it?
Hints Solution