3

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 ?

4

4 回答 4

4

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();
于 2012-07-11T09:31:58.563 回答
0

a+a is interpreted as a formula.

since ascii value of '3' is 51, 51 + 51 = 102.

于 2012-07-11T09:30:56.943 回答
0

It is just the sum of ascii values

于 2012-07-11T09:31:18.207 回答
0

you can see c+c as 51 + 51, because it takes the ascii code of '3'. if you want to print 33, then you can try this:

System.out.println(String

.format("%c + %c", c, c));

于 2012-07-11T09:51:27.763 回答