What is the result?

Given the code fragment:

System.out.println(“Result: ” + 2 + 3 + 5);
System.out.println(“Result: ” + 2 + 1 * 5);

What is the result?

Given the code fragment:

System.out.println(“Result: ” + 2 + 3 + 5);
System.out.println(“Result: ” + 2 + 1 * 5);

What is the result?

A.
Result: 10
Result: 30

B.
Result: 10
Result: 25

C.
Result: 235
Result: 25

D.
Result: 215
Result: 215

E.
Compilation fails

Explanation:
String concatenation is produced.
The output is:
Result: 235
Result: 25
Note #1:
To produce an arithmetic result, the following code would have to be used:
System.out.println(“Result: ” + (2 + 3 + 5));
System.out.println(“Result: ” + (2 + 3 * 5));
run:
Result: 10
Result: 17
Note #2:
If the code was as follows:
System.out.println(“Result: ” + 2 + 3 + 5″);
System.out.println(“Result: ” + 2 + 1 * 5″);
The compilation would fail. There is an unclosed string literal, 5″, on each line.



Leave a Reply 2

Your email address will not be published. Required fields are marked *


Abed Abu Alhalawa

Abed Abu Alhalawa

C

James

James

The Answer is C.

If the argument of the System.out.println() method starts with a String any additional + operands will convert Numbers to Strings and concatenate the String values. Only the other hand, if the numeric operations come first with + operators, the mathematical operations will be performed first and the result will be concatenated with the last string. For instance:

System.out.println(2 + 3 + 5 + “Result”);

will print 10Result.

Also:

System.out.println(2 + 3 + 5 + “Result” + 3 + 5);

will print 10Result35.