When testing this (with the below code), the ASCII value for char 'a'
is 10, and the ASCII value for char 'b'
is 11. However, when concatenating char 'a'
and char 'b'
, the result is 195.
There must be an error in my logic and/or understanding here... I do understand that chars cannot be concatenated as a String, but what would the ASCII int value of 195 then represent?
And what would be the usage of such a result?
public class Concatenated
{
public static void main(String[] args)
{
char char1 = 'a';
char char2 = 'b';
String str1 = "abc";
String result = "";
int intResult = 0;
Concatenated obj = new Concatenated();
// calling methods here
intResult = obj.getASCII(char1);
System.out.println("The ASCII value of char \"" + char1 + "\" is: " + intResult + ".");
intResult = obj.getASCII(char2);
System.out.println("The ASCII value of char \"" + char2 + "\" is: " + intResult + ".");
result = obj.concatChars(char1, char2);
System.out.println(char1 + " + " + char2 + " = " + result + ".");
result = obj.concatCharString(char1, str1);
System.out.println("The char \"" + char1 + "\" + the String \"" + str1 + "\" = " + result + ".");
} // end of main method
public int getASCII(char testChar)
{
int ans = Character.getNumericValue(testChar);
return ans;
} // end of method getASCII
public String concatChars(char firstChar, char secondChar)
{
String ans = "";
ans += firstChar + secondChar; // "+=" is executed last
return ans; // returns ASCII value
} // end of method concatChars
public String concatCharString(char firstChar, String str)
{
String ans = "";
ans += firstChar + str;
return ans;
} // end of method concatCharString
} // end of class Concatenated
The ASCII value of char "a" is: 10.
The ASCII value of char "b" is: 11.
a + b = 195.
The char "a" + the String "abc" = aabc.
getASCII
should be changed to this to return the correct ASCII value (and not the UNICODE value):
public int getASCII(char testChar)
{
// int ans = Character.getNumericValue(testChar); ...returns a UNICODE value!
int ans = testChar;
return ans;
} // end of method getASCII
I haven't changed the above code to reflect this, for posterity sake.
You are calling the wrong method: getNumericValue
interprets the char as a digit. For example, a hex digit A
has the value of 10.
What you should do instead is simply use the value of your char directly. Cast it to an int
, for example.
Character.getNumericValue()
returns the int value that the specified Unicode character represents.
According to the getNumericValue()
Javadocs: "The A tp Z letters both in uppercase and lowercase have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values."
However, when you add them in the concatChars()
method, the 2 values that are added are the ASCII values (97 + 98).
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