hey guys,

i am working on coordinates in one program and there is a line such as this one:

int xx =Math.round((int) getWidth() * 100 / 768);

can somebody tell me what calculation is actually taken before the value is set to int xx
thanks a lot for any suggestions

first the getWidth() function will be called, upon return of a value it will be multiple by 100 and then divided by 768. After which it will be converted to an integer, finally it would be rounded via Math.round and assigned to xx.

This is actually a little complicated than that. Here goes - if I miss something, I'm sure someone will correct me.

int xx =Math.round((int) getWidth() * 100 / 768)

First getWidth is evaluated, and a cast to int is performed - casting is a higher precedence operation than the arithmetic operators.

For example:

System.out.println( (int) 7.8 * 100);

gives 700, NOT 780.

So we know we're doing integer division. The multiplicative operators are equal in precedence, so the arithmetic is done left to right. This is important because we're doing integer division. If the value, after casting, returned by getWidth is less than 8, the result of the arithmetic will be 0. ( 7 * 100 / 768 = 0, remainder of 68). If there were parentheses around the division operation, the value would always be zero. (10^100 * (100/768) = 10^100 * 0 = 0)

So we get an integer value which is then gratuitously rounded. That's if everything goes as the author of the code apparently hoped for.

Now, there's another layer of complication: we don't know what type getWidth is returning. If it's a widening cast, that's no bother, but that's not likely (who here has used a short lately?). If it's a cast from a float, that's pretty okay. You lose the decimal part, I guess you expected that.

But if you're converting from a long or a double, you have the chance of some weirdness. If the value is too large to be represented as an int, you get a truncated number which will not be what you expect. For example

long l = 2247483647L;
      System.out.println ("long l = " +l+ "  but casts to int as: " +

l = 2247483647 but casts to int as: -2047483649

A similar effect will happen with a double: it'll be converted to a long, and then if it's too big to fit in an int, it'll just come out all kinds of wrong.

(see JLS 5.1 for the gory details on conversion - they're actually sort of cool, in a geeky sort of way)

I hope that gives you much more than you expected by way of an answer - this is actually a tricky sort of expression, and it probably does things that the person who wrote it doesn't expect, or at least it has the potential to offer up some surprises.

wow impressed by such a detailed explanation. this does make it more clearer and easy to understand how it works.
thank you very much for the response
i really do appreciate the help!