1

I hit some strange String concatenation syntax when writing some code and was surprised to find that it compiles.

quota.setText("Cloud storage: " + used + " (" + + + + quotaUsed / quotaAvailable * 100 + " of " + total);

The strange part is around the four continuous + operators (I was going to place more strings between them, and I was surprised there were no red squiggly lines underneath them. quotaUsed and quotaAvailable are longs and used and total are Strings.

Can anyone explain how the system will interpret that statement?

Jeshurun
  • 22,940
  • 6
  • 79
  • 92
  • I think it might be applying the `++` operator once and the unary `+` operator once (making the value positive) and applying concatenation. I am not sure and would need to see output to know. – blueblob Nov 10 '13 at 00:40
  • 1
    @blueblob - Incorrect guess. The `++` operator cannot have a space in the middle of it. – Stephen C Nov 10 '13 at 00:45
  • @blueblob unary `+` does not "make a value positive". If `x` is negative, `+x` is still negative. `Math.abs(x)` would make it positive. – ajb Nov 10 '13 at 00:54

1 Answers1

4

The first + is going to be the concatenation operator, and the next three will simply be the unary + operator, basically no-ops in this situation. Note that you will be performing integer division on your fraction, so if you write it as

(100 * quotaUsed) / quotaAvailable

you'll get better precision.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Thanks, I have heard of but never used the unary plus operator before. This SO answer has a good example: http://stackoverflow.com/a/2624541/473637 – Jeshurun Nov 10 '13 at 01:08