Quiz

Quiz #

To answer the quiz (and check your answers), click here

Objects and references #

public class City {

  String name;
  Country country;

  public City(String name,
              Country country) {
    this.name = name;
    this.country = country;
  }
}
public class Country {

  String name;
  City capital;

  public Country(String name,
                 City capital) {
    this.name = name;
    this.capital = capital;
  }
}
Country italy = new Country("Italy", null);
City florence = new City("Florence", italy);
City rome = new City("Rome", italy);
italy.capital = rome;

System.out.print(italy.capital.name + ", ");
System.out.print(florence.country.capital.name + ", ");
System.out.print(rome.country.capital.name + ", ");
System.out.print(rome.country.capital.country.capital.name);

This Java program:

  • does not terminate
  • outputs null, null, null, null
  • outputs null, null, Rome, null
  • outputs null, null, Rome, Rome
  • outputs Rome, null, null, null
  • outputs Rome, null, Rome, null
  • outputs Rome, null, Rome, Rome
  • outputs Rome, Rome, Rome, Rome
  • I do not know the answer

toString #

public class City {

  String name;
  Country country;

  public City(String name,
              Country country) {
    this.name = name;
    this.country = country;
  }

  @Override
  public String toString() {
    return "City{"+
      "name=" + name + ", "+
      "country=" + country + "}";
  }
}
public class Country {

  String name;
  City capital;

  public Country(String name,
                 City capital) {
   this.name = name;
   this.capital = capital;
  }

  @Override
  public String toString() {
    return "Country{"+
      "name=" + name + ", "+
      "capital=" + capital + "}";
  }
}

In this program, the method City.toString():

  • can output the empty string
  • always outputs the empty string
  • never outputs the empty string
  • is recursive
  • is not recursive
  • may not terminate
  • always terminates
  • never terminates

Static attribute #

public class MyClass {

    static int value;
    boolean flag;

    public MyClass(int value, boolean flag){
        this.value = value;
        this.flag = flag;
    }

    void print(){ System.out.print("["+value+" "+flag+"]"); }

    void incrementValue(){ value++; }

    void setFlag(boolean flag){ this.flag = flag; }
}
MyClass o1 = new MyClass(2, true);
MyClass o2 = new MyClass(3, false);
o1.print();
myMethod(o1);
o1.print();

void myMethod(MyClass object) {
    object.setFlag(false);
    object.incrementValue();
    object.print();
}

This (strange) Java program outputs:

  • [2 true][3 false ][3 false]
  • [3 true][4 false ][4 false]
  • [2 true][3 false ][2 true]
  • [3 true][4 false ][3 true]
  • [2 false][3 false ][3 false]
  • [3 false][4 false ][4 false]
  • [2 false][3 false ][2 true]
  • [3 false][4 false ][3 true]
  • I do not know the answer.