Possible Duplicate:
char and int in Java
AsicII table :http://www.asciitable.com
The code below print out the Dec value of the corresponding char, for example "123" -> 49 50 51
public void foo(String str)
{
for(int x = 0; x < str.length(); x++)
{
int temp = str.charAt(x);
System.out.println(temp);
}
}
But I notice java is a strong type language, which mean every thing has to be cast in compile time, but how come the code knows how and when to convert char into the correct Dec value in AsicII table? Did I mess up any of the java/programming fundamental?
In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.
The character is only a representation of an integer value. For example, '0' can be written as 0x30 or 48 , 'a' is an alternative for 0x61 or 97 , etc. So the assignment is perfectly valid.
The char keyword is a data type that is used to store a single character.
You can assign a single Char in a Text or Code variable to a Char variable, as shown in the second line of the following code example. You can assign a numeric value to a Char variable, as shown in the third line of the following code example.
If we direct assign char variable to int, it will return ASCII value of given character. If char variable contains int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String.
A char
is simply an unsigned 16-bit number, so since it's basically a subset of the int
type, the JVM can cast it without any ambiguity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With