Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 13)
13.
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 */
    } 
}
18
117
567
Compiler error
Answer: Option
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() ); 

Discussion:
4 comments Page 1 of 1.

Amaan said:   3 years ago
Thank you @Sanjay Chitorda.

Now, I got the perfect answer & explanation from you.

Sanjay chitroda said:   8 years ago
For i1=5 and i2=6.
i1 + i2 = 11 // normal addition.

Then s1='7' is a string so that concat behind '11'+'7'=117.
(1)

Charudatta said:   1 decade ago
Hi @Avinash.

I compile this code answer is 117. The execution of code is from LHS to RHS.

Avinash said:   1 decade ago
But the execution will run from RHS to LHS, then answer will be 567 because in that case either of the operands will be string leading to concatenation of strings

Post your comments here:

Your comments will be displayed after verification.