Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

language history - What is the purpose of Java's unary plus operator?

Java's unary plus operator appears to have come over from C, via C++.

int result = +1;   

It appears to have the following effects:

  • Unboxes its operand, if it's a wrapper object
  • Promotes its operand to int, if it's not already an int or wider
  • Complicates slightly the parsing of evil expressions containing large numbers of consecutive plus signs

It seems to me that there are better/clearer ways to do all of these things.

In this SO question, concerning the counterpart operator in C#, someone said that "It's there to be overloaded if you feel the need."

However, in Java, one cannot overload any operator. So does this unary plus operator exist in Java only because it existed in C++?

question from:https://stackoverflow.com/questions/2624410/what-is-the-purpose-of-javas-unary-plus-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The unary plus operator performs an automatic conversion to int when the type of its operand is byte, char, or short. This is called unary numeric promotion, and it enables you to do things like the following:

char c = 'c';
int i = +c;

Granted, it's of limited use. But it does have a purpose. See the specification, specifically sections §15.15.3 and §5.6.1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...