Java - Problem with casting an int to char - java

I have a bit of confusion regarding casting from int to char data type, this is what i have;
int k = 3;
System.out.println((char)k + " " + k)
The output should have been
3 3
yet, i got this instead
3
Could somebody explains to me why is this happening?

The char '3' doesn't have a numeric value of 3. Its numeric value is 51.
This will print 3:
int k = 51;
System.out.println((char)k);
The char having a numeric value of 3 is an invisible character.
If you want to convert a single digit int to the corresponding char, you can write
int k = 3;
char three = (char)('0' + k);
System.out.println(three);

In addition to the other answers: If you know for sure that 0 <= k <= 9, you can use
System.out.println((char)(k + '0'));
to print the 'charified' version of your integer.
If k < 0 or k > 9, there isn't a single char (character) describing it. In that case, you'll have to use a string, which is basically an array of chars:
System.out.println(Integer.toString(k));

ASCII value of (char) 3 is : End of text
If you want to get the numeric value you need to use numeric value 51 which is the ASCII value of 3:
int k = 51;
System.out.println((char) k + " " + k);
This gives output :
3 51
Complete ASCII table can be found here

Related

Why does this equation return the answer it does?

I am Confused as to why this returns 1;
(char)('0' + 11) = ; why?
Full code below where ending = 1;
char[] ending;
char a = (char)('0' + 11/10);
ending = new char[]{a, (char)('0' + 11)};
System.out.println(ending);
Char value of '0' is 48.
48 + 11 = 59
Char value of 59 is ';'.
You can check char values in integer value in any ASCII Character Set in internet.
In Java, char can be use as a int, short, byte, long with values between 0 and 65535 without any casting.
A better explanation is found in: Java char is also an int?
You are assigning '1' to variable a. '0' + 11/10 => '0' + 1
You are assigning a two letter string to endings. Le first letter is a ('1') the second is a semi colon. ('0' + 11).

java converting char to int [duplicate]

Can someone please explain to me what is going on here:
char c = '+';
int i = (int)c;
System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));
This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?
Edit: Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?
Edit2: 43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?
Character.getNumericValue(c)
The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.
The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
This method returns the numeric value of the character, as a
nonnegative int value;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 if the character has no numeric value.
And here is the link.
As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:
int value = (int)c.charValue();
Try any one of the below. These should work:
int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');
From the Javadoc for Character#getNumericValue:
If the character does not have a numeric value, then -1 is returned.
If the character has a numeric value that cannot be represented as a
nonnegative integer (for example, a fractional value), then -2 is
returned.
The character + does not have a numeric value, so you're getting -1.
Update:
The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back.
http://en.wikipedia.org/wiki/ASCII
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}

How can an int be declared with ' ' and why is '2' == 50?

Question is: What gets displayed in console?
And I really have some problems with understanding.
Here is the code:
public static void felda(){
char[] felda = {'2',0x31,48};
for (int i = 0; i< felda.length; i++){
System.out.println(" : " + felda[i]);
}
System.out.println();
}
public static void feldb(){
int[] feldb = {'2',0x31,48};
for (int i = 0; i< feldb.length; i++){
System.out.println(" : " + feldb[i]);
}
System.out.println();
}
public static void feldc(){
int [] feldc = {'2',0x31,48};
for (int i = 0; i< feldc.length; i++){
System.out.println(" : " + (char) feldc[i]);
}
System.out.println();
}
So if I run in the Solution is:
: 2
: 1
: 0
: 50
: 49
: 48
: 2
: 1
: 0
So I don't understand how it is even possible to have an int definded with ' '.
And I find it very confusing how int feldb = '2' results in being 50 and int feldb=0x31 results in being 49.. dam this is all so confusing. I hope someone can enlighten me.
Edit: Why is char feldc = 48; resulting in being 0?
In Java, a char represents a Unicode character. But it's also in fact an unsigned integer, on 2 bytes, which can go from 0 to 216 - 1.
So,
char c = '2';
initializes c with the character '2'. And the numeric value of the character '2', in Unicode, is 50.
So, if you print it as a character, '2' will be printed. If you print it as a numeric value (as an int, using int c = '2'), 50 will be printed.
When doing
char feldc = 48;
you initialize feldc with the character whose numeric Unicode value is 48, and that character is the character '0'. It's thus equivalent to
char feldc = '0';
0x31 is a number written as an hexadecimal literal (that's what the 0xprefix means). When you write 31, the value is in decimal. It's equal to 1 * 100 + 3 * 101.
In hexadecimal, the base is 16 rather than 10. So 0x31 is equal to 1 * 160 + 3 * 161, which is equal to 49.
50 is the ASCII value of the '2' character. Defined like that its not the number 2.. its giving the ASCII value of a character. See this ASCII table and find the '2' char
http://ascii.cl/index.htm?content=mobile

why a single Java char variable can represent more than 65535 characters?

char in Java is 2 bytes, you can get its range by running below code:
System.out.println((Character.MIN_VALUE + 0) + "<char<" + (Character.MAX_VALUE + 0));
it's 0~65535
but I am confused that we can convert a integer value (>65535, like 70000) to char, and print it:
char testChar = (char) 70000;
char testChar2 = (char) 280388456;
System.out.println(testChar); //prints ᅰ
System.out.println(testChar2); //prints 捨
but why?
The 280388456 literal exceeds the char range and in the context of the char type it's actually 25448 (because 280388456 % 65536 = 25448). Which seems to be the index of 捨. Same goes for the other character.

How to convert ASCII code (0-255) to its corresponding character?

How can I convert, in Java, the ASCII code (which is an integer from [0, 255] range) to its corresponding ASCII character?
For example:
65 -> "A"
102 -> "f"
Character.toString ((char) i);
System.out.println((char)65);
would print "A"
String.valueOf(Character.toChars(int))
Assuming the integer is, as you say, between 0 and 255, you'll get an array with a single character back from Character.toChars, which will become a single-character string when passed to String.valueOf.
Using Character.toChars is preferable to methods involving a cast from int to char (i.e. (char) i) for a number of reasons, including that Character.toChars will throw an IllegalArgumentException if you fail to properly validate the integer while the cast will swallow the error (per the narrowing primitive conversions specification), potentially giving an output other than what you intended.
int number = 65;
char c = (char)number;
it is a simple solution
new String(new char[] { 65 })
You will end up with a string of length one, whose single character has the (ASCII) code 65. In Java chars are numeric data types.
An easier way of doing the same:
Type cast integer to character, let int n be the integer,
then:
Char c=(char)n;
System.out.print(c)//char c will store the converted value.
One can iterate from a to z like this
int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}
for (int i = 0; i < 256; i++) {
System.out.println(i + " -> " + (char) i);
}
char lowercase = 'f';
int offset = (int) 'a' - (int) 'A';
char uppercase = (char) ((int) lowercase - offset);
System.out.println("The uppercase letter is " + uppercase);
String numberString = JOptionPane.showInputDialog(null,
"Enter an ASCII code:",
"ASCII conversion", JOptionPane.QUESTION_MESSAGE);
int code = (int) numberString.charAt(0);
System.out.println("The character for ASCII code "
+ code + " is " + (char) code);
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));

Categories