Java OCA OCP Practice Question 3230

Question

Consider the following program:

public class Main {
        public static void main(String []args) {
                Object nullObj = null;
                StringBuffer strBuffer = new StringBuffer(10);

                strBuffer.append("hello ");
                strBuffer.append("world ");
                strBuffer.append(nullObj);
                strBuffer.insert(11, '!');
                System.out.println(strBuffer);
        }//from  w w  w  .ja  v  a 2s  .  c o  m
}

Which one of the following options correctly describes the behavior of this program?

a)      This program prints the following: hello world!
b)      This program prints the following: hello world! null
c)      This program throws a NullPointerException.
d)      This program throws an InvalidArgumentException.
e)      This program throws an ArrayIndexOutOfBoundsException.


b)

Note

The call new StringBuffer(10); creates a StringBuffer object with initial capacity to store 10 characters; this capacity would grow as you keep calling methods like append().

After the calls to append "hello" and "world ," the call to append null results in adding the string "null" to the string buffer (it doesn't result in a NullPointerException or InvalidArgumentException).

With the append of "null," the capacity of the string buffer has grown to 17 characters.

So, the call *strBuffer.insert(11, '!');* successfully inserts the character '!' in the 11th position instead of resulting in an ArrayIndexOutOfBoundsException.




PreviousNext

Related