When I run the following code it doesn't give me the output that I've been excepted. Consider the following code-snippet:
public class T
{
public static void main(String arg[])
{
char a='3';
System.out.println(a+a);
}
}
The output here is : 102
Could please anybody explain that to me ?
The + operator applies an implicit type cast which converts the two characters into their numerical ASCII representation which is 51.
So the expression
'3'+'3'
can also be seen as
51 + 51
which is 102.
I assume what you want to have is the result "33" which is not a char any more but a string. To achieve this you can for example simply implicitly convert the result of the expression into a string:
char c = '3';
string s = "" + c + c;
Another possibility would be to facilitate the StringBuilder class:
char c = '3';
String s = new StringBuilder().append(c).append(c).toString();
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