sushil pandey
sushil pandey

Reputation: 21

Why is String concatenation not allowed here in the second case?

The second case gives compilation error,shows 5 is string while 4 is int.This should be the case with the first case also but it gives output.Why????

class Test
    {
    public static void main(String args[])
    {
    System.out.println("The sum is: "+5*4);   //Gives output The sum is: 20

    System.out.println("The sum is: "+5-4);  

    //Gives compilation error shows 5 is string while 4 is int.This should be the case with prevous case also but it gives output.Why????
    }
    }

Upvotes: 1

Views: 46

Answers (2)

adjan
adjan

Reputation: 13652

"The sum is: "+5*4

contains a * which has a higher precendence than +. Thus, 5*4 is evaluated first. Then the concatenation implicitly converts the int result to a String.


"The sum is: "+5-4

In this case, both + and - have the same precendence. Thus, the whole expression is evaluated from left to right. The concatenation also implicitly converts the 5 into a String. The next operation fails because you cannot subtract an int from a String. In order to enforce the right evaluation, use parentheses.

Note that if we did the subtraction first this would work:

5-4+" is the sum"

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

The Java rules for operator precedence state that * binds more tightly than +, but - does not.

That means that the first expression is the same as "The sum is: " + (5 * 4), which evaluates to "The sum is: 20". However, the second expression is the same as ("The sum is: " + 5) - 4 which makes no sense - you can't subtract a number from a String.

Upvotes: 2

Related Questions