Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does plus sign does here in string?

Tags:

java

string

I would like to know, what is the difference between two statements, these may be simple

      String ss="myname";
      char[] charArray = ss.toCharArray();
      for ( char character : charArray )
         {
            System.out.println( +character );//Statements are here what does plus refers here:

            System.out.println( character ); //Statements are here:

     } 

I got the output for the code no errors but little doubt on how it works? What happens here?

If you would down vote let me know the reason please.

like image 870
gks Avatar asked Dec 05 '25 20:12

gks


1 Answers

You have to remember that char is still a numeric type.

The + here is the unary plus, which does ... nothing. +x has the same value as x.

However +x is an int while x is a char in your case. So the effect it has in this case is that println(int) is called as opposed to println(char) effectively printing the numeric value of your char instead of the character represented by it.

The reason why +x is an int is that the Unary Operator + performs a so-called Unary Numeric Promotion which "normalizes" numeric values to the types int, long, float and double as appropriate.

An easier to understand version of that line would be

System.out.println((int) character);

It exists mostly for the language to be symmetric with regards to the unary minus (-x), which returns the negated value of its operand.

See this page (under "The Unary Operators") for details.

like image 181
Joachim Sauer Avatar answered Dec 08 '25 08:12

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!