tags:

views:

104

answers:

4

Does the following Java statement have an error in it? If so, what is it?

P *= x/y
A: 

It lacks a semicolon

If there's more errors, it depends on the types of P,x and y. They have to be number types

nos
Works for any numeric type.
Stefan Kendall
A: 

Looks perfectly fine apart from the aforementioned lack of a semicolon, and possible problems with type. That statement just divides x by y, multiplies that result by p, and places that value into p. p = (p*(x/y));

Twisol
A: 

If P is a primitive numeric data type (float, double, int, etc) it should probably be in lowercase. Uppercase variable names are typically reserved for constants in Java.

Also, since it translates to (P*(x/y)), if x and y where int and P were float or double, you might not get the answer you expect.

Grant Wagner
+3  A: 

If you're looking for "logical errors" and if the types are all integers, it's probably better to do:

P = (P*x)/y;

Because the current expression (IIRC) is equivalent to:

P = P*(x/y);

The latter expression may be less "accurate" if the types are integers. For example:

// evaluates to 3, as expected.
(5*3)/5;

However,

// Evaluates to 0 because of truncation.
5*(3/5);

So you need to be careful. In general division on integer expressions should be done as the final step.

Peter
Wouldn't your first example (5*3)/5 evaluate to 3?5*3=15 15/5 = 3
Mike Clark
@Mike COops, you're right, a careless mistake on my part, will correct it.
Peter