So I wanted to add a character to a string, and in some cases wanted to double that characters then add it to a string (i.e. add to it itself first). I tried this as shown below.
char s = 'X';
String string = s + s;
This threw up an error, but I'd already added a single character to a string so I tried:
String string = "" + s + s;
Which worked. Why does the inclusion of a string in the summation cause it to work? Is adding a string property which can only be used by characters when they're converted to strings due to the presence of a string?
char
+char
returns anint
so the compiler complains thatString string = (int)
, which is indeed wrong.To concatenate the chars, you can use the empty String (
""
) at the beginning so the+
operator will be forString
concatenation or use aStringBuilder
that can append chars as well.Note: the
char
variable iss
, notX
.It's because String + Char = String, similar to how an int + double = double.
Char + Char is int despite what the other answers tell you.
String s = 1; // compilation error due to mismatched types.
Your working code is (String+Char)+Char. If you had done this: String+(Char+Char) you would get a number in your string. Example:
Here X i'ts threated as a variable
You should use something as
Or
then
String string= x+y;
should work just fine, this is because you are concatening with the "+" sign, you could also useor
In Java,
char
is a primitive integral numeric type. As such, the operator + is defined to mean addition of two chars, with anint
result. The operator means concatenation only on strings. So one way to do it isThis will coerce the right-hand operand to a string, which is what you want to achieve.
A side point:
char
is the only unsigned primitive numeric type in Java and in one project of mine I specifically use it as such.When you do
char s = 'X'; String string = X + X;
Why not do this instead?
char s = 'X'; String string = s + s;
Adding in the "" changes the return type to a string. Leaving it out means the return type is a char which doesn't match.