Unexplained parenthesise in Java
What do parenthesis do in Java other than type casting.
I'开发者_高级运维ve seen them used in a number of confusing situations, here's one from the Java Tutorials:
//convert strings to numbers
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
I only know only two uses for parenthesis, calls, and grouping expressions. I have searched the web but I can't find any more information.
In the example above I know Float.valueOF(arg)
returns an object. What effect does parenthesize-ing the object have?
Absolutely nothing. In this case they are not necessary and can be removed. They are most likely there to make it more clear that floatValue()
is called after Float.valueOf()
.
So this is a case of parenthesis used to group expressions. Here it's grouping a single expression (which does obviously nothing).
It can be shortened to:
float a = Float.valueOf(args[0]).floatValue();
float b = Float.valueOf(args[1]).floatValue();
which can then be logically shortened to
float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);
I dont believe they serve any purpose here. Maybe left over after some refactoring
None other than to confuse you. It's as good as saying
float a = Float.valueOf(args[0]).floatValue();
directly.
I suspect the programmer just found it more readable. I don't agree with him in this particular case, but often use parentheses to make it clearer. For example, I find
int i = 3 + (2 * 4);
clearer than
int i = 3 + 2 * 4;
The extra parentheses in your code sample do not add anything.
//Your example:
float a = (Float.valueOf(args[0]) ).floatValue();
// equivalent:
float a = Float.valueOf(args[0]).floatValue();
It could be that the original programmer had done something more elaborate within the parentheses and so had them for grouping, and neglected to remove them when simplifying the code. But trying to read intent into old source is an exercise in futility.
The extra space in args[0]) )
is pretty odd looking, too, as it is unmatched in the opening paren.
Here they are used for grouping. What's inside one of those expression if of type Float, so you can apply the method floatValue()
to the whole content of the parenthesis.
They could be removed here as there is no ambiguity. They would have been mandatory with an expression using another operator of higher preseance order. But according to the docs, there is no such operator, the dot/projector has highest priority. So they are really useless here.
Regards, Stéphane
精彩评论