Discussion :: Java.lang Class
-
What will be the output of the program?
class Q207 { public static void main(String[] args) { int i1 = 5; int i2 = 6; String s1 = "7"; System.out.println(i1 + i2 + s1); /* Line 8 */ } }
Answer : Option B
Explanation :
This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are:
If either operand is a String, the + operator concatenates the operands.
If both operands are numeric, the + operator adds the operands.
The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as:
System.out.println( new StringBuffer() .append(new Integer(i1 + i2).toString()) .append(s1) .toString() );
Be The First To Comment