-3

I'm having trouble in figuring out why the output for theses two lines is different ..

public static void main(String[] args) {
   System.out.println("6.0+1="+6.0+1);
   System.out.println("6.0+1="+(6.0+1));
}

The output
6.0+1=6.01
6.0+1=7.0

  • 1
    + is left associative, so "6.0+1="+6.0 is the string "6.0+1=6.0" and the +1 concatenates "1". – CodesInChaos Oct 8 '16 at 14:21
1

Your example don't use unary plus.

You use it for string concatenation, and for addition.

"6.0+1="+6.0+1 will be evaluated in types as string + number + number. So first "6.0+1" + 6.0 will use + as the string concatenation operator, resulting in a new string: "6.0+1=6.0". Then the same happens with the + 1 at the end, resulting in another string concatenation.

"6.0+1="+(6.0+1) wil first evaluate the (...) part, in which you add two numbers, so the result will be 7.0 (floating point + integer => floating type). Then the string concatenation as in the first variation takes place.

Unary operators would work on a single variable/constant/expression, i.e. the unary minus operator as in x = -1.

| improve this answer | |
-1

The answers would definitely be different because of the use of Bracket on the second operation,the operation would first start from bracket to other operators.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.