Search This Blog

Sunday, January 30, 2011

Question 19

What is the result of compiling and running the given code?

public class NullPointerString {
  public static void main(String[] args){
    StringBuffer sb = new StringBuffer("Java");
    String nullString = null;
    sb.append(nullString);
    System.out.println(sb);
  }
}

Options :


A. Compiler error at line “String nullString = null”.
B. NullPointerException thrown at runtime.
C. Prints "Javanull".
d. None of the above.



Answer : C

This is slightly tricky question. One can assign a null value to the string, so Option A is incorrect. According to the method definition[Method definition is copied below] of append method it can take a null string and append it successfully to the string buffer. So option B is also incorrect.

Method Definition [taken from Java 1.6 API]

public StringBuffer append(String str)



Appends the specified string to this character sequence.

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.

Let n be the length of this character sequence just prior to execution of the append method. Then the character at index k in the new character sequence is equal to the character at index k in the old character sequence, if k is less than n; otherwise, it is equal to the character at index k-n in the argument str.

Question 19SocialTwist Tell-a-Friend

No comments:

Post a Comment