While using substring
will solve the problem (as in the answer of @Giorgi Tsiklauri), this doesn't point to the real hidden question posted that is:
Why a concatenation between chars is not the same of a concatenation of two strings of size 1 ?
That happens because the + symbol doesn't work as a concatenation in this context.
When you apply the +
operator on chars a conversion to int
is done before the operation. This operation is called Binary Numeric Promotion. From the second point in the JLS:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
So if you want to sum the string
value of the 0
char
and the string
value of the 1
char
you explicitly need to convert them in string as follow:
String room = "901";
String roomNumber = String.valueof(room.charAt(1)) + String.valueof(room.charAt(2));
If you do that the +
operator is considered a concatenation between strings and not as a sum between int.