Review Questions

graphics/rq_icon.gif

10.28

What will be the result of attempting to compile and run the following program?

public class MyClass {
    public static void main(String[] args) {
        String s = "hello";
        StringBuffer sb = new StringBuffer(s);
        sb.reverse();
        if (s == sb) System.out.println("a");
        if (s.equals(sb)) System.out.println("b");
        if (sb.equals(s)) System.out.println("c");
    }
}

Select the one correct answer.

  1. The code will fail to compile since the constructor of the String class is not called properly.

  2. The code will fail to compile since the expression (s == sb) is illegal.

  3. The code will fail to compile since the expression (s.equals(sb)) is illegal.

  4. The program will print c when run.

  5. The program will throw a ClassCastException when run.

10.29

What will be the result of attempting to compile and run the following program?

public class MyClass {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("have a nice day");
        sb.setLength(6);
        System.out.println(sb);
    }
}

Select the one correct answer.

  1. The code will fail to compile since there is no method named setLength in the StringBuffer class.

  2. The code will fail to compile since the StringBuffer reference sb is not a legal argument to the println() method.

  3. The program will throw a StringIndexOutOfBoundsException when run.

  4. The program will print have a nice day when run.

  5. The program will print have a when run.

  6. The program will print ce day when run.

10.30

Which of these parameter lists have a corresponding constructor in the StringBuffer class?

Select the three correct answers.

  1. ()

  2. (int capacity)

  3. (char[] data)

  4. (String str)

10.31

Which method is not defined in the StringBuffer class?

Select the one correct answer.

  1. trim()

  2. length()

  3. append(String)

  4. reverse()

  5. setLength(int)

10.32

What will be the result of attempting to compile and run the following code?

public class StringMethods {
    public static void main(String[] args) {
        String str = new String("eenny");
        str.concat(" meeny");
        StringBuffer strBuf = new StringBuffer(" miny");
        strBuf.append(" mo");
        System.out.println(str + strBuf);
    }
}

Select the one correct answer.

  1. The code will fail to compile.

  2. The program will print eenny meeny miny mo when run.

  3. The program will print meeny miny mo when run.

  4. The program will print eenny miny mo when run.

  5. The program will print eenny meeny miny when run.