Monday 18 February 2013

7. In the following pieces of code, A and D will compile without any error. True/False?

7. In the following pieces of code, A and D will compile without any error. True/False?

A: StringBuffer sb1 = "abcd";
B: Boolean b = new Boolean("abcd");
C: byte b = 255;
D: int x = 0x1234;
E: float fl = 1.2;


Choices:
a. True
b. False


B. The code segments B and D will compile without any error.
A is not a valid way to construct a StringBuffer, you need to creat a StringBuffer object using "new".
B is a valid construction of a Boolean (any string other than "true" or "false" to the Boolean constructor will result in a Boolean with a value of "false").
C will fail to compile because the valid range for a byte is -128 to +127 (ie, 8 bits,signed).
D is correct, 0x1234 is the hexadecimal representation in java.
E fails to compile because the compiler interprets 1.2 as a double being assigned to a float (down-casting), which is not valid. You either need an explicit cast (as in "(float)1.2") or "1.2f", to indicate a float.

No comments:

Post a Comment