Given the code fragment:
Which two statements at Line n1 independently enable you to print 1250? (Choose two.)
Given the code fragment:
Which two statements at Line n1 independently enable you to print 1250? (Choose two.)
To print 1250, the two statements that can be used independently at Line n1 are "Integer res = 250 + s2;" and "Integer res = 250; res += s2;". The first statement works because it directly adds the integer value of s2, which is 1000, to 250. The second statement initializes res with 250 and then uses the "+=" operator to add s2's value to it. Statements involving parsing the string 's' like parseInt() and valueOf() will fail because the string contains an underscore, resulting in a syntax error. Using the string directly in arithmetic operations or incorrect casting methods is also syntactically invalid.
Should be C and D, but D should have "+=" instead of "=+". I've tried all the alternatives in an online compiler and these are the only ones that work. A and B would work if "s" were "1000", but parseInt() and valueOf() arent able to handle the underscore in "10_00". E is just plain wrong cuz s is a string and cant be automatically cast to an int. F is wrong cuz "Integer()" casting doesn't exist. One would instead use valueOf() to cast.
package q25; public class Q25 { public static void main(String[] args) { String s = "10_00"; Integer s2 = 10_00; // Line n1 // A. // Integer res = 250 + Integer.parseInt(s); // parseInt exception. // B. // Integer res = 250 + Integer.valueOf(s); // parseInt exception. // C. // Integer res = 250 + s2; // at the end, result = 1250 . // D. Integer res = 250; res += s2; // At then end, result = 1250 . // E. // Integer res = 250 + s; // Syntax error. // F. // Integer res = 250 + Integer(s2); // Syntax error. System.out.println(res); } }
CD but there's an error with the display of Answer option D D. Integer res = 250; res =+ s2; This will only return 1000 in result because there's no operator like =+ The correct choice of answer would be as below (for D), D. Integer res = 250; res += s2;