Java.lang Class

Q1: 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

ANS:A - 18

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



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.