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
can also be seen as
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:Another possibility would be to facilitate the StringBuilder class: