Reputation: 33
How to connect char number with char number? My code is:
String room = "901";
// I want to a new String "01" so i do this
String roomNum = room.charAt(1) + room.charAt(2); // it's error
String roomNum = h.charAt(0).concat(h.charAt(1)); // error too
When I use String.valueOf()
it gives me an ASCII.
Upvotes: 2
Views: 540
Reputation: 11138
String room = "901";
//I want to a new String "01":
Use:
room.subString(1);
String#subString(int)
returns substring starting with int
and ending with the last character.
For more subString
overloads, have a look at String API.
If you want to concatenate two chars, you can do:
String room = "901";
char a = room.charAt(1);
char b = room.charAt(2);
String result = String.valueOf(a).concat(String.valueOf(b));
Otherwise, String roomNum = 'a'+'b';
will not compile, as the result of adding Java chars, shorts, or bytes is an int.
Beware, that char
represents an Unicode Character (in Java, 16-bits each). So, each char
value, under the hood, is encoded by numeric value, which is stored as a hexadecimal, decimal or other radix-system number. This is the main reason, why arithmetic operation on char
value promotes to int
.
Upvotes: 4
Reputation: 26946
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.
Upvotes: 2