Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concat char in sysout gives weird output?

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 ?

like image 329
raevilman Avatar asked Jan 27 '26 14:01

raevilman


1 Answers

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();
like image 181
marc wellman Avatar answered Jan 29 '26 03:01

marc wellman



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!