Integer arithmetic with character - java

I have a simple block of code, can someone explain to me why this acceptable in Java?
int a = 10;
int c = 'A' + (a -1);
System.out.println(c);
The result of this displayed in compiler is: 74.
So where exactly the values of seventies come from?
Thanks for your answers.

In Java a char can be (explicitly or implicitly) casted to int, it then uses the ASCII value associated to this character.
It your case, the seventies comes from the character 'A'. The ASCII value of this character is 65. So the system implicitly does the casting 'A' → 65. Your calculation does:
c = 'A' + (a-1)
↓
c = 65 + (10-1)
↓
c = 74

The ascii value of 'A' is 65. Check this link for complete reference. The conversion occurs through (implicit) widening the char datatype to int datatype using its unicode value, which in this case for 'A' is 65 (jls 5.6.1).

Char is implicitly converted into integer resulting 'A' = 65
so 65+9 = 74

When you assign value of one data type to another, the two types might not be compatible with each other. It should be casted to correct type:
There are 2 types:-
Widening or Automatic Type Conversion.
which casts in this sequence:
byte -> short -> int -> long -> float -> double
char -> int
example :
int i = 100; //i is 100
float f = i; // f is 100.0
Narrowing or Explicit
Conversion. which casts in this sequence:
double -> float -> long -> int ->short -> byte
example:
double d = 100.100; //d is 100.100
int i = (int)d; //i is 100
So, When a Character value is used in integer context. It is automatically casted to int.
In your case:
int a = 10;
int c = 'A' + (a -1); //c = 65 + (10-1)
'A' ascii value is 65, thus you get c = 74
Hope this helps.

Related

How to get ASCII representation of a character?

I have very basic question.
How is possible for int a = 'a' to give 97 in output.
Below is my code:
class myClass {
int last = 'a' ;
myClass () {
System.out.println(last );
}
}
You can have a look at this: Why are we allowed to assign char to a int in java?
Basically, you are assigning a char to your int. A char is technically an unsigned 16-bit character. That's why you can assign it to an int.
Hope this helps.
You can basically cast the char to the int and store it as int:
int a = (int)'a';
System.out.println(a); //prints 97
Since Java can do the basic castings from your type specifications, you do not need to explicity write casting even.
int a = 'a';
System.out.println(a); // prints 97
The output is the ASCII value of the character stored in last. The ASCII value of the character 'a' is 97, and hence the output on the console is 97.
you have to take 'a' as a char
char char1 = 'a';
then cast it to int
int num = (int) char1 ;

change ascii to string after adding number to it

I am trying to reform a string from ascii characters. I noticed when I break down ascii it matches the number with the ascii char, this changes when I tried to do (c+=c+0) on it as seen below, I tried to revert back to the original string but it doesn't seems to work. I was wondering does the ascii number change when you append it to a string?
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0);
char d = b.charAt(0);
System.out.println(d-=d+0); //blank
When you use + to sum a char with and int, the result will be promoted
to int.
When you use compound assignment operators +=, the result will be converted to left
operand data type(in this case, char)
This is what happens with your code:
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0); // result of c+c+0 is int 202, it is converted to char Ê
char d = b.charAt(0); // char d = Ê
System.out.println(d-=d+0); // result of d-(d+0) is int 0, it will be converted to null
It's not clear what you're trying to accomplish, but hopefully this example helps you figure out what's going on:
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); // e
System.out.println((int) c); // 101
char doubleC = (char) (c + c);
b.append(doubleC);
char d = b.charAt(0);
System.out.println((int) d); // 202
System.out.println(d - c); // 101
System.out.println((char) (d - c)); // e
}
Whether a character is printed as a letter or its ASCII value depends on its type. You can see that (int) c casts the character to its int ASCII value. Your approach of c+0 also does this but in a less intuitive way.
You also apparently want to "undo" your modification to c, but subtracting d-d always gives you 0. You need to store your value of c and subtract that from d.
+0s don't do anything because the character is underneath a number (so it's essentially like saying 101 + 0).
d-=d+0 evaluates to d = d - d + 0, so (because we're manipulating chars) d - d = 0
If you wanted to get c from d, you'd have to do d = d - c, because 'c' is the difference between the initial and the final value.
So no, the ASCII number of a character doesn't change, you're just not doing the reverse calculation as you should be.
It's like saying: x + y = z,
and then wondering why z - z != y.
You should be doing: z - x = y
#Edit
To add to your comment under pkpnd's answer - if you have only String b to work with, you'd still need to know the difference (i.e. by how much you increased/decreased the number) to reverse to the original chars.

How to turn a char(0-9) into int in java?

char c = '7';
int i = c - '0';
// Here value of '0' is 48 and c = '7' is 55. Therefore, i = 55 - 48 or 7;
More example:
String s = "453467"
Here, you may need the integer value located at 3rd cell.
You can first make a char variable. Then convert the char variable into an int.
char c = s.charAt(3);
int i = c - '0';
Sometimes this thing is needed for solving programming problems and to take the input from the user as an string.
Can you tell me the other ways to convert them. This will be very helpful for me to solve problems. THANKS!!
You want:
Character.getNumericValue(char ch)
Use the Integer class:
`int yourInt = Integer.parseInt(Character.toString('0'));

Converting characters to integers in Java

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;
}

What's the "java" way of converting chars (digits) to ints [duplicate]

This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 2 years ago.
Given the following code:
char x = '5';
int a0 = x - '0'; // 0
int a1 = Integer.parseInt(x + ""); // 1
int a2 = Integer.parseInt(Character.toString(x)); // 2
int a3 = Character.digit(x, 10); // 3
int a4 = Character.getNumericValue(x); // 4
System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);
(version 4 credited to: casablanca)
What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)
We are not converting the actual numerical value of the char, but the value of the representation.
Eg.:
convert('1') -> 1
convert('2') -> 2
....
How about Character.getNumericValue?
I'd strongly prefer Character.digit.
The first method. It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages. Of course, its error handling leaves something to be desired.
If speed is critical (rather than validation you can combine the result)
e.g.
char d0 = '0';
char d1 = '4';
char d2 = '2';
int value = d0 * 100 + d1 * 10 + d2 - '0' * 111;
Convert to Ascii then subtract 48.
(int) '7' would be 55
((int) '7') - 48 = 7
((int) '9') - 48 = 9
The best way to convert a character of a valid digit to an int value is below. If c is larger than 9 then c was not a digit. Nothing that I know of is faster than this. Any digits in ASCII code 0-9(48-57) ^ to '0'(48) will always yield 0-9. From 0 to 65535 only 48 to 57 yield 0 to 9 in their respective order.
int charValue = (charC ^ '0');

Categories

Resources