Java Programming - Java.lang Class - Discussion

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 */
    } 
}

[A]. 18
[B]. 117
[C]. 567
[D]. Compiler error

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() ); 


Avinash said: (Jan 16, 2012)  
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

Charudatta said: (Aug 25, 2015)  
Hi @Avinash.

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

Sanjay Chitroda said: (Aug 25, 2017)  
For i1=5 and i2=6.
i1 + i2 = 11 // normal addition.

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

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.