|
RHS |
Test 03 - Solution
Name : ______________________________________________________
When answering the following questions be sure to read all introductions - they may include important declarations or information needed to solve the questions.
You should be able to answer all 27 questions (in 3 groups) in less then 30 mins.
Group 1
Check whether the following loops are valid.
If they are valid you should
also write down the output produced by the loop when it is executed.
Assume that the following declaration has been made: int j = 0;
Loop |
Valid |
Not valid |
Output |
|
| for (int i = 0, i < 5, i++)
|
X (commas used instead of semicolons) |
|||
| for (i = 0; i < 5; i++)
|
X (type of i not declared) |
|||
| for (int i = 0; i <= 5; i++)
|
X |
0 1 2 3 4 5 |
||
| for (int i = 0; i < 5; i++);
|
X (as the body of the loop is empty (semicolon after loop-head) and i is not declared outside loop the print() will crash) |
|||
| for (int i = 0; i < 5; i = i + 2)
|
X |
0 2 4 |
||
| while (j <= 5)
|
X |
0 0 0 0 (infinite as j never changes) |
||
| while (j < 5){
|
X |
0 1 2 3 4 |
||
| while (j < 5)
|
X |
0 1 2 3 4 |
Group 2
Assume that the following two classes are fully implemented:
![]() |
Also assume the following declaration have been made: Person
pers = new Person("Peter", "HighStreet 12", "Roskilde");
Which of the following statements are valid?
Statement |
Valid |
Not valid |
||
| pers.toString();
|
X |
|||
| Person.toString();
|
X (toString() not static) |
|||
| pers.getName();
|
X |
|||
| String s = pers.getAddress();
|
X (getAddress() does not return String) |
|||
| String s = Person.getAddress();
|
X (getAddress() not static) |
|||
| Address a = pers.getAddress();
|
X |
|||
| Address a = Person.getAddress();
|
X (getAddress() not static) |
|||
| String city = Person.getAddress.getCity();
|
X (getAddress is a method(and is not static)) |
|||
| String city = (Address) pers.getCity();
|
X (getCity() not in Person) |
|||
| String city = pers.getAddress().getCity();
|
X |
|||
| String city = pers.getAddress.getCity();
|
X (getAddress() is a method) |
Group 3
Which of the following implementations of the toString() method
for the class Person would
be valid?
toString() |
Valid |
Not valid |
||
| public String toString(){
|
X (no return statement) |
|||
| public String toString(){
|
X (street and city not available in Person) |
|||
| public String toString(){
|
X |
|||
| public String toString(){
|
X |
|||
| public String toString(){
|
X (. before semicolon not correct) |
|||
| public String toString(){
|
X (street and city not public) |
|||
| public String toString(){
|
X |
|||
| public String toString(){
|
X |