Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 11)
11.
What will be the output of the program?
class SC2 
{
    public static void main(String [] args) 
    {
        SC2 s = new SC2();
        s.start();
    }

    void start() 
    {
        int a = 3;
        int b = 4;
        System.out.print(" " + 7 + 2 + " ");
        System.out.print(a + b);
        System.out.print(" " + a + b + " ");
        System.out.print(foo() + a + b + " ");
        System.out.println(a + b + foo());
    }

    String foo() 
    {
        return "foo";
    }
}
9 7 7 foo 7 7foo
72 34 34 foo34 34foo
9 7 7 foo34 34foo
72 7 34 foo34 7foo
Answer: Option
Explanation:

Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands.

Discussion:
12 comments Page 2 of 2.

Kush said:   8 years ago
In java, we have only operator precedence but not operand precedence.before applying any operator all operand will be evaluated from left to right.

Here, System.out.print(foo() + a + b + " "); foo34.

because of foo() will be evaluated first which returns string "foo" so if string first comes then the remaing value will be converted to the string like foo34 and
here, System.out.println(a + b + foo());7foo.

Here primitive value added first, because operator precedence and last string will be converted like 7foo

The string always convertes while primitives always added.

Ganesh said:   7 years ago
Thanks all for explaining.


Post your comments here:

Your comments will be displayed after verification.