Search This Blog

Wednesday, February 9, 2011

SCJP 6 Question 26:

What will happen when you attempt to compile and run the following code?

public class WrapTest {
  public static void main(String[] args) {
    String str = "19";
    str.concat(".5");
    Double d = new Double(str);
    Long l = new Long(str);
    System.out.println(d.intValue()+d.doubleValue()+l.doubleValue());
  }
}

Choose one answer.
a. It will print  57.5
b. It will print  57.0
c. It will print  58.0
d. Compilation error
e. Runtime exception




Answer : B

This question is slightly tricky if do not know the point that string objects are immutable. Since string objects are immutable str.concat() operation does not change the value of existing string, instead it returns a new string with appended characters. So str value remains 19 throughout the program. Based on the above explanation, A, C, and D options are incorrect.

String API for reference.

String concat(String str)
          Concatenates the specified string to the end of this string.

SCJP 6 Question 26:SocialTwist Tell-a-Friend

1 comment:

  1. Hello,
    I am very thankful to you to solve this equation, I am doing some work for my Vancouver public relations, and I got stuck in this equation but after reading your post, I have solved my equation. Thank you
    Best regards

    ReplyDelete