Question 48) Given the following variables char c = 'c'; int i = 10; double d = 10; long l = 1; String s = "Hello"; Which of the following will compile without error? 1)c=c+i; 2)s+=i; 3)i+=s; 4)c+=s; I wondering why 3) is not the correct answer? I know i = i+s will giving a correct answer but why not i += s? Thank You.
i += s will fail because you are trying to add a integer and a string. That doesnt make any sense to me , nor will it to the java compiler, so it cribs. on the same token, i = i + s; is no good. that will fail too
When one of the operands of a "+" operation is a String, the other non-String operand(s) get converted to a String and the result of the expression is a String. Therefore, (s + i) will result in the String "Hello10". So far, so good. However, when you try to assign this String value to an int, the Java compiler will complain about an incompatible type. (s += i) will work
I just tried out this, int i=0; String s="hello"; i+=s; System.out.println(i); result given 59336428. But the answer for this question is only 2). char c = 'c'; int i = 10; double d = 10; long l = 1; String s = "Hello"; Which of the following will compile without error? 1)c=c+i; 2)s+=i; 3)i+=s; 4)c+=s; And i make a mistake that i + s will compile fine but not i = i+s;
What mistake did you make? I didn't understand your last sentence. Also, the code you list does NOT compile, at least not under jdk1.3.0_02. I get the following error, as I expected: :roll:
"TestAssignment.java": Error #: 354 : incompatible types; found: java.lang.String, required: int at line 10, column 5 "TestAssignment.java": Error #: 374 : primitive type or String required for left hand side of += operator at line 10, column 3 [ January 09, 2002: Message edited by: Rob Ross ]
SteffySY Sing, I did try compiling the (i += s) code using the Scrapbook in VisualAge for Java Version 3.5.3 and was surprised to find that it was successful. I ran it and got something similar to what you got: a number (mine was a different one though). What IDE or version of Java are you using? For the purpose of the certification exam, the code should not compile. I tried compiling under Java 1.3.1_01 and got an "inconvertible type" compile error.