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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With